当应用于 ostream_iterator 时,后缀运算符 return 是否左值?

Do postfix operators return lvalue when applied on ostream_iterator?

C++ Primer中给出的后续代码是不是不正确?

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

后缀运算符 returns 旧值,不是引用那么如何让它充当左值?

如有错误请指正

代码可以为:

*out_iter++ = e;

等于:

*(out_iter++) = e;

因此后缀增量首先发生,然后执行解引用。

来自 operator++:

ostream_iterator& operator++();
ostream_iterator& operator++( int );

Does nothing. They make it possible for the expressions *iter++=value and *++iter=value to be used to output (insert) a value into the underlying stream.

Return value

*this

来自operator*

ostream_iterator& operator*();

It returns the iterator itself, which makes it possible to use code such as *iter = value to output (insert) the value into the underlying stream.

Return value

*this

基本上,这意味着 *(out_iter++) returns 对迭代器本身的引用,因此可以以 *(out_iter++) = value.

的形式写入流

根据参考http://en.cppreference.com/w/cpp/iterator/ostream_iterator/operator_arith

ostream_iterator& operator++();

ostream_iterator& operator++( int );

但是ostream_iterator的运算符*和运算符++什么都不做,它们只return引用*this,所以你可以这样写

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

输出是一样的。