Search code examples
c++shared-ptr

shared_from_this throws bad_weak_ptr with boost::asio


First, I have read all related questions listed.

They say, "you must have an existing shared_ptr to this before you can use shared_from_this." As far as I can see, there is no way I am violating that condition. I create the instance of Foo as a shared_ptr and enforced that it is always created as a shared_ptr. I then, stored the shared_ptr in a collection. Yet, I still get the bad_weak_ptr exception when shared_from_this is called.

#pragma once

#include <memory>
#include <vector>

//--------------------------------------------------------------------
class Foo : std::enable_shared_from_this<Foo>
{
public:

    typedef std::shared_ptr<Foo> SharedPtr;

    // Ensure all instances are created as shared_ptr in order to fulfill requirements for shared_from_this
    static Foo::SharedPtr Create()
    {
        return Foo::SharedPtr(new Foo());
    };

    Foo(const Foo &) = delete;
    Foo(Foo &&) = delete;
    Foo & operator = (const Foo &) = delete;
    Foo & operator = (Foo &&) = delete;
    ~Foo() {};

    // We have to defer the start until we are fully constructed because we share_from_this()
    void Start()
    {
        DoStuff();
    }

private:

    Foo() {}

    void DoStuff()
    {
        auto self(shared_from_this());
    }
};

//--------------------------------------------------------------------
int main()
{
    std::vector<Foo::SharedPtr> foos;
    Foo::SharedPtr foo = Foo::Create();
    foos.emplace_back(foo);
    foo->Start();

    return 0;
}

Solution

  • You must inherit enable_shared_from_this with public specifier according to

    Publicly inheriting from std::enable_shared_from_this provides the type T with a member function shared_from_this.

    from http://en.cppreference.com/w/cpp/memory/enable_shared_from_this.

    So write

    class Foo : public std::enable_shared_from_this<Foo>