代码之家  ›  专栏  ›  技术社区  ›  Emiliano

将智能指针与“this”一起使用

  •  4
  • Emiliano  · 技术社区  · 14 年前

    我正在学习如何使用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);”的内容是无用的,因为它不安全。 我该怎么办?

    2 回复  |  直到 14 年前
        1
  •  12
  •   hkaiser    14 年前

    你可能想看看 enable_shared_from_this 这是为了具体解决类似于您的问题。

        2
  •  6
  •   Gianni    14 年前

    你必须让你的类继承自 boost::enable_shared_from_this<> . 看看Boost的例子 here .