Search code examples
c++boostconstructorshared-ptrweak-ptr

Weak pointer to this in constructor


I understand it is not possible to obtain a shared_ptr by calling shared_from_this() from the constructor of a class, as the object is not yet constructed. Is it possible however to obtain a weak_ptr to the object from the constructor? Some boost forum posts discussing a "weak_from_raw()" method suggests that it may be possible.

Edit: Boost form discussing weak_from_raw http://lists.boost.org/boost-users/2010/08/61541.php


Solution

  • I think what you're referencing is this. Which seems not to have been merged to the boost release (may be wrong about that).

    From the boost docs:

    Frequently Asked Questions

    Q. Can an object create a weak_ptr to itself in its constructor?

    A. No. A weak_ptr can only be created from a shared_ptr, and at object construction time no shared_ptr to the object exists yet. Even if you could create a temporary shared_ptr to this, it would go out of scope at the end of the constructor, and all weak_ptr instances would instantly expire.

    The solution is to make the constructor private, and supply a factory function that returns a shared_ptr:

    class X
    {
    private:
    
        X();
    
    public:
    
        static shared_ptr<X> create()
        {
            shared_ptr<X> px(new X);
            // create weak pointers from px here
            return px;
        }
    };