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.
No. A reference is simply an alias for an existing object. const is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r .
In the by-reference case, we get a const Base& reference that refers to a Derived object. The entire temporary object, of type Derived , is lifetime-extended.
But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With