c++ - 在 Shutdown() 方法而不是析构函数中清理

标签 c++ directx game-engine class-design

Rastertek DirectX tutorials他们有空的构造函数和析构函数,而是使用 initialize()shutdown() 函数来初始化和清理对象。使用此设计一段时间后,我可以稍微了解使用 initialize() 方法的好处,但我看不出使用 shutdown() 方法有什么用比将所有清理代码放在析构函数中更好。

他们提供的原因如下:

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.

所以一般的使用模式是这样的:

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;

当查看 Rastertek 的代码时,在我看来它们来自 C 背景(在函数顶部初始化所有变量,仅使用原始指针和原始数组等),所以我想知道这是否是另一个这在现代 C++ 中是不必要的(一方面,它使使用智能指针变得更加困难)。这种设计有什么真正的好处吗?

最佳答案

一般来说,不在析构函数中进行清理是一个糟糕的建议。

但如果清理操作可能失败,并且您想抛出异常,您可以这样做。然后你必须小心,因为另一个异常会调用 abort()。对于这种特殊情况,在单独的函数中进行清理是有意义的。

顺便说一下,代码示例确实看起来像来自 c 世界的人。

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.

这是正确的,但尽量避免这样的功能。同样来自 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).

因此只要让线程很好地结束,析构函数就会被调用。

关于c++ - 在 Shutdown() 方法而不是析构函数中清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21505014/

相关文章:

选择应在 map 上显示的内容的算法

c++ - 如何启用共享对象在运行时访问数据文件 (UNIX)

c++ - 仅检测引号中的文本 (C++)

visual-c++ - D3D12 CreateHeap 对齐,MSDN 使用 1024 还是 1000 来定义 KB

c++ - 检查是否支持 DirectX 或 OpenGL

architecture - SceneKit 游戏架构

android - 哪个游戏框架很容易在android中开发2D游戏应用程序?

Python 安装包使用 msvccompiler 出现错误

c++ - C++ 中常量的正确性

opengl - 宽屏显示器上的全屏渲染