Why should C ++ iterators return a link?

I implement an iterator that iterates over the results of a generator function, and not over the data structure in memory, such as a vector or map.

Reading through the final working draft for C ++ 17 §27.2.3, the return type of the dereference operator for the input iterator (and, as a rule, most other iterators) should be a reference. This is normal for elements that exist in the data structure, an iterator iteration. However, since I do not use a data structure and compute each element when the dereference operator is called, I do not have a valid return reference; the computed element is destroyed when the operator returns. To get around this, I save the calculation result in the iterator itself and return a link to the saved result. This works fine for my use, but has its problems when used with arbitrary custom types.

I can understand that iterators are allowed to return a link, but why would this be a requirement for non-mutating iterators? Didn't the authors of the standard consider generators and transformations on the fly to be valid use cases for iterators? Will returning a value instead of referencing a constant cause any actual harm?

[edit]: I ask more out of curiosity about why the standard is written as it is, since I already have a great workaround.

+4
source share
1 answer

, glvalue ( ). , "reference, T", , reference .

, gl:

X , reference T; X , reference const T,

, , " ", , . (, std::for_each std::all_of).

+4

Source: https://habr.com/ru/post/1687095/


All Articles