C++

Use of C++ unique_ptr

The smart pointers are used to allocate the resource dynamically. Many types of smart pointers are used in C++ for various purposes, such as auto_ptr, unique_ptr, and shared_ptr. The auto_ptr pointer is deprecated in the new version of C++. The unique_ptr is used in replacement of the auto_ptr. The object of this pointer can take ownership of the pointer. The object of this pointer owns the pointer uniquely, and no other pointer can point to the object. The unique_ptr deletes the objects automatically. This pointer manages those objects if the objects are destroyed, or the value of the object is changed or the reset() function is called. The features of the unique_ptr and the uses of this pointer are discussed in this tutorial.

Major Components:

Two main components of the unique_ptr object are provided below:

A. Stored Pointer:

It is used to manage the objects created by a unique pointer. It is created at the time of pointer creation, and it can be changed in different ways.

B. Stored Deleter:

It takes the argument of the stored pointer type that is used to delete the managed object. It is also created at the time of pointer creation, and it can be changed by different ways.

Example 1: Create a Pointer Object of a Class With Constructor

The way to declare the unique pointer objects of a class and access the method of the class is by using the objects as shown in the following example. A class with a constructor and a public method has been declared in the code. The constructor has three arguments. The first unique pointer has been created by calling the constructor with three argument values. The Result() method is called by the pointer object that calculates the sum of three argument values of the constructor. Next, the second unique pointer object is created without calling the constructor, and the first pointer is moved to the second pointer. The Result() method is called by the second pointer object.

//Include necessary libraries

#include <iostream>

#include <memory>

usingnamespace std;

//Define the class
class Addition {

    int number1, number2, number3;
    public:
    //Declare the constructor
    Addition(int a, int b, int c)
    {
        number1 = a;
        number2 = b;
        number3 = c;
    }
    //Declare method to calculate the sum
    int Result()
    {
        return number1 + number2 + number3;
    }
};
int main()
{
    //Declare the first pointer
    unique_ptr pointer1(new Addition(45, 55, 30));

    cout<<"The result of sum using the first pointer :"<Result() <<"\n";
    //Declare the second pointer
    unique_ptr pointer2;
    //Move the first pointer to the second pointer
    pointer2 = move(pointer1);

    cout<<"The result of sum using the second pointer :"<Result() <<"\n";
    return0;
}

Output:

The following output will appear after executing the above code. The sum of 45, 55, and 30 is 130 that has been printed for both pointers.

Example 2: Create a Pointer Object of a Class With Constructor and Destructor

The way to declare a unique pointer object of a class with constructor and destructor has been shown in the following example. The class contains a constructor with one argument, a public method named Display() to the value of the class variable, and a destructor that will print a destroy message before destroying the object of the class. The Display() method is called after creating the unique pointer object in the code.

//Include necessary libraries

#include <iostream>

#include <memory>

usingnamespace std;

//Define the class
class Customer
{
    string name;

    public:
    //Declare the constructor
    Customer(string n)
    {
        name = n;
        cout<<"The resource is allocated.\n";
    }

    //Declare method to print the customer name
    void Display()
    {
        cout<<"The name of the customer is: "<< name <<"\n";
    }

    //Declare the destructor
    ~Customer()
    {
        cout<<"The resource is destroyed.\n";
    }
};
int main()
{
    //Allocate the Resource object that is owned by the unique_ptr
    unique_ptruPointer{ new Customer("Mir Abbas") };
    uPointer->Display();
    return0;
}

Output:

The following output will appear after executing the above code:

Example 3: Check the Pointer After Transferring the Ownership

The way to check the ownership of the unique pointer has shown in the following example by creating two unique pointers of a class. A class with two string variables and a public method has been declared in the code. The Book_details() method of the class is called after creating the first unique pointer object of the class. Next, the second unique pointer object has been created, and the first pointer has been moved to the second pointer that destroys the first pointer. The ownership of both pointers should be checked later.

//Include necessary libraries

#include <iostream>

#include <memory>

usingnamespace std;

//Define the class
class Book {

    string title = "The C++ Programming Language";
    string author = "Bjarne Stroustrup";

    public:
    //Declare method to print book details
    voidBook_details()
    {
        cout<<"Book Name: "<< title <<"\n";
        cout<<"Author Name: "<< author <<"\n";
    }
};
int main()
{
    //Declare the first pointer
    unique_ptr pointer1(new Book());

    pointer1->Book_details();
    //Declare the second pointer
    unique_ptr pointer2;
    //Move the first pointer to the second pointer
    pointer2 = move(pointer1);

    //Check the first pointer
    if (static_cast(pointer1)) cout<<"The first poiner is not null\n";
    elsecout<<"The first poiner is null\n";
    //Check the second pointer
    if (static_cast(pointer2)) cout<<"The second poiner is not null\n";
    elsecout<<"The second poiner is null\n";

    return0;
}

Output:

The following output will appear after executing the above code. According to the output, the ownership of the first pointer was removed, and the message, “The first pointer is null” has printed for the first pointer. The ownership of the second pointer exists, and the message, “The first pointer is not null” has printed for the second pointer:

Conclusion:

The purposes of using a unique pointer in C++ programming have been described in this tutorial by using multiple examples. The ways to create a unique pointer, transfer the ownership of the pointer, and check the current ownership of the pointer have been explained here to help the readers to know the use of the unique pointer properly.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.