ARTICLE AD BOX
#include <iostream>
#include <vector>
#include <ranges>
#include <algorithm>
auto get_vec()
{
return std::vector<int> { 1, 2, 3, 4, 5, 6, 7 };
}
int main()
{
// 1) As expected, returns: std::ranges::dangling
auto it = std::ranges::max_element(get_vec());
// 2) Is lifetime extended for the view, or is it dangling (undefined behavior)
auto vw = get_vec() | std::ranges::views::take(3);
// prints first 3 ints
std::ranges::for_each(vw, [](const int &i) { std::cout << i << '\n'; });
}
In statement 1), the returned type is ranges::dangling
This seems correct because get_vec() returns an rvalue and as such, the iterator points at a value that no longer exists, i.e. dangling.
For the same reason, I am expecting undefined behavior in statement 2) because the view is based on the same rvalue return object.
However, it works fine and I cannot find anything wrong with it both with valgrindandlibasan.
The question is whether this code triggers undefined behavior?
Compiler is gcc 16.0.1
9594 silver badges13 bronze badges
3
