以下代码在 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/