I am learning C ++ 11 functions, in particular shared_ptr , and I had a problem with a reference to this and using it as a reference for other classes.
The reason for this is because I have a Simulation instance that is passed to other instances in the simulation (for example, Apple ), so they themselves can modify the simulation or even remove themselves from the simulation.
In my more complex code, I get a double free error (when the program exists), which, as I understand it from here , I should not create shared_ptr twice on the same raw object. How to pass this to the Apple object as shared_ptr when the Simulation class does not know that this already has shared_ptr ?
My thought is to pass shared_ptr in the initialization argument, but that seems redundant, for example:
Perhaps I'm trying to implement this in an unusual pattern, or maybe my understanding is not entirely true? Maybe there is a better way to do this?
I have a simplified example below:
#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; }
source share