What is std::unique_ptr? How to Use std::unique_ptr?

The std::unique_ptr is basically a template smart pointer class. It is smart about cleaning up the allocated memory. Template class means this can work with different data types. We have to provide the actual pointer in time of constructing the object. In the desctuctor, the pointer is freed. Another thing is, the usual pointer operator like *, &, -> etc are overloaded such that we can use this just like any other pointer.

I think it is better to start with a problem that this std::unique_ptr helps us to solve. It is not like we can not solve this problem otherwise but std::unique_ptr just make our life easy.

Memory Management Problem in C++

In the constructor of class CA in the above program, we allocated some memory and printed a confirmation message. Similarly, in destructor, we de-allocated the memory and printed the de-allocation confirmation message.

In the main function, we created an object of type CA by calling new operator and assign the pointer of the object to a.
If we run this program, the output will be like this.

There is no print for memory de-allocation. The means the allocated memory is not freed. If you have this type of code in a function that will get called repeatedly, the program will lead to significant memory leak.
One solution of this problem is to delete the object by calling the delete operator before returning from the function.

But deleting object something is very cumbersome. Lets have a look at the example below.

In this program we have four return points. We have to remember to delete the object from all four places.

Solution with std::unique_ptr

This std::unique_ptr helps to solve this difficulty. You can define a std::unique_ptr for our class and use the pointer just like the example before. But you don’t have to free that. The pointer will be freed automatically.

Now the output will be like this.

That means, memory is allocated as well as freed. You might already noticed that we did not call delete explicitly. Even if we have multiple return points we don’t have to explicitly delete from anywhere. This is a great way to avoid mistake.

The syntax of creating a std::unique_ptr is:

Implementation of std::unique_ptr

This is basically a template smart pointer. We have to provide a pointer in time of creating the std::unique_ptr object. In the desctuctor, the pointer is freed. Another thing is, the usual pointer operator like *, &, -> etc are overloaded such that we can use this just like any other pointer.

In the article below, I showed how to create smart pointer in C++.

The actual implementation of std::unique_ptr might not be exactly same but would be very similar. The above article will give you the idea on how we can create different types of smart pointers in C++.

Leave a Reply

Your email address will not be published. Required fields are marked *