Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifetime of temporaries

The following code works fine, but why is this correct code? Why is the "c_str()" pointer of the temporary returned by foo() valid? I thought, that this temporary is already destroyed when bar() is entered - but it doesn't seem to be like this. So, now I assume that the temporary returned by foo() will be destroyed after the call to bar() - is this correct? And why?

std::string foo() {   std::string out = something...;   return out; }  void bar( const char* ccp ) {   // do something with the string.. }  bar( foo().c_str() ); 
like image 932
Frunsi Avatar asked Nov 18 '10 11:11

Frunsi


People also ask

What is a lifetime in C++?

C/C++ use lexical scoping. The lifetime of a variable or object is the time period in which the variable/object has valid memory. Lifetime is also called "allocation method" or "storage duration."

What is lifetime of an object?

In object-oriented programming (OOP), the object lifetime (or life cycle) of an object is the time between an object's creation and its destruction.

How can you extend the life time of an object?

The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details.

What happens when a reference goes out of scope?

The the reference ends its lifetime before the object does, then... well, nothing happens. The reference disappears, the object continues to live.


2 Answers

A temporary object is destroyed when the full-expression that lexically contains the rvalue whose evaluation created that temporary object is completely evaluated. Let me demonstrate with ASCII art:

____________________   full-expression ranges from 'b' to last ')' bar( foo().c_str() );      ^^^^^          ^        |            |      birth       funeral 
like image 102
fredoverflow Avatar answered Oct 17 '22 01:10

fredoverflow


$12.2/3- "Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception."

The lifetime of the temporary returned by foo() extends until the end of the full expression where it is created i.e. until the end of the function call 'bar'.

EDIT 2:

$1.9/12- "A full-expression is an expression that is not a subexpression of another expression. If a language construct is defined to produce an implicit call of a function, a use of the language construct is considered to be an expression for the purposes of this definition."

like image 22
Chubsdad Avatar answered Oct 17 '22 02:10

Chubsdad