智能指针unique_ptr
生活随笔
收集整理的這篇文章主要介紹了
智能指针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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 比亚迪秦多少钱啊?
- 下一篇: Oracle中分页查询语句