Why do I get an exception for this usage of enable_shared_from_this()?

Viewed 117

On the following example below, something is escaping me. Why does this generate the usual weak_ptr exception when using the shared_from_this, if there is an outstanding shared_ptr reference to the object which calls it ?

class A : std::enable_shared_from_this<A> {
public:
    static std::shared_ptr<A> create() {
        return std::shared_ptr<A>(new A());
    }
    A() {}
    void setParent(const std::shared_ptr<A>& other) {}
    std::shared_ptr<A> keep() {
        auto o = A::create();
        o->setParent(shared_from_this());
        return o;
    }
};

int main() {
    std::shared_ptr<A> a = A::create();
    auto s = a->keep();
}
2 Answers

You need to inherit publicly from enable_shared_from_this so the shared ptr ctor can see it.

As an aside, clang fails to compile your example due to this.

enable_shared_from_this must be an unambiguous and accessible base of A for the library to handle the internal weak pointer correctly.

Your inheritance is private (the default when using the class keyword).

Related