in this page Range-based for loop on a temporary range, user Barry mentioned that the following is not affected by the destroyed temporary object, and I tested member v indeed exists throughout the for loop(as the destructor ~X didn’t get called throughout the for loop). Can anyone explain why for me please? Many thanks!
struct X {
std::vector<int> v;
~X()
{
}
};
X foo()
{
return X();
}
for (auto e : foo().v) {
// ok!
}
>Solution :
According to cppreference, a range-based for loop is equivalent to:
{
auto && __range = range-expression ;
for (auto __begin = begin-expr, __end = end-expr; __begin != __end; ++__begin)
{
// ...
}
}
and in your example, the temporary returned by foo is part of range-expression (in fact it is range-expression, pretty much) so its lifetime is that of the entire loop. After all, a range-based for loop would be of little value if it worked any other way.