Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use temporary object as default argument in C++?

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."

like image 741
updogliu Avatar asked Jul 20 '12 01:07

updogliu


1 Answers

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.

like image 143
SoapBox Avatar answered Oct 30 '22 22:10

SoapBox