Reputation: 1075
I wonder if the void func(const char *str);
refer to a valid str
if I wrote as follow:
auto str = string("hello").c_str();
func(str);
How is it different from code below?
func(string("hello").c_str())
Upvotes: 3
Views: 969
Reputation: 126412
From Paragraph 12.2/3 of the C++11 Standard:
[...] 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. [...]
This means that the temporary created within the expression that contains the call to func()
will live until function call returns.
On the other hand, the lifetime of the temporary in the first code snippet will end up before func()
is invoked, and str
will be dangling. This will result in Undefined Behavior.
Upvotes: 3
Reputation: 76235
The difference is that the first creates a temporary string
object that gets destroyed at the end of the first statement, so str
becomes a dangling pointer. The second also creates a temporary, but it exists throughout the call to func
because the temporary object doesn't get destroyed until after the call to func
returns.
Upvotes: 6
Reputation: 254421
In both cases, the string
object is a temporary, destroyed at the end of the statement.
In the first case, str
ends up dangling - pointing to memory that was managed by the temporary string
, but which has now been destroyed. Doing anything with it is an error, giving undefined behaviour.
In the second case, the temporary string
is not destroyed until after the function returns. So this is fine, as long as the function doesn't keep hold of the pointer for something else to use later.
Upvotes: 8