Boost logo

Boost :

Subject: Re: [boost] [range] Question about adapted range safety given C++11 auto
From: Nathan Ridge (zeratul976_at_[hidden])
Date: 2012-04-22 16:16:15


> http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3350.html claims:
>
> "Boost's range library focuses on defining a set of Range concepts
> that allow Containers to be Ranges. Because Containers are
> heavy-weight, this forces Boost to use references for all of their
> uses of Ranges, including Ranges that are captured by Range Adapters.
> This worked fine in C++98, where users couldn't name the types of the
> Range Adapters in order to declare local variables, but with C++11's
> auto keyword, users can now save adapted ranges. Since Boost's adapted
> ranges capture references to their arguments, which can be
> temporaries, this is no longer a safe design."
>
> Is this claim correct? If so, what's the real-world impact?

I have run into issues related to this a few times. To give an example,
the following works:

for (T e : function_returning_vector())
{
   ...
}

because the temporary vector is bound to a const reference, so its lifetime
is extended to the end of the loop. However, the following does not:

for (T e : function_returning_vector() | filtered(pred))
{
   ...
}

because while the filtered range's lifetime is extended to the end of the
loop, the underlying vector dies before the first iteration.

Interestingly (and somewhat inconsistently), if you do it with for_each
it works:

for_each(function_returning_vector() | filtered(pref), [&]()
{
   ...
};

because the temporary vector lives until the end of the statement, and
the statement in this case is the whole loop.

Regards,
Nate
                                               


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