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