devxlogo

The Lifetime of Temporary Objects

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=

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist