Unique_ptr is a smart pointer to exclusive ownership. It provides a strict semantic ownership, including: 1. Have the object to which it points. 2. The copy structure cannot be performed, and the copy assignment operation cannot be performed. That is to say, we cannot get two unique_ptr pointing to the same object. However, you can perform the move construction and move value assignment operations. 3. Save the pointer to an object. When it is deleted and released (for example, it leaves a certain scope), it will use a given deleteer to release the object it points. You can use unique_ptr to implement the following functions: 1. Provides exceptional security for dynamically applied memory. 2. Pass ownership of the dynamically applied memory to a function. 3. Return the dynamically applied memory ownership from a function. 4. Save the pointer in the container. 5. All functions that auto_ptr should have (but cannot be implemented in C ++ 03. The following is a piece of traditional security exceptionCode:
1X *F ()2 {3X * P =NewX;4//Some operations may throw an exception.5ReturnP;6}
The solution is to use unique_ptr to manage the ownership of the object and release the object.
1X *F ()2 {3Unique_ptr <x> P (NewX );4//Some operations may throw an exception.5ReturnP. Release ();6}
IfProgramIf an exception is thrown during execution, unique_ptr will release the object to which it points. However, unless we really need to return a built-in pointer, we can also return a unique_ptr.
1Unique_ptr <x>F ()2 {3Unique_ptr <x> P (NewX );4//Some operations may throw an exception.5ReturnP;6}
Now, we can use the function f () as follows ():
1 void G () 2 { 3 unique_ptr
q = f ();
///
use a moving constructor
4 q-> dosomething ();
///
Use q
5 X = * q;
///
copy the object pointed to by the pointer q
6 }< span style =" color: #008000; ">///
when the function exits, Q and the objects it points to are deleted and released.
unique_ptr has mobile semantics, so we can use the right value returned by function f () to initialize Q, in this way, the ownership is simply transferred to Q.