如果一个类需要明确的销毁动作,定义析构函数
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.
析构函数在对象的生命周期结束时被隐式调用。如果默认的析构函数已经足够,没有必要另外定义。只有在一个类需要其成员析构函数处理之外的动作时定义非默认的析构函数。
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被销毁时执行。
There are two general categories of classes that need a user-defined destructor:
通常有两种情况类需要用户定义析构函数。
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.
默认的析构函数可以做得更好,更有效,还不会有错。
If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use =default.
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
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!