Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't a transform_view a borrowed_range?

Tags:

c++

std-ranges

For std::ranges, why isn't a transform_view a borrowed_range? Here is a simple example: https://godbolt.org/z/14K8Y1xMe and below:

#include <ranges>

void foo() {
    auto i = std::ranges::views::iota(10);
    auto t = i | std::ranges::views::transform([](auto v) {return v;});
    static_assert(std::ranges::borrowed_range<decltype(i)>);
    static_assert(std::ranges::borrowed_range<decltype(t)>);
}

I checked that the base is a borrowed range. Is there an issue with the function? The documentation doesn't say: https://en.cppreference.com/w/cpp/ranges/transform_view.

like image 290
rscohn2 Avatar asked May 22 '26 16:05

rscohn2


1 Answers

transform_view internally saves the callable as a member, and its iterator saves a pointer to transform_view for accessing the callable. So when transform_view is destroyed, the callable is also destroyed, which causes its iterator to access a dangling pointer.

That's why it's not borrowed_range.

like image 186
康桓瑋 Avatar answered May 24 '26 07:05

康桓瑋



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!