Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2002-08-15 09:16:38

From: "Peter Dimov" <pdimov_at_[hidden]>

> "[4] The result type of operator[]() is value_type instead of reference
> might be expected. There are two reasons for this choice. First, the C++
> standard only requires that the return type of an arbitrary Random Access
> Iterator's operator[]be ``convertible to T'' (Table 76), so when adapting
> arbitrary base iterator we may not have a reference to return. Second,
> more importantly, for certain kinds of iterators, returning a reference
> could cause serious memory problems due to the reference being bound to a
> temporary object whose lifetime ends inside of the operator[]."
> First: the operational semantics of a[n] are *(a + n), and that returns a
> reference.


> Second: could you please show an example?

Any iterator which stores the referent of its operator* within the iterator
object is an example that causes serious memory problems if operator[]
returns a reference.

That's a legal technique for random-access iterators.


           David Abrahams * Boost Consulting
dave_at_[hidden] *

Boost list run by bdawes at, gregod at, cpdaniel at, john at