Search code examples
c++iterator

Input Iterator - Star and Postfix-Operator


Is it valid to do this on an input iterator *it++ ?

I understand the code as follow, that it dereference the iterator and gives me the value and then step one ahead.

In the c++ reference the * operator is lower than the postfix operator: http://en.cppreference.com/w/cpp/language/operator_precedence

But I read this style is bad practice. Why?


Solution

  • Is it valid to do this on an input iterator *it++?

    Yes, that is valid. The iterator will be incremented, its previous value will be returned, and you will dereference that returned iterator.

    But I read this style is bad practice. Why?

    Consider these two implementations I've just pulled out of some graph code I wrote a while back:

    // Pre-increment
    BidirectionalIterator& operator++()
    {
        edge = (edge->*elem).next;
        return *this;
    }
    
    // Post-increment
    BidirectionalIterator operator++(int)
    {
        TargetIterator oldval(list, edge);
        edge = (edge->*elem).next;
        return oldval;
    }
    

    Notice that for post-increment, I need to first construct a new iterator to store the previous value which will be returned.

    If it's simple and clear to write your program to make use of pre-increment, there may be better performance, less work for the compiler to do, or both.

    Just don't go crazy on this (for example, rewriting all your loops)! That would likely be micro-optimization. However, the reason people say it's good practice is that if you get into a habit of using pre-increment as default then you get (potentially) better performance by default.