Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
Apr 2, 2001

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=
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date