For example:
int StrLen(const std::string &s = "default string") {
const std::string &t = "another string"; // BTW, is this line safe?
return s.size();
}
Update
SoapBox's conclusion is correct, but the reason is not completely right.
the lifetime of the temporary is automatically extended to be the same as the reference that holds it.
This is usually true with several exceptions. One is that
"A temporary bound to a reference parameter in a function call persists until the completion of the full-expression containing the call."
I think this exception applys for the default argument case.
Another exception is related to the additional example in SoapBox's answer:
"The lifetime of a temporary bound to the returned value in a function return statement is not extended; the temporary is destroyed at the end of the full-expression in the return statement."
Yes, both of those things are safe to do. They construct temporary objects, and the lifetime of the temporary is automatically extended to be the same as the reference that holds it.
While we're on the subject though, this is a common mistake with temporaries that is not safe.
std::string const &accessor() const {
if (my_name_is_valid())
return m_my_name;
else
return "";
}
This is invalid because the temporary is created inside the accessor
function and then a reference to it is returned. The caller will receive a reference to a destructed object... which is undefined behavior, and will usually cause a crash.
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