About the lifecycle of string.c_str ()
From clause 12.2 / 3 of the C ++ 11 standard:
[...] Temporary objects are destroyed as the last step in evaluating a complete expression (1.9) that (lexically) contains the point at which they were created. This is true even if the evaluation ends up throwing an exception. [...]
This means that the temporary created in the expression containing the call func()
will work until the function call returns.
On the other hand, the lifetime of the temporary in the first piece of code will end before being called func()
, but str
will hang. This will result in Undefined Behavior.
source to share
In both cases, the object string
is temporary, destroyed at the end of the statement.
In the first case, it str
ends up freezing - indicates memory that is being managed temporarily string
, but which is now destroyed. Doing anything with this is an error giving undefined behavior.
In the second case, the temporary string
will not be destroyed until the function returns. So it's okay if the function doesn't hold a pointer to something that can still be used later.
source to share
The difference is that the first one creates a temporary object string
, which is destroyed at the end of the first statement, so str
it becomes a dangling pointer. The second also creates a temporary one, but it exists at the time of the call func
, because the temporary object will not be destroyed until the call returns func
.
source to share