Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 284
gk2 Avatar asked Oct 15 '25 20:10

gk2


1 Answers

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.

like image 156
Quimby Avatar answered Oct 17 '25 09:10

Quimby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!