BeginEnd
BeginEnd

Reputation: 343

Modyfying temporary object

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

Upvotes: 4

Views: 104

Answers (2)

Jirka Hanika
Jirka Hanika

Reputation: 13529

Because the C++ standard requires this behavior. Give the object a name if you want it to persist. It will persist as long as the name.

Edit: You your example, test1 is the name that you gave to the first object, whereas the second object has obtained no name at all, and so it does not outlast evaluation of the expression.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476980

test(2).test_method() returns a reference, which is bound to test2, 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 test1 remains 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":

extern T & get_ref(T &);

{
    T const & x = get_ref(T());

    // stuff

    // Is x still valid?
}

We have no idea if x remains valid beyond the first line. get_ref could be doing anything. If it's implemented as T & get_ref(T & x) { return x; }, we might hope for magic, but it could also be this:

namespace { T global; }
T & get_ref(T & unused) { return global; }

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.

Upvotes: 6

Related Questions