Search code examples
c++boostshared-ptrobject-lifetimeweak-ptr

Boost shared_from_this and destructor


I found that it is not allowed to call shared_from_this in the destructor from a class:

https://svn.boost.org/trac/boost/ticket/147

This behavior is by design. Since the destructor will destroy the object, it is not safe to create a shared_ptr to it as it will become dangling once the destructor ends.

I understand the argument, but what if I need a "shared_from_this" pointer for cleaning up references ( not for sharing owner ship).

Here is an example where I'm not using shared_ptr:

class A{
public:
    A( Manager * m ) : m_(m) {
        m_->add(this);
    }

    ~A() {
        m_->remove(this);
    }

private:
    Manager * m_;
};

Here I have tried to translate it into shared pointers. But I can not find a good way to finish the destructor:

class A : public boost::enable_shared_from_this< A > {
public:
    typedef boost::shared_ptr< A > Ptr;

    static Ptr create( Manager * m ) {
        Ptr p( new A(m));
        p->init();
        return p;
    }

    ~A() {
        // NON-WORKING
        // m_->remove( shared_from_this() );
    }

private:
    A( Manager * m ) : m_(m) { }

    void init() {
        m_->add(shared_from_this());
    }

    Manager * m_;
};

How can I implement the destructor in the example above?


Solution

  • If your Manager has a shared_ptr to your object, then it owns it. Thus your object shall not be destructed, as the Manager still have a reference to it.

    You may pass a weak pointer to the Manager, but then it's the work of the manager to check that the pointer is still valid, and delete it if not.

    Your question is interesting, but your case is caused by a misconception. As long as an object own a reference to your object, it's the aim of shared_ptr that it will not be destructed. For the destructor to be called, you should have manually called delete on the pointer, which is a bad behavior when working with shared_ptr.

    Simple define who really own the object, and give them the shared_ptr. If a part of code occasionally need your object - if it exists - then give it a weak_ptr.