Referring to "this" as shared_ptr?

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:

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

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; } 
+5
source share
2 answers

The first thing that comes to mind is to use enable_shared_from_this : http://en.cppreference.com/w/cpp/memory/enable_shared_from_this

But the second thing that comes to mind is that Simulation needs to control Apple's lifetime, so Apple doesn't need to control Simulation's lifetime. Therefore, it is better for you if Apple does not hold shared_ptr<Simulation> - only main() , or some high-level function should control the lifetime of the Simulation.

If you are not careful, you will get circular links. Do not assume that every pointer in C ++ 11 should be shared_ptr.

+8
source

Use enable_shared_from_this , so an object function can create a new shared_ptr for itself. You will want to do this instead of the string apple->init(std::shared_ptr<Simulation>(this)); , which creates a second shared_ptr in Simulation . You will also want to rturn or save apple shared_ptr somewhere, since currently apple only exists when initSomethingElse() is initSomethingElse() , which is not very useful ...?

+1
source

Source: https://habr.com/ru/post/1203353/


All Articles