Home > Blogs > 30 C++ Tips in 30 Days: Tip # 28 the lifetime of a temporary object bound to a reference

30 C++ Tips in 30 Days: Tip # 28 the lifetime of a temporary object bound to a reference

By  Dec 24, 2007

Topics: Programming, C/C++

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 temporary
void f()
{
 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:

void func()
{
 string & ref=string("5");
 int x;
 cout<<ref.c_str()<<endl;
 x=atoi(ref.c_str());
 cout<<x<<endl;
}//ref goes out of scope, temp string is destroyed here

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.

Other Things You Might Like

Xamarin Unleashed

Xamarin Unleashed