I'm trying to understand lifetime extension guarantees in C++. Can someone explain why the usage of different types of parentheses below yields differing results in terms of when the temporary object destructor is invoked?
#include <iostream>
struct X {
X() {
std::cout << __PRETTY_FUNCTION__ <<"\n";
}
~X() {
std::cout << __PRETTY_FUNCTION__ <<"\n";
}
};
struct Y {
X &&y;
};
int main() {
Y y1(X{});
std::cout << "Here1\n";
Y y2{X{}};
std::cout << "Here2\n";
}
Output
X::X()
X::~X()
Here1
X::X()
Here2
X::~X()
Since C++20:
That means for
Y y2{X{}};, the lifetime of temporary will be extended asy2(and its member); while forY y1(X{});it won't, the temporary will be destroyed after full expression immediately.