|
Boost : |
Subject: Re: [boost] [Foreach] Supporting range adaptors for temporary containers
From: Michel MORIN (mimomorin_at_[hidden])
Date: 2011-04-21 18:43:39
Jeffrey Lee Hellrung, Jr. wrote:
> On Thu, Apr 21, 2011 at 1:07 PM, Michel MORIN <mimomorin_at_[hidden]> wrote:
>
>> Sometimes it is convenient to apply range adaptors to a temporary container
>> and iterate over it:
>>
>> // `using namespace boost::adaptors;` is assumed
>> BOOST_FOREACH(auto x, std::string("Hello, world!") | reversed) {...}
>>
>> However, the lifetime of the temporary container ends before the loop body
>> begins.
>
> I believe BOOST_FOREACH correctly accounts for rvalue range expressions.
> See second-to-last example from
>
> http://www.boost.org/doc/libs/1_46_1/doc/html/foreach.html
>
> Does this address your concern?
No.
extern std::vector<float> get_vector_float();
BOOST_FOREACH( float f, get_vector_float() )
{
...
}
This code is OK. A temporary range returned by `get_vector_float()` is
copied. In C++0x range-based for, the temporary range is bound to an
rvalue reference and its lifetime is extended.
extern std::vector<float> 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!
Regards,
Michel
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk