日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

智能指针unique_ptr

發(fā)布時(shí)間:2023/11/27 生活经验 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 智能指针unique_ptr 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

unique_ptr的一些操作:

int main()
{unique_ptr<int> uptr(new int(10));//unique_ptr<int> uptr2(uptr);//報(bào)錯(cuò)//unique_ptr<int> uptr3 = uptr;//報(bào)錯(cuò)
unique_ptr<int> uptr2 = std::move(uptr);//轉(zhuǎn)移所有權(quán)//cout << *uptr << endl;//錯(cuò)誤,uptr si NULLreturn 0;
}

?

unique_ptr使用場景:

  1.為動(dòng)態(tài)申請的資源提供異常安全保證

傳統(tǒng)情況,可能會(huì)因?yàn)楫惓6鴽]有走到delete部分,如下:

void func()
{int *p = new int(10);//maybe throw exceptionif (NULL != p){delete p;p = NULL;}
}

使用unique_ptr,只要unique_ptr指針創(chuàng)建成功,析構(gòu)函數(shù)就一定會(huì)被調(diào)用,如下:

void func()
{unique_ptr<int> uptr(new int(10));//maybe throw exception
}

  2.返回函數(shù)內(nèi)動(dòng)態(tài)申請資源的所有權(quán)

unique_ptr<int> func(int value)
{unique_ptr<int> uptr(new int(value));return uptr;
}int main()
{unique_ptr<int> uptr2 = func(10);cout << *uptr2 << endl;return 0;
}

  3.在容器內(nèi)保存指針

int main()
{vector<unique_ptr<int>> vec;unique_ptr<int> uptr(new int(10));vec.push_back(std::move(uptr));return 0;
}

  4.管理動(dòng)態(tài)數(shù)組

int main()
{unique_ptr<int[]> uptr(new int[5]{1, 2, 3, 4, 5});uptr[0] = 100;cout << uptr[0] << endl;return 0;
}

?

轉(zhuǎn)載于:https://www.cnblogs.com/chen-cai/p/9566593.html

總結(jié)

以上是生活随笔為你收集整理的智能指针unique_ptr的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。