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

当类需要在对象销毁时执行特定操作,如资源清理或特定行为,应定义析构函数。默认析构函数通常足够,除非需要执行额外的代码。析构函数的一个例子是final_action,用于确保在对象生命周期结束时执行一段代码。避免不必要的成员变量清理,并使用=default显式要求生成默认析构函数。
摘要由CSDN通过智能技术生成
b209b81f02fd564ecf86611b46f9b2fa.png

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(示例)

templatestruct final_action {   // slightly simplified    A act;    final_action(A a) :act{a} {}    ~final_action() { act(); }};templatefinal_action finally(A act)   // deduce action type{    return final_action{act};}void test(){    auto act = finally([]{ cout << "Exit test"; });  // 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表达式)在其被销毁时执行。

Note(注意)

There are two general categories of classes that need a user-defined destructor:通常有两种情况类需要用户定义的析构函数。

  • A class with a resource that is not already represented as a class with a destructor, e.g., a vector or a transaction class.类管理的资源没有表现为包含析构函数的类。例如vector或者事务类。
  • A class that exists primarily to execute an action upon destruction, such as a tracer or final_action.类存在的主要目的就是在析构时执行某个动作。例如tracer和final_action。

Example, bad(反面示例)

class Foo {   // bad; use the default destructorpublic:    // ...    ~Foo() { s = ""; i = 0; vi.clear(); }  // clean upprivate:    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


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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值