使用带有“this”的智能指针
我正在学习 boost 智能指针的使用,但我对一些情况有点困惑。 假设我正在实现一个状态机,其中每个状态都是通过单个更新方法实现的。 每个状态都可以返回自身或创建一个新的状态对象:
struct state
{
virtual state* update() = 0; // The point: I want to return a smart pointer here
};
struct stateA : public state
{
virtual state* update() { return this; }
};
struct stateB : public state
{
virtual state* update() { if(some condition) return new stateA() else return this; }
};
状态机循环看起来像这样:
while(true)
current_state = current_state->update();
你能翻译这段代码以使用 boost 智能指针吗?当谈到“返回这个”部分时,我有点困惑,因为我不知道该怎么做。 基本上我认为返回“return boost::shared_ptr(this);”之类的东西是没有用的。因为它不安全。 我应该怎么办?
I'm learning the use of boost smart pointers but I'm a bit confused about a few situations.
Let's say I'm implementing a state machine where each state is implemented by a single update method.
Each state could return itself or create a new state object:
struct state
{
virtual state* update() = 0; // The point: I want to return a smart pointer here
};
struct stateA : public state
{
virtual state* update() { return this; }
};
struct stateB : public state
{
virtual state* update() { if(some condition) return new stateA() else return this; }
};
The state machine loop would look like this:
while(true)
current_state = current_state->update();
Could you translate this code to use boost smart pointers? I'm a bit confused when it comes to the "return this" part because I don't know what to do.
Basically I think it's useless to return something like "return boost::shared_ptr(this);" because it's not safe.
What should I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能需要查看
enable_shared_from_this
,它是专门解决与您类似的问题的。You may want to look at
enable_shared_from_this
, which is there for specificly solving problems similar to yours.您必须使您的类继承自
boost::enable_shared_from_this
。 此处查看 Boost 的示例。You have to make your classes inherit from
boost::enable_shared_from_this<>
. Check out Boost's example here.