Boost logo

Boost :

Subject: Re: [boost] [Foreach] Supporting range adaptors for temporary containers
From: Michel MORIN (mimomorin_at_[hidden])
Date: 2011-04-22 02:34:45


Vicente BOTET wrote:
>> extern std::vector get_vector_float();
>> BOOST_FOREACH( float f, get_vector_float() | reversed )
>> {
>> ...
>> }
>>
>> But this code results in a dangling reference. ONLY a temporary
>> iterator_range returned by `get_vector_float() | reversed` is
>> copied (or bound to an rvalue reference in C++0x range-based for).
>> The lifetime of `get_vector_float()` ends before the loop body begins!
>
> Sorry if my question is innocent. Would the functional form of the adaptor work?
>
> extern std::vector get_vector_float();
> BOOST_FOREACH( float f, reverse(get_vector_float()) )
> {
> ...
> }

No. `boost::adaptors::reverse(rng)` is a synonym of
`rng | boost::adaptors::reversed` and so this does not work properly.
Only a temporary iterator_range is copied and the lifetime of a temporary
container ends before the loop body begins!

Regards,
Michel


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk