您好,登錄后才能下訂單哦!
這篇文章主要介紹“C++中為什么直接擁有一個(gè)對象所有權(quán)時(shí)永遠(yuǎn)不要拋出異?!保谌粘2僮髦?,相信很多人在C++中為什么直接擁有一個(gè)對象所有權(quán)時(shí)永遠(yuǎn)不要拋出異常問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C++中為什么直接擁有一個(gè)對象所有權(quán)時(shí)永遠(yuǎn)不要拋出異?!钡囊苫笥兴鶐椭〗酉聛?,請跟著小編一起來學(xué)習(xí)吧!
Reason(原因)
That would be a leak.
那樣做會發(fā)生泄露。
Example(示例)
void leak(int x) // don't: may leak{ auto p = new int{7}; if (x < 0) throw Get_me_out_of_here{}; // may leak *p // ... delete p; // we may never get here}
One way of avoiding such problems is to use resource handles consistently:
避免這種問題的一種方法是始終如一地使用資源句柄。
void no_leak(int x){ auto p = make_unique<int>(7); if (x < 0) throw Get_me_out_of_here{}; // will delete *p if necessary // ... // no need for delete p}
Another solution (often better) would be to use a local variable to eliminate explicit use of pointers:
另外一個(gè)解決方案(通常更好)是用局部變量來避免使用指針。
void no_leak_simplified(int x){ vector<int> v(7); // ...}
Note(注意)
If you have local "things" that requires cleanup, but is not represented by an object with a destructor, such cleanup must also be done before a throw. Sometimes, finally() can make such unsystematic cleanup a bit more manageable.
如果局部的“某物”需要清除,但卻沒有實(shí)現(xiàn)為一個(gè)具有析構(gòu)函數(shù)的對象,這些清理操作也必須在拋出異常之前進(jìn)行。有時(shí),finally函數(shù)可以讓這種非系統(tǒng)化的清理動作稍微容易管理一些。
到此,關(guān)于“C++中為什么直接擁有一個(gè)對象所有權(quán)時(shí)永遠(yuǎn)不要拋出異?!钡膶W(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。