Consider the following code:
class Abc
{
public:
Abc() { std::cout << " ABC::ABC\n"; }
Abc& doIT() { std::cout << " Abc::doIT\n"; return *this; }
~Abc() { std::cout << " ABC::~ABC\n"; }
};
Usage:
const Abc& ap = Abc().doIT(); //After this line ap references garbage
My question is why temp Abc destroyed and not binded to ap ?
Lifetime extension only happens when you bind a reference to a prvalue directly .
In your case, the type of the expression Abc().doIT()
is Abc&
(an lvalue reference), not Abc
.
This is not a prvalue, so lifetime extension does not apply.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.