TheLogicGuy
TheLogicGuy

Reputation: 691

Why does the STL Output Iterator allow only once assignment?

As mentioned here: http://www.cplusplus.com/reference/iterator/OutputIterator/

Can be dereferenced as an lvalue (if in a dereferenceable state). It shall only be dereferenced as the left-side of an assignment statement. Once dereferenced, its iterator value may no longer be dereferenceable.

Next to it there is an example of a valid expression:

*a = t

After this expression (the dereference) I can't derefernce again.
I don't understand why for example I can't do:

*a = t2

After the first expression.

Upvotes: 1

Views: 86

Answers (2)

tso
tso

Reputation: 4914

Other iterator types, including Trivial Iterator and Input Iterator, define the notion of a value type, the type returned when an iterator is dereferenced. This notion does not apply to Output Iterators, however, since the dereference operator (unary operator*) does not return a usable value for Output Iterators. The only context in which the dereference operator may be used is assignment through an output iterator: *x = t. Although Input Iterators and output iterators are roughly symmetrical concepts, there is an important sense in which accessing and storing values are not symmetrical: for an Input Iterator operator* must return a unique type, but, for an Output Iterator, in the expression *x = t, there is no reason why operator= must take a unique type. Consequently, there need not be any unique "value type" for Output Iterators.

Upvotes: 0

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136208

One reason is that output iterators are used for output streams, such as terminals, pipes and sockets. Once data have been written into the stream, it is considered sent elsewhere and thus cannot be changed.

Upvotes: 3

Related Questions