以下代码会在
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
之前,构造函数尚未完全执行,因此对象尚未完全构建有关?
如果不是这样,那是什么原因呢?