简体   繁体   English

使用带有“this”的智能指针

[英]using smart pointers with “this”

I'm learning the use of boost smart pointers but I'm a bit confused about a few situations. 我正在学习使用boost智能指针,但我对一些情况有点困惑。 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? 你能翻译这段代码来使用boost智能指针吗? 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);" 基本上我觉得返回像“return boost :: shared_ptr(this);”这样的东西是没用的。 because it's not safe. 因为它不安全 What should I do? 我该怎么办?

您可能需要查看enable_shared_from_this ,它可以解决与您类似的问题。

You have to make your classes inherit from boost::enable_shared_from_this<> . 你必须让你的类继承自boost::enable_shared_from_this<> Check out Boost's example here . 看看Boost的例子在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM