Can someone tell why test(2) object is destroyed after test_method() call?
#include<iostream>
#include<string>
using namespace std;
class test
{
int n;
public:
test(int n) : n(n)
{
cout << "test: " << n << endl;
}
~test()
{
cout << "~test: " << n << endl;
}
test & test_method()
{
cout << "test_method: " << n << endl;
return *this;
}
};
int main(int argc, const char *argv[])
{
cout << "main start" << endl;
const test &test1 = test(1);
const test &test2 = test(2).test_method();
cout << "main end" << endl;
}
Output is:
main start
test: 1
test: 2
test_method: 2
~test: 2
main end
~test: 1
test(2).test_method()returns a reference, which is bound totest2, and then the object to which it refers is destroyed at the end of the full expression, since it is a temporary object. That should not be a surprise.The real surprise is that
test1remains a valid reference, because it is directly bound to a temporary, and binding a temporary to a reference extends the lifetime of the temporary to that of the reference variable.You only have to note that in the
test(2)case, the temporary object isn’t bound to anything. It’s just used to invoke some member function, and then its job is done. It doesn’t “babysit” member functions, or in other words, lifetime extension isn’t transitive through all possible future references.Here’s a simple thought experiment why it would be impossible to actually have “arbitrary lifetime extension”:
We have no idea if
xremains valid beyond the first line.get_refcould be doing anything. If it’s implemented asT & get_ref(T & x) { return x; }, we might hope for magic, but it could also be this:It’s impossible to decide within the original translation unit whether anything needs to be extended or not. So the way the standard has it at present is that it’s an entirely trivial, local decision, just made when looking at the reference declaration expression, what the lifetime of the temporary object in question should be.