您好,登錄后才能下訂單哦!
本篇內容介紹了“C++析構函數,內存釋放和swap操作分析”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
E.16:析構函數,內存釋放和swap操作永遠不能失敗
如果析構函數、swap操作或者內存釋放失敗了,我們不知道如何編寫可信賴的處理程序;也就是說,如果它因為異常退出或者只是沒有執行要求的操作。
Example, don't(反面示例)
class Connection {
// ...
public:
~Connection() // Don't: very bad destructor
{
if (cannot_disconnect()) throw I_give_up{information};
// ...
}
};
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.
為了編寫違反本規則的可信賴代碼示例進行了很多嘗試,例如網絡鏈接“拒絕關閉”。即使動作所有知識,也沒有人發現這么做的通用方法。偶然情況下,對于非常特殊的情況,你可以通過設定在將來清除處理時使用的某些狀態。例如我們可以將不想關閉的socket放入一個“壞socket”列表中,以便用正規的系統狀態清除程序進行檢查。我們看到的所有相關示例都是容易出錯的,特殊的,通常也有很多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.
標準庫假設析構函數,內存釋放函數(例如delete運算符),swap都不會拋出異常。如果它們異常,標準庫的不變量就被破壞了。
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運算符的內存釋放函數一定不要拋出異常。swap函數一定不要拋出異常。大多數析構函數默認情況下
Enforcement(實施建議)
Catch destructors, deallocation operations, and swaps that throw. Catch such operations that are not noexcept.
捕捉拋出異常的析構函數,內存釋放操作和swap函數。捕捉這些操作中沒有聲明為noexcept的情況。
“C++析構函數,內存釋放和swap操作分析”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。