Boost logo

Boost :

Subject: Re: [boost] [Foreach] Supporting range adaptors for temporary containers
From: Vicente BOTET (vicente.botet_at_[hidden])
Date: 2011-04-22 02:08:04


> Message du 22/04/11 00:44
> De : "Michel MORIN"
> A : boost_at_[hidden]
> Copie à :
> Objet : Re: [boost] [Foreach] Supporting range adaptors for temporary containers
>
> Jeffrey Lee Hellrung, Jr. wrote:
> > On Thu, Apr 21, 2011 at 1:07 PM, Michel MORIN 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 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 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()) )
{
...
}

Best,
Vicente


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