Unique_ptr_c++11

Source: Internet
Author: User

Unique_ptr replaces the original auto_ptr, pointing to the object is unique, that is, the same time can only have unique_ptr point to the given object (and auto_ptr different is the ban copy semantics,
Replace with mobile semantics)

The Unique_ptr object life cycle is consistent with its scope range, from creation until it leaves the scope

Unique_ptr pointer and its bound object relationship: During the life cycle of the smart pointer, it can change its bound object, can be re-specified by reset (), can release its ownership through the release method, transfer its ownership by moving semantics

First, the mode of initialization
Through new
Unique_ptr<investment> Up (new Investment ());

Through the normal pointer
Investment *PINV = new investment ();
Unique_ptr<investment> up1 (PINV);

by Make_unique
Auto PINV = make_unique<investment> ();

Through the move () function
unique_ptr<investment> up1 = Std::move (UP);


Note: Unique_ptr cannot be duplicated or copied, the following code will make an error:
Unique_ptr<investment> Up1 (UP); Error, can not is copy
Unique_ptr<investment> up2 = up; Error, can not is assigned

However, unique_ptr can be used as the return value of a function:
Unique_ptr<investment> getptr (); function Getthe Unique pointer
unique_ptr<investment> PINV = GetPtr (); Ok


UNIQUE_PTR Basic Operation
Unique_ptr<investment> pinvestment; Create an empty smart pointer
Pinvestment.reset (new investment ()); Bind dynamic Object
Investment *pi = Pinvestment.release (); Release ownership
Pi= nullptr; Explicitly destroys the object, while the smart pointer changes to a NULL pointer.


Managing dynamic arrays
Because Unique_ptr has std::unique_ptr<t[]> overloaded functions, it can be used to manage array resources
Unique_ptr<int[]> Parray (New int[3]{1,3,3});

Unique_ptr_c++11

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.