Lifetime of the returned range-v3 object in C++


I want to make a function that works like np.arange(). With range-v3, the code is

auto arange(double start, double end, double step){
    assert(step != 0);
    const auto element_count = static_cast<int>((end - start) / step) + 1;

    return ranges::views::iota(0, element_count) | ranges::views::transform([&](auto i){ return start + step * i; });

and to use it,

auto range = arange(1, 5, 0.5);
for (double x : range){
    std::cout << x << ' '; // expect 1 1.5 2 2.5 3 3.5 4 4.5 5

However, the result told me a dummy value. I think the lifetime of returned range object is expired, and I found that by making them to vector can pass the result well. (And it will cause overhead for constructing vector.)

Is there any way to return range itself without expired lifetime ?


You fell victim to Undefined Behaviour due to capturing of local variables via [&].

If you capture by value [start, step](auto i){ return start + step * i; }, the code will work correctly.

Note that views are always non-owning, can be copied around and are generally O(1) in their storage. Since iota is a generating view and stores its full state inside itself, the code is safe.

Answered By – Quimby

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.