C++核心准则C.30:如果一个类需要明确的销毁动作,定义析构函数

面向对象思考

共 730字,需浏览 2分钟

 ·

2019-12-20 23:22

df4d4e4ede785f5812425972ff196280.webp

C.30: Define a destructor if a class needs an explicit action at object destruction

如果一个类需要明确的销毁动作,定义析构函数


Reason(原因)

A destructor is implicitly invoked at the end of an object's lifetime. If the default destructor is sufficient, use it. Only define a non-default destructor if a class needs to execute code that is not already part of its members' destructors.

析构函数在对象的生命周期结束时被隐式调用。如果默认的析构函数已经足够,没有必要另外定义。只有在一个类需要其成员析构函数处理之外的动作时定义非默认的析构函数。


Example(示例)
template
struct final_action { // slightly simplified
A act;
final_action(A a) :act{a} {}
~final_action() { act(); }
};

template
final_action finally(A act) // deduce action type
{
return final_action
{act};
}

void test()
{
auto act = finally([]{ cout << "Exit test\n"; }); // establish exit action
// ...
if (something) return; // act done here
// ...
} // act done here

The whole purpose of final_action is to get a piece of code (usually a lambda) executed upon destruction.

final_action唯一的目的就是让一段代码(通常是lambda表达式)在final_action被销毁时执行。


Note(注意)

There are two general categories of classes that need a user-defined destructor:

通常有两种情况类需要用户定义析构函数。


Example, bad(反面示例)
class Foo {   // bad; use the default destructor
public:
// ...
~Foo() { s = ""; i = 0; vi.clear(); } // clean up
private:
string s;
int i;
vector vi;
};

The default destructor does it better, more efficiently, and can't get it wrong.

默认的析构函数可以做得更好,更有效,还不会有错。


Note(注意)

If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use =default.

如果需要默认析构函数,但是其产生已经被抑制(例如由于定义了移动构造函数),使用=default(明确要求生成,译者注)。

Enforcement(实施建议)

Look for likely "implicit resources", such as pointers and references. Look for classes with destructors even though all their data members have destructors.

寻找可能的“隐式资源”,例如指针和引用。寻找有析构函数的类,即使它们所有的数据成员都有析构函数。


原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c30-define-a-destructor-if-a-class-needs-an-explicit-action-at-object-destruction




觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

浏览 24
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报