Unique_ptr of C ++ 11

Source: Internet
Author: User
Tags exit in

Unique_ptr of C ++ 11

 

Many new features have been added to C ++ 11, and unique_ptr is unique. It is simple and effective for dynamically allocated memory objects. Although it is not omnipotent, It is enough: You can use simple syntax to manage dynamically allocated objects.

 

Basic Syntax:

Unique_ptr Is a template class, you can easily construct a unique_ptr object, as follows:

 

std::unique_ptr
 
   p( new foo(42) );
 

After the construction is complete, you can operate the object like a normal pointer. For example, operator * and operator-> operators work as expected.

 

 

Just as you can use the unique_ptr class like a normal pointer, the most important thing is that you can automatically destroy this object when unique_ptr is out of scope. You don't have to worry about memory leakage caused by the deletion of an exit in the scope. Even if an exception occurs, it can automatically destroy objects.

 

Unique_ptr and container:

So far, everything has been lucky. According to the Standard C ++ syntax, you can also implement the above functions. In fact, auto_ptr (C ++ 11 has discarded it) is a tool that can be used as a RAII package.

No, auto_ptr does not work properly. Even for some basic operations, auto_ptr is not doing well. For example, if you need to create a container for storing auto_ptr, this will be a big problem.

 

I have written a simple code to understand the relationship between objects and containers:

 

Class A {public: A () {cout <A ctor called... <endl ;}a (const A &) {cout <vec; for (int I = 0; I <5; ++ I) {cout <I = <I <endl; vec. push_back (A (); // construct the object and copy it. See the running result of the following code} return 0 ;}

The execution result of the above Code is:

 

 

We can see that the copy constructor is called in the execution result of the above Code.

 

[Continue:

C ++ 11 has added the right value reference and move semantics to solve these problems. Fortunately, after repair, unique_ptr can be stored in the container, even if the container is resize and moved, it has the correct semantics. When the container is destroyed, the resources managed by these pointers can also be destroyed normally.

 

Uniqueness and move semantics:

What exactly does unique mean? Just as literally, when you create a unique_ptr, you claim that the pointer is unique and unambiguous, and only you can have it, it is impossible for others to copy it.

For example, a common pointer has the following code:

Foo * p = new foo (useful object );

Make_use (p); // the parameter of the make_use function is an object pointer.

Here, I have assigned an object and a pointer p points to it. What happens to the pointer p when I call the make_use function? Will make_use copy the pointer? Will the memory be released after the call is completed? In other words, it is just a simple borrow. After a while, the pointer will remain intact, so that the caller can release space?

 

We cannot answer either of the above questions because C ++ has not made any agreement on how to use pointers. You can only view your own code, view your memory and documents.

 

Fortunately, with unique_ptr, these problems are not a problem. If you pass a pointer to another routine (when the function understands it ). You will not copy the pointer (because it is unique). Even if you do that, the compiler will not agree.

 

Pointer owner:

First, let's take a simple example: Create a unique_ptr and store it in a container. As a newbie of unique_ptr, you may write the following code:

 

std::unique_ptr
 
   q( new foo(42) );v.push_back( q );
 

This seems reasonable, but it will bring me into a gray zone: who is the owner of the pointer, will the container release the pointer at some point in its lifecycle? Or does it have to be released by the Creator?

 

 

In the face of these confusions, unique_ptr prohibits such code. Compiling such code will cause compilation errors.

 

Anyway, the problem here is that we only allow a copy of the pointer. If you want to give the object to another object, you must call the move function, that is, you must discard the ownership of the object.

For example:

v.push_back( std::move(q) );

 

After the preceding statement is executed, q has become empty because q has abandoned the ownership of the object and handed the ownership to the container.

 

Move semantics can be used in any place where you need to create a "right value reference. For example, the following code:

Return q;

If a unique_ptr is returned, no special code is required.

Also, creating a temporary object to a function that requires unique_ptr does not require special processing. For example:

Process (std: unique_ptr (New foo (41 )));

 

Legacy Code: The old program is actually compatible.

When you are using unqiue_ptr. What you need now is an underlying pointer. There are two methods:

 

do_something( q.get() );          //retain ownershipdo_something_else( q.release() ); //give up ownership

The get function does not forward ownership. Therefore, the get function is not recommended in most cases. Because once you release the true pointer of the unique_ptr package to the function, it is difficult for you to control what operations the function will perform on the pointer. That is to say, you must be cautious with your function to ensure that the function simply borrows the pointer.

 

The release function is a more reliable method. When you call release to the pointer q like above, you have already declared that this object is no longer under my control, now it's yours.

 

When your code is relatively mature, this will not happen frequently.

Also, when unique_ptr is passed to the function as a reference object, it is as follows:

 

void inc_baz( std::unique_ptr
 
   &p ){    p->baz++;}
 

Because it is a reference, you do not have to worry that the pointer will be copied or blurred by the owner.

 

 

To use auto_ptr, we only need to use the auto keyword in the Code for type inference. In fact, when we rewrite our code to use unqiue_ptr, we do not need to change more user code.

 

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.