samedi 25 novembre 2017

std::reverse_iterator strange behaviour (UB?)

I created a pseudo-container class (it does not contain any elements) and an iterator class for this container. The following code always outputs '776' on my system (my compiler is GCC 5.4.0)

#include <iostream>
#include <iterator>

class Container
{
public:
  class Iterator;
  Container()=default;
  Container::Iterator begin();
  Container::Iterator end();
};

class Container::Iterator: public std::iterator<std::bidirectional_iterator_tag, size_t>
{
public:

    Iterator(size_t n);
    size_t& operator*();
    Container::Iterator& operator--();
    const Container::Iterator operator--(int);

    bool operator==(const Container::Iterator& rhs) const;
    bool operator!=(const Container::Iterator& rhs) const;
  private:
    size_t n_;
};



Container::Iterator Container::end()
{
  return Iterator(777);
}





Container::Iterator::Iterator(size_t n):
  n_(n)
{
}

size_t& Container::Iterator::operator *()
{
  return n_;
}

Container::Iterator& Container::Iterator::operator--()
{
  n_--;
  return *this;
}

const Container::Iterator Container::Iterator::operator--(int)
{
  Container::Iterator oldVal = *this;
  n_--;
  return oldVal;
}

int main()
{
 Container cont;
 std::reverse_iterator<Container::Iterator>revit(cont.end());
 //as cppreference says, "For a reverse iterator r constructed from an iterator i, the relationship &*r == &*(i-1) is always true...", so I expect that the output must be the same as if I used instead next commented line, and it does so on my system
  // auto it = cont.end(); it--; std::cout << *it << std::endl;
  std::cout << *revit << std::endl;
 return 0;
}

But when I use any online compiler (with C++11 support), this code outputs just '0' (except one Clang version, then the output is some 'random' big number)

I can't figure out, where is my error?

Aucun commentaire:

Enregistrer un commentaire