enable_shared_from_this - empty internal weak pointer?

前端 未结 3 1991
鱼传尺愫
鱼传尺愫 2020-12-31 01:15

I\'m using enable_shared_from_this and then inherit from Base. When trying to use shared_from_this() in Derived

相关标签:
3条回答
  • 2020-12-31 01:46

    You cannot call shared_from_this() in the object's constructor. shared_from_this() requires that the object is owned by at least one shared_ptr. An object cannot be owned by a shared_ptr before it is constructed.

    I would guess that the internal weak pointer is set when a shared_ptr takes ownership of the object for the first time. Before that point, there is no reference count struct that the weak pointer can reference.

    0 讨论(0)
  • 2020-12-31 02:01

    Conceptually, shared_from_this() picks a shared_ptr pointing to this and returns a copy of it.

    In the constructor, there is no shared_ptr pointing to this.

    0 讨论(0)
  • 2020-12-31 02:08

    James McNellis's answer is right.

    As for the explanation of the enable_shared_from_this template itself, which as you observe appears to do nothing, note 7 at the bottom of this page explains:

    ...the template enable_shared_from_this holds a weak_ptr object that points to the derived object. There's a chicken-and-egg problem, though, about how to initialize that weak_ptr object when there is no corresponding shared_ptr object. The implementation trick is that the constructors for shared_ptr know about enable_shared_from_this, and set the weak_ptr object during construction of a shared_ptr object that owns a resource that has enable_shared_from_this as a public base class.

    0 讨论(0)
提交回复
热议问题