Is the lvalue reference return of a member function of a temporary object a dangling reference?

129 views Asked by At

There is a class CBase.

class CBase
{
    ...
    CBase &Create()
    {
        return *this;
    }
    ...
}

If I declare an lvalue reference and a pointer,

CBase &kk = CBase().Create();
CBase *pp = &( CBase().Create() );

is kk a dangling reference and is pp a dangling pointer?

I think kk and pp are dangling. Because calling CBase() creates a temporary object no doubt, the derivative, CBase().Create(), should be too. However, Xcode (version 6.1) gives no warning or error message.

Can anyone give some hints or tell me where the C++11 document describes these behaviors? Or am I wrong?

1

There are 1 answers

1
David G On

Yes, kk is a dangling reference and pp is a dangling pointer. The temporary produced by CBase() only exists for the duration of the full expression in which it appears. Note that it is still valid to have a pointer or reference refer to this object, as long as their lifetime is bound to the expression as well.

Since kk and pp still exist after the full expression, this is not the case. Using kk and dereferencing pp has undefined behavior.