In practice, the vector series in c ++ -- vector (unique_ptr () initialization (Ownership Transfer)
C ++ 11 provides us with smart pointers and brings us a lot of convenience.
What if unique_ptr is used as an element of the vector container?
The format is exactly the same:vector > vec;
But how to add elements to vec?
See the following:
# Include
# Include
# Include
Using namespace std; int main () {vector
> Vec; vec. push_back (1); // return 0 ;}
Then define a unique_ptr and then perform push_back ():
# Include
# Include
# Include
Using namespace std; int main () {vector
> Vec; unique_ptr
Sp (new int (126); vec. push_back (sp); // try to reference the deleted function return 0 ;}
This is the ownership of the unique smart pointer. In this case, you need to use std: move:
# Include
# Include
# Include
Using namespace std; int main () {vector
> Vec; unique_ptr
Sp (new int (126); // vec. push_back (1); vec. push_back (std: move (sp); // try to reference the deleted function cout <* vec [0] <endl; // output 126 // cout <* sp <endl; return 0 ;}
But what is the sp programming in the above Code? Use the * value to check the cause of the program crash?
The sp has been released and ownership has been transferred!