将"this"称为shared_ptr?

gak*_*gak 6 c++ shared-ptr c++11

我正在学习c ++ 11的功能,特别是shared_ptr,我在引用this和使用它作为其他类的参考时遇到了问题.

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

在我更复杂的代码中,我得到一个double free错误(当程序存在时),据我从这里理解,我不应该shared_ptr在同一个原始对象上创建两次.如何在Simulation类不知道已经存在的情况下传递thisApple对象?shared_ptrthisshared_ptr

我的想法是通过shared_ptr初始化参数,但这似乎是多余的,例如:

// The argument is a std::shared_ptr<Simulation>
simulation->initSomethingElse(simulation);
Run Code Online (Sandbox Code Playgroud)

也许我试图以一种不寻常的模式实现这一点,或者我的理解可能不太正确?也许有一种更好的方法可以做到这一点?

我有一个简化的例子如下:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*nck 9

首先想到的是使用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.