Boost logo

Boost Users :

Subject: Re: [Boost-users] [range] strange behaviour with range-based for loop and adaptors
From: Sebastian Redl (sebastian.redl_at_[hidden])
Date: 2011-03-12 05:29:51


On 12.03.2011, at 11:12, Nathan Ridge wrote:

>
> Hello,
>
> I am experiencing some strange behaviour when using adaptors with a range-based for loop.
>
> Here's what I'm trying:
>
> #include <vector>
> #include <iostream>
> #include <boost/foreach.hpp>
> #include <boost/range/adaptor/transformed.hpp>
>
> std::vector<int> f()
> {
> return std::vector<int>{1, 2, 3, 4};
> }
>
> int add1(int x) { return x + 1; }
>
> int main()
> {
> for (int i : f() | boost::adaptors::transformed(add1))
> std::cout << i << ' ';
> std::cout << '\n';
> }
>
>
> The output is 1 3 4 5, instead of the 2 3 4 5 that I would expect.
>
> Is there something funny going on with temporaries?
> Does the temporary returned by f() not stick around for the duration of the loop?

That's very likely the reason. You could test that by making your own container wrapper that writes messages on construction and destruction.

Sebastian


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net