C++核心準則C.30:如果一個類需要明確的銷毀動作,定義析構函數(shù)

C.30: Define a destructor if a class needs an explicit action at object destruction
如果一個類需要明確的銷毀動作,定義析構函數(shù)
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.
析構函數(shù)在對象的生命周期結束時被隱式調用。如果默認的析構函數(shù)已經(jīng)足夠,沒有必要另外定義。只有在一個類需要其成員析構函數(shù)處理之外的動作時定義非默認的析構函數(shù)。
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被銷毀時執(zhí)行。
Note(注意)
There are two general categories of classes that need a user-defined destructor:
通常有兩種情況類需要用戶定義析構函數(shù)。
A class with a resource that is not already represented as a class with a destructor, e.g., a vector or a transaction class.
類管理的資源沒有表現(xiàn)為包含析構函數(shù)的類。例如vector或者事務類。
A class that exists primarily to execute an action upon destruction, such as a tracer or final_action.
類存在的主要目的就是在析構時執(zhí)行某個動作。例如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 vi;
};
The default destructor does it better, more efficiently, and can't get it wrong.
默認的析構函數(shù)可以做得更好,更有效,還不會有錯。
Note(注意)
If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use =default.
如果需要默認析構函數(shù),但是其產生已經(jīng)被抑制(例如由于定義了移動構造函數(shù)),使用=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.
尋找可能的“隱式資源”,例如指針和引用。尋找有析構函數(shù)的類,即使它們所有的數(shù)據(jù)成員都有析構函數(shù)。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c30-define-a-destructor-if-a-class-needs-an-explicit-action-at-object-destruction
覺得本文有幫助?請分享給更多人。
關注【面向對象思考】輕松學習每一天!
面向對象開發(fā),面向對象思考!
