I'm learning about c++11 features, specifically shared_ptr, and I am having an issue with referring to this and using it as a reference for other classes.
The reason for doing this is I have a Simulation instance that is passed around to other instances within the simulation (e.g. Apple) so they can themselves 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 from here that I should not create a shared_ptr twice on the same raw object. How do I pass this to the Apple object as a shared_ptr when the Simulation class doesn't know that this is already a shared_ptr?
My thought is to pass the shared_ptr in the initialisation argument but that seems redundant, e.g.:
// The argument is a std::shared_ptr<Simulation>
simulation->initSomethingElse(simulation);
Maybe I am trying to implement this in an unusual pattern, or maybe my understanding is not quite right? Maybe there is a nicer way of doing this instead?
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;
}