本篇內(nèi)容介紹了“C++析構(gòu)函數(shù),內(nèi)存釋放和swap操作分析”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!
創(chuàng)新互聯(lián)建站是專業(yè)的臨泉網(wǎng)站建設(shè)公司,臨泉接單;提供成都做網(wǎng)站、成都網(wǎng)站設(shè)計,網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進行臨泉網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!
E.16:析構(gòu)函數(shù),內(nèi)存釋放和swap操作永遠不能失敗
如果析構(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};
// ...
}
};
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.
標準庫假設(shè)析構(gòu)函數(shù),內(nèi)存釋放函數(shù)(例如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運算符的內(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)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!