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 andpp
is a dangling pointer. The temporary produced byCBase()
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
andpp
still exist after the full expression, this is not the case. Usingkk
and dereferencingpp
has undefined behavior.