【问题标题】:std::bad_weak_ptr exception when using shared_from_this使用 shared_from_this 时出现 std::bad_weak_ptr 异常
【发布时间】:2017-07-20 09:31:08
【问题描述】:

MyCommand 的ctor 执行而不是函数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,我知道:

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

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

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

如果不是,那是什么?

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-22
      • 2018-06-03
      • 1970-01-01
      • 2015-02-26
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多