Problems with shared_from_this

Take the following code (in file shared.cpp):

#include <memory>
#include <iostream>

class A : /* public */ std::enable_shared_from_this<A>
{
public:
    explicit A(int v)
        : m_val( v )
    {}
    std::shared_ptr<A> getShared() {
        return shared_from_this();
    }
    void print() {
        std::cout << "The value is " << m_val << std::endl;
    }
private:
    int m_val;
};

int main()
{
    auto a1 = std::make_shared<A>(20);
    auto a2 = a1->getShared();
    a2->print();
    return 0;
}

It compiles with no errors using: g++ -g -Wall -o shared shared.cpp

I then ran ./shared

terminate called after throwing an instance of 'std::bad_weak_ptr'
  what():  bad_weak_ptr
Aborted

If I remove the commented public in

class A : /* public */ std::enable_shared_from_this<A>

it runs as expected and produces the output

The value is 20.

This is most unfortunate since the shared_from_this only ever gets used within the class.

The reason for this that when make_shared creates A it is unable to detect the constructor for std::enable_shared_from_this and therefore cannot set the internal weak_count. This meanst that when you try to call shared_from_this, you end up with an error.

Hopefully you will read this blog and not lose as much sleep over this as I did.