【发布时间】: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 尚未完全执行因此对象未完全构造的事实有关吗?
如果不是,那是什么?
【问题讨论】:
-
如果构造函数抛出,你是如何管理调用函数的?
-
@doctorlove 我注释掉了ctor的内容。
标签: c++ c++11 constructor shared-ptr