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

1363

被折叠的 条评论
为什么被折叠?



