问题
Lets take a look to this two functions:
std::string get_string()
{
std::string ret_value;
// Calculate ret_value ...
return ret_value;
}
void process_c_string(const char* s)
{
std::cout << s << endl;
}
And here are two possible calls of process_c_string
with argument returned by get_string
.
Without binding const reference to the returned object of
get_string
.process_c_string(get_string().c_str());
With binding const reference to the returned object of
get_string
.const std::string& tmp_str = get_string(); process_c_string(tmp_str.c_str());
I know that second way is valid, but what about the first one, what does standard say about this case? Will the temporary object returned by get_string
be deleted before process_c_str
finished because of there is no const reference
to it?
Note: The both versions are ok in MSVC.
回答1:
The lifetime of the temporary extends for the length of the full expression in which it was created. In your case, the temporary will be destroyed but only after the call to process_c_string
completes. As long as the function does not store the pointer for later use, you are fine.
In the second case (binding of reference), the lifetime of that temporary is extended to be the scope of the reference, but I would advise against that pattern in this particular case. You get the same effect by creating a local string initialized with the temporary and the code is simpler. (From a performance point of view, all compilers elide the potential extra copy in the code, so the cost would be the same)
来源:https://stackoverflow.com/questions/9018778/will-temporary-object-be-deleted-if-there-is-no-const-reference-to-it