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

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<typename A>
struct final_action {   // slightly simplified
    A act;
    final_action(A a) :act{a} {}
    ~final_action() { act(); }
};

template<typename A>
final_action<A> finally(A act)   // deduce action type
{
    return final_action<A>{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:

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

  • 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 destructor
public:
    // ...
    ~Foo() { s = ""; i = 0; vi.clear(); }  // clean up
private:
    string s;
    int i;
    vector<int> 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


觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

发布了408 篇原创文章 · 获赞 653 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/craftsman1970/article/details/104299878
今日推荐