Cleaning up in Shutdown() method instead of destructor

这一生的挚爱 提交于 2019-12-06 05:50:13

问题


In Rastertek DirectX tutorials they have empty constructors and destructors and instead use initialize() and shutdown() functions for objects initialization and cleaning up. After using this design for a while I can somewhat understand the benefits of having an initialize() method, but I can't see how using a shutdown() method is any better than putting all the clean-up code in the destructor.

The reason they provide is the following:

You will also notice I don't do any object clean up in the class destructor. I instead do all my object clean up in the Shutdown function you will see further down. The reason being is that I don't trust it to be called. Certain windows functions like ExitThread() are known for not calling your class destructors resulting in memory leaks. You can of course call safer versions of these functions now but I'm just being careful when programming on windows.

So the general usage pattern looks like this:

class Renderer
{
public:
    Renderer() { }
    ~Renderer() { }

    bool initialize(...) { /* perform initialization */ }
    void shutdown() { /* clean-up */ }
}; 

Renderer* renderer = new Renderer;
renderer->initialize(...);

// use the renderer

renderer->shutdown();
delete renderer;
renderer = NULL;

When looking at Rastertek's code it seems to me that they're coming from C background (initializing all variables at the top of the function, using only raw pointers and raw arrays etc.), so I wonder if this is yet another thing that is unnecessary in modern C++ (for one it makes it more difficult to use smart pointers). Is there any real benefit to this design?


回答1:


Generally, it is a bad advice not to do a cleanup in the destructor.

But you can do it if the clean operation can fail, and you want to throw an exception. Then you have to be careful, as another exception would call abort(). For that particular case, doing cleanup in a separate function makes sense.

By the way, the code example indeed looks like from someone coming from the c world.

The reason being is that I don't trust it to be called. Certain windows functions like ExitThread() are known for not calling your class destructors resulting in memory leaks.

That is correct, but try to avoid such functions. Also from here :

There is no portable way in C++11 (that I'm aware of) to non-cooperatively kill a single thread in a multi-thread program (i.e. without killing all threads).

therefore just let the thread nicely finish, and destructors will be called.



来源:https://stackoverflow.com/questions/21505014/cleaning-up-in-shutdown-method-instead-of-destructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!