加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用Shutdown()方法而不是析构函数进行清理

发布时间:2020-12-16 07:07:30 所属栏目:百科 来源:网络整理
导读:在 Rastertek DirectX tutorials中,它们具有空构造函数和析构函数,而是使用initialize()和shutdown()函数进行对象初始化和清理.在使用这个设计一段时间之后,我可以稍微了解一下使用initialize()方法的好处,但是我不知道如何使用shutdown()方法比将所有清理代
在 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).

因此,只需让线程完成,就会调用析构函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读