In practice, the vector series in c ++ -- vector (unique_ptr () initialization (Ownership Transfer)

Source: Internet
Author: User

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.