Is the C++ code below well-formed? Will the std::string
get destroyed before or after the function finishes executing?
void my_function(const char*);
...
my_function(std::string("Something").c_str());
4
1 Answer
1
Reset to default
Highest score (default)
Trending (recent votes count more)
Date modified (newest first)
Date created (oldest first)
Will the std::string get destroyed before or after the function finishes executing?
Temporary objects are destroyed (with some exceptions, none relevant here) at the end of the full-expression in which they were materialized (e.g. typically the end of an expression statement).
The std::string
object here is such a temporary materialized in the full-expression that spans the whole my_function(std::string("Something").c_str());
expression statement. So it is destroyed after my_function
returns in your example.
Your Answer
Sign up or log in
Post as a guest
Required, but never shown
Post as a guest
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.
Not the answer you're looking for? Browse other questions tagged
or ask your own question.
or ask your own question.
But seriously, the temporary
string
will die at the end of the expression. That'll be after the function call. So long asmy_function
doesn't store that pointer somewhere with a longer life you're good.11 hours ago
Some nearly-canonical documentation.
11 hours ago
I'm surprised I can't find a good duplicate of this. Closest I got is this.
11 hours ago
Here's the canonical documentation and some supporting information on when the expression ends. Took longer to find than I thought it would. But go with the stuff at CPP reference. I reads like it was translated from Martian, but in a way that's because it was.
11 hours ago
|