"C + + Primer 12th Chapter" Unique_ptr

Source: Internet
Author: User

Unique_ptr

a unique_ptr owns the objects it manages, and unlike shared_ptr, Unique_ptr points to an object that can have only one user . When the unique_ptr is destroyed, the object it points to is also destroyed.

• Unlike shared_ptr, no make_shared_ptr-like standard function returns a unqiue_ptr, when a unique_ptr is defined, it needs to be bound to a pointer returned by new, like shared_ptr, Initialization unique_ptr must take the form of direct initialization:

unique_ptr<double> p1;              // P1 points to a double type  variable unique_ptr<int> P2 (newint(1024x768));  // P2 points to an int type with a value  of 1024x768 •

because only one unique_ptr owns the object it points to, Unique_ptr does not support normal copy or assignment operations.

Unqiue_ptr operation

Although we cannot copy or assign Unqiue_ptr, we can transfer the ownership of the pointer from one unqiue_ptr to another by calling release:

// transfer ownership from P1 (point to String Stegosaurus) to P2unqiue_ptr<string> P2 (p1.release ())      // release set P1 to null nqiue_ptr<string> P3 (thenewstring("Trex " ));p 2.reset (P3.release ())    //  Reset released the memory                          that the P2 originally pointed to //  Reset releases the memory it originally pointed to

Pass to the Unique_ptr parameter and return unique_ptr

• Although you cannot copy a unique_ptr, with one exception, we can copy or assign a unique_ptr that will be destroyed, such as returning a unique_ptr:

unique_ptr<int> Clone (int  p) {    return unique_ptr<int> (newint(P));}  

You can also return a copy of a local variable:

unique_ptr<int> Clone (int  p) {    unique_ptr<int> RET ( New int (P));       return ret;    }  

Note : For two pieces of code, the compiler knows that the object to be returned will be destroyed. In this case, the compiler performs a special copy.

"C + + Primer 12th Chapter" Unique_ptr

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.