I have issues understanding when does a type deduce to std::ranges::dangling . For example I have function that returns a prvalue to a standard container, say std::vector which I use directly as an argument to std::ranges::sort, then I expect to get a compilation error regarding std::ranges::dangling when I attempt to dereference the iterator, which is what I get :

#include <vector>
#include <algorithm>

auto get_data(){
    return std::vector<int>{1, 2, 99, 5, 9, 4};
}

auto get_sorted(){
    return std::ranges::sort(get_data());
}


int main(){
    auto it = get_sorted();
    *(it-1); //Compiler Error because it is a std::ranges::dangling iterator
}

However if I change the get_sorted function above slightly to first capture the vector in a named variable and use that instead to return the result of std::ranges::sort, then I don’t get a dangling iterator, in the main even though the allocated vector in named variable should have been destroyed after the function get_sorted returned :

auto get_sorted(){
    auto vec = get_data();
    return std::ranges::sort(vec);
}


int main(){
    auto it = get_sorted();
    *(it-1); //Okay result  = 99
}

Even if I change get_sorted to use a named variable based container declared locally, I get a behavior where the compiler doesn’t complain about dangling iterator on being dereferenced in its caller (say main function) .

//doesn't return a std::ranges::dangling
auto get_sorted(){
    std::vector<int> vec{1, 2, 99, 5, 9, 4};
    return std::ranges::sort(vec);
}

and when I pass a prvalue vector to the std::ranges::sort algorithm, I again get a std::ranges::dangling as expected

//returns a std::ranges::dangling
auto get_sorted(){
    std::vector<int> vec{1, 2, 99, 5, 9, 4};
    return std::ranges::sort(std::vector<int>{1, 2, 99, 5, 9, 4});
}

For the cases where I don’t get an error by compiler regarding std::ragnes::dangling I do observe a runtime error when I compile with fSanitize=address option which is likely because the vectors that were allocated in named variable within the get_sorted function went out of scope as soon as the latter function returned.

However I would like to understand why using named variable within a function changes the return type of get_sorted function and possible a guide on how to use temporaries and prvalues containers correctly to get std::ranges::dangling whenever possible.