C++

C++ Std:: Unique_Ptr

A unique pointer is a smart pointer. To discuss what a Unique pointer is, we have to understand what Smart pointers are. The process of adding and removing items can be automated with smart pointers. Smart pointers mean that when you call now you do not have to call delete and in many cases with smart pointers, we do not even have to call new. Smart pointers are best in that way to make all of that happen.

Whenever the smart pointer is created, it will automatically call new and allocate the memory heap. Then, based on which smart pointer you use, that memory will automatically become free. Let’s now get to our main subject, the Unique Pointer. A unique pointer will be eliminated when it goes out of scope. Unique pointers cannot be copied to the other pointer whether it is of the same datatype because a unique pointer is pointing to a memory. If the unique pointer has been copied, that means at a time two pointers are pointing to the same memory heap. So, that is why we cannot copy unique pointers. Unique pointers make sure that they delete their objects with them.

Syntax

The syntax to create a Unique pointer is as follows:

std::unique_ptr<int> p(new int);

Here, the dynamically created object is also destroyed when the unique pointer itself gets destroyed.

Example # 01:

To understand Unique pointers in more depth, we will be giving an example. In this example, we’ve defined a structure named Person. “Person” has a constructor which takes a string as a parameter and prints the value. It also has a destructor which upon destruction will print “Deleted” so that we can understand that the person is destroyed. Inside the main method, we have declared a unique pointer and passed it a value “Jack.”.

Now, this pointer will take “Jack” and pass it to the memory it is pointing to that is the Structure “Person”. The value “Jack” will go to the constructor and will get printed. After that, the unique pointer will automatically delete the object and “Deleted!” will be printed on the screen. Now, let’s run and execute our code to see the output.

#include <memory>

#include <iostream>

using namespace std;
struct Person
{
  Person (string n):Name (n)
{
cout<<n<<endl;
}
   ~Person ()
  {
cout<< "Deleted!";
  }
  string Name;
};
int
main ()
{
  auto p = make_unique ("Jack");
  return 0;
}

Our code has been executed successfully and gives us the expected output. The unique pointer has taken the value “Jack” and passed it to the constructor because it was pointing toward the object of the “Person” Structure. The constructor has printed the value. After that, “Deleted” is printed. Now, here, we have only printed the value. But in real-time scenarios, we can perform all the operations and after the operation is performed the object of structure or class will itself get destroyed.

Example # 02:

In this example, we have tried to explain the unique constructor in details. We have also tried to create a unique pointer differently so that you can understand the different syntaxes and approaches to create unique pointers. To perform this example, we have created a class named “UniquePtr”. In this class, we have a constructor of this class and a destructor. In the earlier example, we explained that we can do whatever operation we want in the constructor. In this example, we have tried to do so to give you a hands-on experience.

So, in the constructor first, we have printed “In constructor” to let the user know that we are in our constructor at the moment. After that, we have declared two integers “x” and “y” which hold the values of “2” and “3” respectively. After that, we declared another variable which is also an integer: “z”. We have summed up or added the values of “x” and “y” and stored the output in the “z” integer. In line number 13, we have printed “Operation Performed” and we have also printed the value of “z” against it so that we can let the user know that the operation is performed and the value after the operation is as follows.

In our destructor, we have simply printed “In Destructor”. In the main method, we have simply created the unique pointer and passed it the class name so that it can understand what memory it has to point towards. Now, we will execute our code to verify the output.

#include <memory>

#include <iostream>

using namespace std;
class UniquePtr
{
    public:
UniquePtr()
    {
cout<<”In constructor”<<endl;
        int x = 2;
        int y = 3;
        int z = x + y;
cout<<”Operation Performed =<<z<<endl;
    }
    ~UniquePtr()
    {
cout<<”In Destructor”<<endl;
    }
};
int main ()
{
  std::unique_ptr x = std::unique_ptr(new UniquePtr);
  return 0;
}

After our code is executed, the following is the output we will get from the system. One thing to explain here is that, in our main method we did not create any object of the class to access it. Instead, we only created a unique pointer and pointed it toward our class. The system has printed “In constructor” which means that it has gone in the constructor and the other printed line also explains that the system has performed the addition operation on the integers and printed the value against the printed message. Lastly, the compiler moved inside the destructor, printed the message, and destroyed the object of the class. One thing to note here is that we did not create or delete the memory heap here. This whole thing was done by our unique pointer.

Conclusion

In this guide, we discussed a type of smart pointer which is a unique pointer. Unique pointers are smart pointers that help us with memory allocation and memory management. So, to understand unique pointers we first explained smart pointers and unique pointers theoretically. After that, we explained the syntax of unique pointers. Multiple examples were performed under different scenarios to make the reader understand unique pointers practically.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.