溫馨提示×

溫馨提示×

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

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

C++中為什么直接擁有一個(gè)對象所有權(quán)時(shí)永遠(yuǎn)不要拋出異常

發(fā)布時(shí)間:2021-11-25 13:56:09 來源:億速云 閱讀:92 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要介紹“C++中為什么直接擁有一個(gè)對象所有權(quán)時(shí)永遠(yuǎn)不要拋出異?!保谌粘2僮髦?,相信很多人在C++中為什么直接擁有一個(gè)對象所有權(quán)時(shí)永遠(yuǎn)不要拋出異常問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C++中為什么直接擁有一個(gè)對象所有權(quán)時(shí)永遠(yuǎn)不要拋出異?!钡囊苫笥兴鶐椭〗酉聛?,請跟著小編一起來學(xué)習(xí)吧!

E.13: 直接擁有一個(gè)對象所有權(quán)時(shí)永遠(yuǎn)不要拋出異常

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í)用的文章!

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

免責(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)容。

c++
AI