c++ - 将 "this"称为 shared_ptr?

标签 c++ c++11 shared-ptr

<分区>

我正在学习 C++11 特性,特别是 shared_ptr,我在引用 this 并将其用作其他类的引用时遇到问题.

这样做的原因是我有一个 Simulation 实例,该实例被传递给模拟中的其他实例(例如 Apple),因此它们可以自己修改模拟,甚至将自己从模拟中移除。

在我更复杂的代码中,我得到了一个 double free 错误(当程序存在时),据我所知 from here我不应该在同一个原始对象上创建两次 shared_ptr。当模拟类不知道 this 时,如何将 this 作为 shared_ptr 传递给 Apple 对象已经是 shared_ptr 了吗?

我的想法是在初始化参数中传递 shared_ptr 但这似乎是多余的,例如:

// The argument is a std::shared_ptr<Simulation>
simulation->initSomethingElse(simulation);

也许我试图以一种不寻常的模式来实现它,或者我的理解不太正确?也许有更好的方法来代替?

我在下面有一个简化的例子:

#include <memory>

class Simulation;

class Apple {
public:
    void init(std::shared_ptr<Simulation> simulation) {
        this->simulation = simulation;
    };

private:
    std::shared_ptr<Simulation> simulation;

};


class Simulation {
public:
    void initSomethingElse() {
        auto apple = std::shared_ptr<Apple>(new Apple());

        // incorrect second reference to the raw pointer
        apple->init(std::shared_ptr<Simulation>(this));
    };
};


int main() {

    auto simulation = std::shared_ptr<Simulation>(new Simulation());
    simulation->initSomethingElse();

    return 0;
}

最佳答案

首先想到的是使用enable_shared_from_this : http://en.cppreference.com/w/cpp/memory/enable_shared_from_this

但想到的第二件事是 Simulation 应该管理 Apple 的生命周期,因此 Apple 不需要管理 Simulation 的生命周期。因此,最好不要让 Apple 持有 shared_ptr<Simulation>。 - 只有 main()或者一些高级功能应该管理模拟的生命周期。

如果您不小心,您最终会遇到循环引用。不要假设 C++11 中的每个指针都应该是 shared_ptr。

关于c++ - 将 "this"称为 shared_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26030421/

相关文章:

c++ - 为什么 C++ 模板编译器不能从协变智能指针参数推断类型?

c++ - 每次我为我的 C++ 程序提供大量输入集时,我的 DOS 都会崩溃

c++ - 如何为 IWICBitmap 创建 ID2D1DeviceContext? (对于 C++ 中的 Metro 应用程序)

c++ - 错误 : LNK1120: 3 unresolved externals

c++ - 如何通过 vector 构建数组?

c++ - 使用 std::remove_reference 获取 STL 容器的元素迭代器

c++ - 从灵气中制作共享指针的 vector

c++ - 在 shared_ptr 中使用 deallocator & allocator

c++ - 是否可以在构造函数体中而不是初始化列表中初始化成员变量?

C++ 测试 lambda 函数