class C
{
public:
int True(int i) const
{
return i+2;
}
};
const C& F(const C& c)
{
return c;
}
int main()
{
const C& c = F(C()); // Line 1
cout << boolalpha << c.True(1) << endl; // Line 2
}
Question> why the above code can print the value correct?
I assume the variable c will refer to an invalid temporary C object when it hits line 2.
// Update
I would like to update this OP to illustrate the reason why I am concern on this question.
Here is code snippet from C++ Templates: The Complete Guide
// maximum of two values of any type
template <typename T>
inline T const& max (T const& a, T const& b)
{
return a < b ? b : a;
}
As you can see the function return reference to the pass-in parameter.
I just wonder why not the following version instead:
// maximum of two values of any type
template <typename T>
inline T max (T const& a, T const& b)
{
return a < b ? b : a;
}
Normally, when a temporary is bound to a const reference, the lifetime of the temporary is extended to the lifetime of the reference. Thus if your code said
const C& c = C()then the temporary would live as long ascdoes.However, you’re passing the temporary to another function
F(). In this case, §12.2.5 of the C++11 spec dictates that the temporary will persist until the completion of the full-expression containing the call.Therefore, when you say
const C& c = F(C()), the temporaryC()is actually destructed at the end of this statement, and is no longer valid on the next line.That said, your code appears to function properly because the call to
c.True()is known at compile-time, and the function definition doesn’t actually refer to any data inc, so the fact that the temporary is dead doesn’t really affect the observed behavior. However this is technically undefined behavior.