Save 40% on books and eBooks + 70% on videos now through May 31*—use code PROGRAM. Shop now.
A temporary object is usually destroyed immediately after the entire expression in which it was created has been fully evaluated. There's an exception to this rule though. When the temporary object is bound to a reference, the lifetime of that object is extended. Learn here about this exception and the rational behind it.
A temporary object is created when the implementation needs one, or when the program explicitly instantiates such a temporary:
string s2=s1+s0; // s1+s0 results in a
string(); //explicit instantiation of temporary
The first temporary is created when the subexpression s1+s0 is evaluated. That temporary is destroyed conceptually once the assignment to s2 has been completed. The second temporary created inside the body of func() is destroyed immediately after the statement which instantiates it has been fully evaluated. In both case, the following generalization is true: Temporary objects are destroyed as the last step in evaluating the full-expression that contains the point where they were created.
And yet, when a temporary object is bound to a reference, the rule changes. To prevent dangling references, C++ guarantees that the temporary to which the reference is bound shall persist for the lifetime of the reference variable. Let's look at an example:
string & ref=string("5");
}//ref goes out of scope, temp string is destroyed here
Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.