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!
}
CodePudding user response:
This is an obscure form of temporary lifetime extension. Normally you have to bind the temporary directly to the reference for it to work (e.g. for (auto x : foo())
), but according to cppreference, this effect propagates through:
- parentheses
( )
(grouping, not a function call), - array access
[ ]
, - member access
.
,.*
, - ternary operator
? :
- comma operator
,
. - any cast that doesn't involve a "user-defined conversion" (presumably uses no constructors nor conversion operators)
I.e. if a.b
is bound to a reference, the lifetime of a
is extended.