class C
{
public:
int True(int i) const
{
return i+2;
}
};
const C& F(const C& c)
{
return c;
}
int main()
{
const C& c =
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 as c
does.
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 temporary C()
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 in c
, so the fact that the temporary is dead doesn't really affect the observed behavior. However this is technically undefined behavior.