C++核心準則C.37:保證析構函數不會拋出異常

C.37: Make destructors noexcept

C.37:保證析構函數不會拋出異常

 

 

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.

所有的析構函數都可以不失敗。如果析構函數試圖拋出異常退出,這是嚴重的設計錯誤,更好的選擇是中止程序。

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.

如果類的所有的成員的析構函數都是noexcept的,它的析構函數(無論是用戶定義的還是編譯器生成的)就會被隱式定義爲noexcept(這和函數體內的具體代碼無關)。通過顯式定義析構函數爲noexcept,可以防止析構函數由於類成員被修改而無法成爲noexcpet。

Example(示例)

 

Not all destructors are noexcept by default; one throwing member poisons the whole class hierarchy

不是所有的析構函數都默認是noexcept的;只要有一個(析構時,譯者注)拋出異常的成員,就會破壞整個繼承體系。

struct X {

    Details x;  // happens to have a throwing destructor

    // ...

    ~X() { }    // implicitly noexcept(false); aka can throw 

};

左右滑動查看更多

So, if in doubt, declare a destructor noexcept.

因此,如果有疑問,就將析構函數定義爲noexcept。

Note(注意)

 

Why not then declare all destructors noexcept? Because that would in many cases -- especially simple cases -- be distracting clutter.

爲什麼不將所有的析構函數都定義爲noexcept?因爲在很多場合,特別是簡單的場合這樣做只會增加干擾信息。

Enforcement(實施建議)

 

(Simple) A destructor should be declarednoexceptif it could throw.

(簡單)如果存在拋出異常的風險,則將析構函數定義爲noexcept。

原爲鏈接

 

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c37-make-destructors-noexcept

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章