kAnton
kAnton

Reputation: 33

shared_from_this with derived class

I am trying to create shared ptr to this with shared_from_this function.

#include <iostream>
#include <memory>

class foo {
public:
    virtual void method() {
        std::cerr << "foo::method()" << std::endl;
    }
};

class foo_derived : public foo, public std::enable_shared_from_this<foo> {
public:
    void method() override {
        auto self(shared_from_this());
        std::cerr << "foo_derived::method" << std::endl;
    }
};

int main() {
    foo_derived().method();
}

This code throw bad_weak_ptr from line auto self(shared_from_this()); I think the problem is with the fact that self is created in derived class. I am looking for an explanation for this behaviour and would also appreciate an example of valid shared_from_this usage with derived class.

Upvotes: 2

Views: 1633

Answers (1)

felix
felix

Reputation: 2222

It has nothing to do with inheritance. Call method this way instead will work: std::make_shared<foo_derived>()->method();

cppreference std::enable_shared_from_this::shared_from_this

It is permitted to call shared_from_this only on a previously shared object, i.e. on an object managed by std::shared_ptr. Otherwise the behavior is undefined (until C++17)std::bad_weak_ptr is thrown (by the shared_ptr constructor from a default-constructed weak_this) (since C++17).

Upvotes: 4

Related Questions