std::bad_weak_ptr exception when using shared_from_this

本文讨论了在C++11中遇到std::bad_weak_ptr异常的情况,具体是一个MyCommand类同时继承了Command和Observer,并使用了enable_shared_from_this。异常出现在构造函数中调用shared_from_this(),但在execute()函数中没有。问题可能与对象构造过程中的shared_ptr所有权有关。文章探讨了可能的原因,包括对象尚未完全构造时调用shared_from_this()。

The following code causes a std::bad_weak_ptr exception when the ctor for MyCommand executes but not the function 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();
}

Reading up on enable_shared_from_this, I know that:

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

I need to understand why the exception is thrown in the ctor but not in the execute function.

Is is something to do with the fact that the ctor has not fully executed before shared_from_this is called and therefore the object is not fully constructed?

If not, what is it?

 

原文转引自

c++11: std::bad_weak_ptr exception when using shared_from_this (cpc110.blogspot.com)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值