Pregunta

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?

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top