226 points
13 6 3

In C++, pointers are often used for allocating resources. Below is one typical use of pointers in C++

void function()
    Resource* ptr = new Resource();     // allocate resources

    // do something

    delete ptr;                         // free resourcess

In simple cases like this, you are not likely to forget to free allocated resources. However, in the case below:

void function(int x)
    Resource* ptr = new Resource();     // allocate resources

    if(x == -1)

    // do something

    delete ptr;                         // free resourcess

Many pepple don’t remember to deallocate in case x == -1.and this may lead to memory leak. This is when smart pointers come to the rescure. Their nature is classes for managing pointers and memory deallocation will take place in classes’s constructors, which are automatically called when going out of scope.

In C++, there are 4 types of smart pointer: std::auto_ptr (deprecated since C++17), std::shared_ptrstd::unique_ptr and std::weak_ptr.

The word “unique” in name of this kind of pointer suggests that a only one unique_pr can mangage a allocated memory region.

Syntax of a unique_ptr:

std::unique_ptr<DataType> ptr;

There are 2 ways to initialize a unique_ptr:

Way 1: Use constructor:

std::unique_ptr<Resource> res(new Resource);

Way 2: Use make_unique()

unique_ptr<Resource> pRes = make_unique<Resource>();

Normally, make_unique() is prefered over constructors when initializing unique_ptr.

For dereferencing, you just use operator like normal pointers:

Resource resObj = *pRes;

Here is the completed code:

#include <iostream>
#include <memory>   // for unique_ptr

using namespace std;

class Resource
    Resource(int _val)
        this->val = _val;

    int getVal() const
        return this->val;
    int val;

int main()
    unique_ptr<Resource> pRes(new Resource(10));
    Resource resObj = *pRes;
    cout << resObj.getVal();

In this article I have shown you why we need smart pointers and how to use make_unique() function to initialize a smart pointer. If you find the content of this article helpful, please give ayes orheart.

Happy coding !

More Posts

const_cast in C++ hhh98hd - Aug 11
-> operator in C++ hhh98hd - Aug 7
Initialize a pointer C++ hhh98hd - Aug 24
Get the size of an array C++ hhh98hd - Aug 5
Incompatible types in assignment of 'char*' to char hhh98hd - Aug 3
Invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] hhh98hd - Aug 4
What are virtual functions in C++ hhh98hd - Aug 18
How to declare two dimensional array using pointers in c-C++ hhh98hd - Aug 3
C++ Program to Find the Number of Vowels and Consonants in a String. Ahsan29 - May 7
C++ program accept five integer from user that will be stored in an array using pointer and print them in reverse order. Ahsan29 - May 7