1

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?

Palec
  • 12,743
  • 8
  • 69
  • 138
ursh
  • 11
  • 2
  • Of course it does not warn/error at compile-time. It does not know that `Create()` will return a reference to `*this` when called at run-time. – Remy Lebeau Nov 19 '14 at 04:47

1 Answers1

3

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.

David G
  • 94,763
  • 41
  • 167
  • 253
  • question: if we'd have `const CBase &kk = CBase().Create();` instead - does `const` change anything here? Is it still dangling reference or `kk`'s life is prolongued now? – Nikolai Shalakin Aug 03 '17 at 11:00