Search code examples
c++11postfix-operator

Do postfix operators return lvalue when applied on ostream_iterator?


Isn't the foll code given in C++ Primer incorrect ?

ostream_iterator<int> out_iter(cout, " ");
for (auto e : vec)
    *out_iter++ = e;  // the assignment writes this element to cout
cout << endl;

The postfix operator returns the old value, not a reference then how can it be made to act as an lvalue ?

Please correct if I am wrong


Solution

  • According to reference http://en.cppreference.com/w/cpp/iterator/ostream_iterator/operator_arith

    ostream_iterator& operator++();

    ostream_iterator& operator++( int );

    but operator* and operators ++ of ostream_iterator do nothing, they only return reference to *this, so you can write this

    for (auto e : vec)
        out_iter = e;  // the assignment writes this element to cout
    

    and the output will be the same.