使用shared_from_this时std :: bad_weak_ptr异常

ksl*_*ksl 3 c++ constructor shared-ptr c++11

以下代码std::bad_weak_ptr在ctor for MyCommand执行但函数未执行时导致异常MyCommand::execute

class Observer
{
public:
    Observer(){}
    virtual ~Observer(){}

    virtual void update(const std::string& msg) = 0;
};

class Command
{
public:
    Command(){}
    virtual ~Command(){}

    virtual void execute() = 0;
};

class MyCommand : public Command, public Observer, public std::enable_shared_from_this<MyCommand>
{
public:
    MyCommand()
    {
        // std::bad_weak_ptr exception
        std::shared_ptr<Observer> observer = shared_from_this();
    }

    virtual ~MyCommand(){}

private:
    virtual void execute()
    {
        // no exception
        std::shared_ptr<Observer> observer = shared_from_this();
    }
    virtual void update(const std::string& msg){}
};

int main(int argc, const char* argv[])
{
    // causes std::bad_weak_ptr exception
    std::shared_ptr<Command> myCommand = std::make_shared<MyCommand>();

    // doesn't cause std::bad_weak_ptr exception
    myCommand->execute();
}
Run Code Online (Sandbox Code Playgroud)

阅读enable_shared_from_this,我知道:

在对象t上调用shared_from_this之前,必须有一个拥有t的std :: shared_ptr。

我需要了解为什么在ctor中而不是在execute函数中引发异常。

这与ctor在shared_from_this调用之前尚未完全执行并因此未完全构造对象有关吗?

如果没有,那是什么?

vas*_*sek 6

您尚未shared_from_this在构造函数中使用,因为shared_ptr尚未分配。看到这个为什么shared_from_this不能从技术角度构造函数中使用?

但是,当构造对象并且shared_ptr实例与对象相关联时,您可以shared_from_this照常调用。


Tom*_*mer 6

注意:对我来说,问题是我没有添加“public”关键字(希望这可以为其他人节省一些时间)。

例如:

class A : std::enable_shared_from_this<A> { //BAD
class A : public std::enable_shared_from_this<A> { //GOOD
Run Code Online (Sandbox Code Playgroud)