The Lifetime of Temporary Objects

Temporary objects, or unnamed objects, are created as a result of expressions requiring a temporary object or when the user instantiates them explicitly. If the temporary object is not bound to a reference and it isn’t used as an initializer of a named object, it is destroyed at the end of the full expression in which it was created. A full expression is one that is not a subexpression of another expression. In other words, the temporary is destroyed when the nearest semicolon is encountered. For example:

 void func( const string & s);int main(){ func(string()); // create a temp string, pass it to func}


In the call of func(), the user explicitly creates a temporary string object which is bound to a reference and is passed to func(). It is a safe operation because the temporary string is destroyed only at the end of the full-expression, i.e., when func() has returned. Likewise, the following expression creates a temporary string that is immediately destroyed after the full expression has been evaluated:

 string s1=

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: