Raider posted:
is such code correct?
#include <string>
typedef std::string T;
T *s;
const T& foo(const T& default)
{
if (s) return *s; else return default;
}
"default" is a keyword in C++.
const T &foo(const T &def)
{
if(s) return *s;
return def;
}
int main()
{
const T& value = foo("bar");
// use value
}
I think the "bar" must be destroyed immediatly when foo() returns.
Step 1: A non-const, nameless, R-value temporary is created.
Step 2: It is passed by const reference to a function.
Step 3: The function then returns it by const reference.
Step 4: The calling function binds a reference named "value" to the
returned reference.
If you bind a reference to a temporary, the temporary's lifetime is
extended to that of the reference. However, there's only one Step in
which this happens: Step 1. The argument to the function gets destroyed
once the function returns. The function returns an invalid reference.
You're left with a reference to an invalid object.