c++ - 使用 shared_from_this 时出现 std::bad_weak_ptr 异常

标签 c++ c++11 constructor shared-ptr

以下代码在 MyCommand 的构造函数执行但不执行函数 MyCommand::execute 时导致 std::bad_weak_ptr 异常。

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,我知道:

Prior to calling shared_from_this on an object t, there must be a std::shared_ptr that owns t.

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

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

如果不是,那是什么?

最佳答案

您不能在构造函数中使用 shared_from_this,因为尚未分配 shared_ptr。看这个Why shared_from_this can't be used in constructor from technical standpoint?

然而,当对象被构建并且有任何 shared_ptr 与实例关联时,您可以像往常一样调用 shared_from_this

关于c++ - 使用 shared_from_this 时出现 std::bad_weak_ptr 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45210772/

相关文章:

C++:cout 和函数调用之间的求值顺序

c++ - 使用 LLVM 在 OSX 上将问题与 boost::program_options 联系起来

java - 为什么可以在参数内创建对象而不命名对象?

c++ - 从除法中删除精度

c++ - 组合两个矩阵,保留它们的元素值

c++ - c++ 中内联函数的零成本列表

javascript - 原型(prototype)继承 : Calling super constructor in sub "class" constructor function

c++ - std::condition_variable 是第一次检查条件,还是必须等待别人通知?

c++ - 使用 libcurl 上传文件到 DropBox

c++ - 没有模板也能完美转发吗