简体   繁体   中英

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; } [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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM