Question

According to the C++ reference, the requirement of a forward iterator is that it supports the post-increment operator (i.e. iterator operator++(int) and

I am wondering if it's safe to disallow this operation on a custom forward iterator, i.e.

custom_iterator operator++(int) = delete; // disallow post-increment, i.e. it++
custom_iterator operator++() { ... } // we only define pre-increment, i.e. ++it

and assume that STL will never call it++ on such a custom iterator it, when it is passed as an argument to a STL generic algorithm such as copy, sort, fill etc.?

A quote from the official C++11 standard regarding this matter would be the most useful one, but answers such as "most implementation do this and that" are also welcome.

Était-ce utile?

La solution

All iterators must be both pre- and post-incrementable. This is part of the requirements for both input and output iterators. See C++11 §24.2[iterator.requirements] Tables 107 and 108. It's rather hard to quote the tables, but in both tables, the expression ++r and r++ must be valid for an iterator r.

So, no. If you are implementing a new iterator type, instances of that type must be both pre- and post-incrementable, and all STL algorithms and any other functions that take iterators may assume post-incrementability.

Because iterators must also be copy constructible, it is generally trivial to implement the postincrement operator in terms of the preincrement operator. For example,

MyIterator operator++(int)
{
    MyIterator original(*this);
    ++*this;
    return original;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top