溫馨提示×

溫馨提示×

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

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

C++析構(gòu)函數(shù),內(nèi)存釋放和swap操作分析

發(fā)布時間:2021-11-24 16:37:54 來源:億速云 閱讀:219 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容介紹了“C++析構(gòu)函數(shù),內(nèi)存釋放和swap操作分析”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

E.16:析構(gòu)函數(shù),內(nèi)存釋放和swap操作永遠不能失敗

Reason(原因)

如果析構(gòu)函數(shù)、swap操作或者內(nèi)存釋放失敗了,我們不知道如何編寫可信賴的處理程序;也就是說,如果它因為異常退出或者只是沒有執(zhí)行要求的操作。

Example, don't(反面示例)

class Connection {
   // ...
public:
   ~Connection()   // Don't: very bad destructor
   {
       if (cannot_disconnect()) throw I_give_up{information};
       // ...
   }
};

Note(注意)

Many have tried to write reliable code violating this rule for examples, such as a network connection that "refuses to close". To the best of our knowledge nobody has found a general way of doing this. Occasionally, for very specific examples, you can get away with setting some state for future cleanup. For example, we might put a socket that does not want to close on a "bad socket" list, to be examined by a regular sweep of the system state. Every example we have seen of this is error-prone, specialized, and often buggy.

為了編寫違反本規(guī)則的可信賴代碼示例進行了很多嘗試,例如網(wǎng)絡(luò)鏈接“拒絕關(guān)閉”。即使動作所有知識,也沒有人發(fā)現(xiàn)這么做的通用方法。偶然情況下,對于非常特殊的情況,你可以通過設(shè)定在將來清除處理時使用的某些狀態(tài)。例如我們可以將不想關(guān)閉的socket放入一個“壞socket”列表中,以便用正規(guī)的系統(tǒng)狀態(tài)清除程序進行檢查。我們看到的所有相關(guān)示例都是容易出錯的,特殊的,通常也有很多bug。

Note(注意)

The standard library assumes that destructors, deallocation functions (e.g., operator delete), and swap do not throw. If they do, basic standard-library invariants are broken.

標(biāo)準(zhǔn)庫假設(shè)析構(gòu)函數(shù),內(nèi)存釋放函數(shù)(例如delete運算符),swap都不會拋出異常。如果它們異常,標(biāo)準(zhǔn)庫的不變量就被破壞了。

Note(注意)

Deallocation functions, including operator delete, must be noexcept. swap functions must be noexcept. Most destructors are implicitly noexcept by default. Also, make move operations noexcept.

包含delete運算符的內(nèi)存釋放函數(shù)一定不要拋出異常。swap函數(shù)一定不要拋出異常。大多數(shù)析構(gòu)函數(shù)默認情況下

Enforcement(實施建議)

Catch destructors, deallocation operations, and swaps that throw. Catch such operations that are not noexcept.

捕捉拋出異常的析構(gòu)函數(shù),內(nèi)存釋放操作和swap函數(shù)。捕捉這些操作中沒有聲明為noexcept的情況。

“C++析構(gòu)函數(shù),內(nèi)存釋放和swap操作分析”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細節(jié)

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

c++
AI