使用shared_from_this时出现std::bad_weak_ptr异常

7
以下代码会在MyCommand的构造函数执行时引发std::bad_weak_ptr异常,但不会在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();
}

阅读关于enable_shared_from_this的内容,我知道:

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

我需要了解为什么在ctor中会抛出异常,而在execute函数中不会。

这是否与在调用shared_from_this之前,构造函数尚未完全执行,因此对象尚未完全构建有关?

如果不是这样,那是什么原因呢?


如果构造函数抛出异常,你是如何成功调用到该调用函数的? - doctorlove
@doctorlove,我注释掉了构造函数的内容。 - ksl
2个回答

13

10
注意:对我来说,问题在于我没有添加“public”关键字(希望这能节省其他人的时间)。
例如:

class A : std::enable_shared_from_this<A> { //BAD
class A : public std::enable_shared_from_this<A> { //GOOD


我也遇到了这个问题,它的原因是什么? - macomphy
1
这可能会回答你的问题。 - Tomer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接