简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM