c++ - 使用带有 "this"的智能指针

标签 c++ boost boost-smart-ptr

我正在学习 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);”之类的东西是没有用的。因为它不安全。 我该怎么办?

最佳答案

你可能想看看enable_shared_from_this ,专门用于解决与您的问题类似的问题。

关于c++ - 使用带有 "this"的智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3374464/

相关文章:

C++ 字符串格式化,如 Python "{}".format

c++ - 我的默认构造函数没有被调用,即使我已经定义了一个

c++ - 在使用 boost::asio 时得到了 receive_from:错误的文件描述符

c++ - Boost 单元测试因 sigabrt 而失败

c++ - 将 boost::shared_ptr 转换为实际类

c++ - 访问违规读取位置 OpenCV Canny 函数

c++ - Boost.Spirit 替代解析器并行化

c++ - boost::正则表达式-\bb?

c++ - 侵入式_ptr : Why isn't a common base class provided?

casting - 如何在多态中使用boost::smart_ptr?