Is std :: unique_ptr removal order guaranteed?

I am creating a global singleton that controls my application, and I want the subsystems to start and end in a specific order.

class App { public: App(); ~App(); void start(); void run(); void shutdown(); private: std::unique_ptr<DisplayManager> displayManager; std::unique_ptr<Renderer> renderer; }; 

Constructor creates pointers in the correct order

 App::App() { displayManager = std::unique_ptr<DisplayManager>(new DisplayManager); renderer = std::unique_ptr<Renderer>(new Renderer); } 

and I want unique_ptrs to be released in reverse order. Does std :: unique_ptr have a guarantee that memory will be freed in this order?

I was thinking of making all managers global singletons, but I felt that it would be better if I could make it work.

EDIT: I was informed that the actual problem is that the elements of the instance variables are being destroyed. In this case, is there a guaranteed order for this?

+5
source share
2 answers

std::unique_ptr does not control when the destructor is called. Instead, he announces that he determines in which order he is destroyed.

Members of a class are constructed in the order in which they are declared in the body of the class, and are destroyed in the reverse order of that order. Therefore, in your case, when a App displayManager is built, the renderer is built first, and then the renderer is built. When the App instance is destroyed, then the renderer destroyed first, and then the displayManager destroyed.


Also note that in

 App::App() { displayManager = std::unique_ptr<DisplayManager>(new DisplayManager); renderer = std::unique_ptr<Renderer>(new Renderer); } 

You are doing the default assignment to unique_ptr s. You need to use a member initialization list like

 App::App(): displayManager(new DisplayManager), renderer(new Renderer) {} // or if you want to be in the don't use new camp App::App(): displayManager(std::make_unique<DisplayManager>()), renderer(std::make_unique<Renderer>()) {} 

If you do not want to construct pointers by default, then assign them.

+13
source

Yes, the order of destruction is guaranteed.

Each div will be called as soon as std::unique_ptr ref is destroyed and std::unique_ptr destroyed in the reverse order of their construction when they all go out of scope of ref .

However, this order is not directly related to the order of your appointments inside App::App() - you could exchange them, and nothing has changed. He believes that the order std::unique_ptr s' inside inside the App is considered.

So, although the order of destruction is guaranteed, it may not be the order you expected.

+7
source

All Articles