C++11 provides us with smart pointers, which brings us a lot of convenience.
So what if the unique_ptr is the element of a vector container?
form the same:vector<unique_ptr<int> > vec;
But how do you add elements to VEC?
See below:
#include<iostream>#include<vector>#include <memory>usingnamespacestd;int main(){ vector<unique_ptr<int>> vec; vec.push_back(1);//错误 return0;}
First define a unique_ptr and then Push_back ():
#include<iostream>#include<vector>#include <memory>usingnamespacestd;int main(){ vector<unique_ptr<int>> vec; unique_ptr<int> sp(newint(126)); vec.push_back(sp);//尝试引用已删除的函数 return0;}
This is the ownership of the unique smart pointer, which requires the use of Std::move:
#include <iostream>#include <vector>#include <memory>using namespace STD;intMain () { vector<unique_ptr<int>> VEC; unique_ptr<int> Sp (New int(126));//vec.push_back (1);Vec.push_back (STD:: Move (sp));//Try referencing a deleted function cout<< *vec[0]<< Endl;//Output 126 //cout << *sp << Endl; return 0;}
But at this point, what does the SP of the above code program do? Using the * value to see the results of the program crashes, why?
This is where the SP has been released and ownership has shifted!
Vector series--vector<unique_ptr<>> initialization in combat C + + (ownership transfer)