C++核心準(zhǔn)則C.37:保證析構(gòu)函數(shù)不會(huì)拋出異常

C.37:保證析構(gòu)函數(shù)不會(huì)拋出異常
Reason(原因)
A destructor may not fail. If a destructor tries to exit with an exception, it's a bad design error and the program had better terminate.
所有的析構(gòu)函數(shù)都可以不失敗。如果析構(gòu)函數(shù)試圖拋出異常退出,這是嚴(yán)重的設(shè)計(jì)錯(cuò)誤,更好的選擇是中止程序。
Note(注意)
A destructor (either user-defined or compiler-generated) is implicitly declared noexcept (independently of what code is in its body) if all of the members of its class have noexcept destructors. By explicitly marking destructors noexcept, an author guards against the destructor becoming implicitly noexcept(false) through the addition or modification of a class member.
如果類(lèi)的所有的成員的析構(gòu)函數(shù)都是noexcept的,它的析構(gòu)函數(shù)(無(wú)論是用戶(hù)定義的還是編譯器生成的)就會(huì)被隱式定義為noexcept(這和函數(shù)體內(nèi)的具體代碼無(wú)關(guān))。通過(guò)顯式定義析構(gòu)函數(shù)為noexcept,可以防止析構(gòu)函數(shù)由于類(lèi)成員被修改而無(wú)法成為noexcpet。

Not all destructors are noexcept by default; one throwing member poisons the whole class hierarchy
不是所有的析構(gòu)函數(shù)都默認(rèn)是noexcept的;只要有一個(gè)(析構(gòu)時(shí),譯者注)拋出異常的成員,就會(huì)破壞整個(gè)繼承體系。
struct X {
? ? Details x; ?// happens to have a throwing destructor
? ? // ...
? ? ~X() { } ? ?// implicitly noexcept(false); aka can throw?
};
左右滑動(dòng)查看更多
So, if in doubt, declare a destructor noexcept.
因此,如果有疑問(wèn),就將析構(gòu)函數(shù)定義為noexcept。
Note(注意)
Why not then declare all destructors noexcept? Because that would in many cases -- especially simple cases -- be distracting clutter.
為什么不將所有的析構(gòu)函數(shù)都定義為noexcept?因?yàn)樵诤芏鄨?chǎng)合,特別是簡(jiǎn)單的場(chǎng)合這樣做只會(huì)增加干擾信息。
Enforcement(實(shí)施建議)
(Simple) A destructor should be declarednoexceptif it could throw.
(簡(jiǎn)單)如果存在拋出異常的風(fēng)險(xiǎn),則將析構(gòu)函數(shù)定義為noexcept。
原為鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c37-make-destructors-noexcept
覺(jué)得本文有幫助?請(qǐng)分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_(kāi)發(fā),面向?qū)ο笏伎迹?/span>
