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.
This is invalid because the temporary is created inside the
accessorfunction 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.