Vector series--vector<unique_ptr<>> initialization in combat C + + (ownership transfer)

Source: Internet
Author: User

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)

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.