C++核心準(zhǔn)則C.127:包含虛函數(shù)的類應(yīng)該有虛析構(gòu)函數(shù)或保護(hù)析構(gòu)函...

獨(dú)山玉雕件
C.127: A class with a virtual function should have a virtual or protected destructor
C.127:包含虛函數(shù)的類應(yīng)該有虛析構(gòu)函數(shù)或保護(hù)析構(gòu)函數(shù)?
Reason(原因)
A class with a virtual function is usually (and in general) used via a pointer to base. Usually, the last user has to call delete on a pointer to base, often via a smart pointer to base, so the destructor should be public and virtual. Less commonly, if deletion through a pointer to base is not intended to be supported, the destructor should be protected and nonvirtual; see?C.35.
包含虛函數(shù)的類通常(大多數(shù)情況下)通過指向基類的指針使用。通常,最后一個(gè)使用者必須通過指向基類的指針調(diào)用delete操作,通常是指向基類的智能指針,因此析構(gòu)函數(shù)應(yīng)該是公開的虛函數(shù)。稍微特殊一些的情況是:如果不希望支持通過指向基類的指針銷毀對象,析構(gòu)函數(shù)應(yīng)該是保護(hù)的非虛函數(shù)。參見C.35。
Example, bad(反面示例)
struct?B?{
????virtual?int?f()?=?0;
????//?...?no?user-written?destructor,?defaults?to?public?nonvirtual?...
};
//?bad:?derived?from?a?class?without?a?virtual?destructor
struct?D?:?B?{
????string?s?{"default"};
};
void?use()
{
????unique_ptr?p?=?make_unique();
????//?...
}?//?undefined?behavior.?May?call?B::~B?only?and?leak?the?string
Note(注意)
There are people who don't follow this rule because they plan to use a class only through a shared_ptr: std::shared_ptr p = std::make_shared(args); Here, the shared pointer will take care of deletion, so no leak will occur from an inappropriate delete of the base. People who do this consistently can get a false positive, but the rule is important -- what if one was allocated using make_unique? It's not safe unless the author of B ensures that it can never be misused, such as by making all constructors private and providing a factory function to enforce the allocation with make_shared.
也有一些人計(jì)劃只通過shared_ptr使用類:std::shared_ptr p=
std::make_shared
Enforcement(實(shí)施建議)
A class with any virtual functions should have a destructor that is either public and virtual or else protected and nonvirtual.
包含虛函數(shù)的類的析構(gòu)函數(shù)要么是公開的虛函數(shù),要么是保護(hù)的非虛函數(shù)。
Flag delete of a class with a virtual function but no virtual destructor.
提示針對包含虛函數(shù)卻沒有虛析構(gòu)函數(shù)的類的銷毀操作。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#enforcement-123
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/p>
