我正在学习 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/