溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++中怎么保證析構(gòu)函數(shù)不拋出異常

發(fā)布時間:2021-07-28 11:43:03 來源:億速云 閱讀:258 作者:Leah 欄目:大數(shù)據(jù)

C++中怎么保證析構(gòu)函數(shù)不拋出異常,相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

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ì)錯誤,更好的選擇是中止程序。

Note(注意)
C++中怎么保證析構(gòu)函數(shù)不拋出異常    

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.

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

Example(示例)
C++中怎么保證析構(gòu)函數(shù)不拋出異常    

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

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

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.

因此,如果有疑問,就將析構(gòu)函數(shù)定義為noexcept。

Note(注意)
C++中怎么保證析構(gòu)函數(shù)不拋出異常    

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)樵诤芏鄨龊希貏e是簡單的場合這樣做只會增加干擾信息。

Enforcement(實(shí)施建議)
C++中怎么保證析構(gòu)函數(shù)不拋出異常    

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

(簡單)如果存在拋出異常的風(fēng)險,則將析構(gòu)函數(shù)定義為noexcept。


看完上述內(nèi)容,你們掌握C++中怎么保證析構(gòu)函數(shù)不拋出異常的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI