Quest
Quest

Reputation: 2843

Bad weak_ptr when calling `shared_from_this`

I've threw together a small class inheriting from std::enable_shared_form_this as follows:

class Foo : std::enable_shared_from_this<Foo>
{
    Foo() = default();
public:
    [[nodiscard]] static auto getInstance()
    {
        static auto f = std::shared_ptr<Foo>(new Foo());
        return f;
    }

    stream construct()
    {
        return stream{ shared_from_this() };
    }
};

Whenever I call construct(), bad_weak_ptr exception is thrown. Can anybody explain why I am observing such behavior?

Compiled with: Apple clang version 13.0.0 (clang-1300.0.29.30)
Target: arm64-apple-darwin21.5.0

Upvotes: 0

Views: 128

Answers (1)

Slava
Slava

Reputation: 44238

As stated in documentation (emphasis is mine)

Publicly inheriting from std::enable_shared_from_this provides the type T with a member function shared_from_this. If an object t of type T is managed by a std::shared_ptr named pt, then calling T::shared_from_this will return a new std::shared_ptr that shares ownership of t with pt.

your inheritance is private, so you violated contract.

Just inherit it public:

 class Foo : public std::enable_shared_from_this<Foo>

Upvotes: 6

Related Questions