实战c++中的vector系列--vectorlt;unique_ptrlt;gt;gt;初始化(全部权转移)
生活随笔
收集整理的這篇文章主要介紹了
实战c++中的vector系列--vectorlt;unique_ptrlt;gt;gt;初始化(全部权转移)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
C++11為我們提供了智能指針,給我們帶來了非常多便利的地方。
那么假設(shè)把unique_ptr作為vector容器的元素呢?
形式如出一轍:vector<unique_ptr<int> > vec;
可是怎么給vec加入元素呢?
看以下:
#include<iostream> #include<vector> #include <memory> using namespace std; int main() {vector<unique_ptr<int>> vec;vec.push_back(1);//錯誤return 0; }那么先定義一個unique_ptr,再進行push_back():
#include<iostream> #include<vector> #include <memory> using namespace std; int main() {vector<unique_ptr<int>> vec;unique_ptr<int> sp(new int(126));vec.push_back(sp);//嘗試引用已刪除的函數(shù)return 0; }這就是unique智能指針的全部權(quán)問題。這個時候就須要使用std::move:
#include<iostream> #include<vector> #include <memory> using namespace std; int main() {vector<unique_ptr<int>> vec;unique_ptr<int> sp(new int(126));//vec.push_back(1);vec.push_back(std::move(sp));//嘗試引用已刪除的函數(shù)cout << *vec[0]<< endl; // 輸出126//cout << *sp << endl;return 0; }可是此時,上面代碼的sp編程了什么呢? 使用*取值看一下,結(jié)果程序崩潰,原因何在?
就是此時sp已經(jīng)釋放,全部權(quán)轉(zhuǎn)移了!
轉(zhuǎn)載于:https://www.cnblogs.com/lytwajue/p/7398748.html
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的实战c++中的vector系列--vectorlt;unique_ptrlt;gt;gt;初始化(全部权转移)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android Tcp操作
- 下一篇: Map集合遍历方法