Temporary objects – when are they created, how do you recognise them in code?

All your questions boil down to a rule in C++ which says that a temporary object (one that has no name) cannot be bound to a non-const reference. (Because Stroustrup felt it could provoke logical errors…)

The one catch, is that you can invoke a method on a temporary: so X(1).modify() is fine but f7(X(1)) is not.

As for where the temporary is created, this is the compiler job. The rules of the language precise that the temporary should only survive until the end of the current full-expression (and no longer) which is important for temporary instances of classes whose destructor has a side-effect.

Therefore, the following statement X(1).modify(); can be fully translated to:

{
    X __0(1);
    __0.modify();
} // automatic cleanup of __0

With that in mind, we can attack f5() = X(1);. We have two temporaries here, and an assignment. Both arguments of the assignment must be fully evaluated before the assignment is called, but the order is not precise. One possible translation is:

{
    X __0(f5());
    X __1(1);
    __0.operator=(__1);
}

(the other translation is swapping the order in which __0 and __1 are initialized)

And the key to it working is that __0.operator=(__1) is a method invocation, and methods can be invoked on temporaries 🙂

Leave a Comment