The Wayback Machine - https://web.archive.org/web/20240920065625/https://www.geeksforgeeks.org/smart-pointers-cpp/
Open In App

Smart Pointers in C++

Last Updated : 12 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Pointers in C++

Pointers are used for accessing the resources which are external to the program – like heap memory. So, for accessing the heap memory (if anything is created inside heap memory), pointers are used. When accessing any external resource we just use a copy of the resource. If we make any changes to it, we just change it in the copied version. But, if we use a pointer to the resource, we’ll be able to change the original resource.

Problems with Normal Pointers

Some Issues with normal pointers in C++ are as follows:

  • Memory Leaks: This occurs when memory is repeatedly allocated by a program but never freed. This leads to excessive memory consumption and eventually leads to a system crash. 
  • Dangling Pointers: A dangling pointer is a pointer that occurs at the time when the object is de-allocated from memory without modifying the value of the pointer.
  • Wild Pointers: Wild pointers are pointers that are declared and allocated memory but the pointer is never initialized to point to any valid object or address.
  • Data Inconsistency: Data inconsistency occurs when some data is stored in memory but is not updated in a consistent manner.
  • Buffer Overflow: When a pointer is used to write data to a memory address that is outside of the allocated memory block. This leads to the corruption of data which can be exploited by malicious attackers.

Example:

C++
// C++ program to demonstrate working of a Pointers
#include <iostream>
using namespace std;

class Rectangle {
private:
    int length;
    int breadth;
};

void fun()
{
    // By taking a pointer p and
    // dynamically creating object
    // of class rectangle
    Rectangle* p = new Rectangle();
}

int main()
{
    // Infinite Loop
    while (1) {
        fun();
    }
}


Output

Memory limit exceeded

Explanation: In function fun, it creates a pointer that is pointing to the Rectangle object. The object Rectangle contains two integers, length, and breadth. When the function fun ends, p will be destroyed as it is a local variable. But, the memory it consumed won’t be deallocated because we forgot to use delete p; at the end of the function. That means the memory won’t be free to be used by other resources. But, we don’t need the variable anymore, we need the memory.

In function, main, fun is called in an infinite loop. That means it’ll keep creating p. It’ll allocate more and more memory but won’t free them as we didn’t deallocate it. The memory that’s wasted can’t be used again. Which is a memory leak. The entire heap memory may become useless for this reason.

Smart Pointers

As we’ve known unconsciously not deallocating a pointer causes a memory leak that may lead to a crash of the program. Languages Java, C# has Garbage Collection Mechanisms to smartly deallocate unused memory to be used again. The programmer doesn’t have to worry about any memory leaks. C++ comes up with its own mechanism that’s Smart Pointer. When the object is destroyed it frees the memory as well. So, we don’t need to delete it as Smart Pointer will handle it.

A Smart Pointer is a wrapper class over a pointer with an operator like * and -> overloaded. The objects of the smart pointer class look like normal pointers. But, unlike Normal Pointers, it can deallocate and free destroyed object memory.

The idea is to take a class with a pointer, destructor, and overloaded operators like * and ->. Since the destructor is automatically called when an object goes out of scope, the dynamically allocated memory would automatically be deleted (or the reference count can be decremented).

Example:

C++
// C++ program to demonstrate the working of Smart Pointer
#include <iostream>
using namespace std;

class SmartPtr {
    int* ptr; // Actual pointer
public:
    // Constructor: Refer
    // https://www.geeksforgeeks.org/g-fact-93/ for use of
    // explicit keyword
    explicit SmartPtr(int* p = NULL) { ptr = p; }

    // Destructor
    ~SmartPtr() { delete (ptr); }

    // Overloading dereferencing operator
    int& operator*() { return *ptr; }
};

int main()
{
    SmartPtr ptr(new int());
    *ptr = 20;
    cout << *ptr;

    // We don't need to call delete ptr: when the object
    // ptr goes out of scope, the destructor for it is
    // automatically called and destructor does delete ptr.

    return 0;
}

Output
20

Difference Between Pointers and Smart Pointers

Pointer

Smart Pointer

A pointer is a variable that maintains a memory address as well as data type information about that memory location. A pointer is a variable that points to something in memory.It’s a pointer-wrapping stack-allocated object. Smart pointers, in plain terms, are classes that wrap a pointer, or scoped pointers.
It is not destroyed in any form when it goes out of its scopeIt destroys itself when it goes out of its scope
Pointers are not so efficient as they don’t support any other feature. Smart pointers are more efficient as they have an additional feature of memory management. 
They are very labor-centric/manual.They are automatic/pre-programmed in nature.

Note: This only works for int. So, we’ll have to create Smart Pointer for every object? No, there’s a solution, Template. In the code below as you can see T can be of any type.

Example:

C++
// C++ program to demonstrate the working of Template and
// overcome the issues which we are having with pointers
#include <iostream>
using namespace std;

// A generic smart pointer class
template <class T> class SmartPtr {
    T* ptr; // Actual pointer
public:
    // Constructor
    explicit SmartPtr(T* p = NULL) { ptr = p; }

    // Destructor
    ~SmartPtr() { delete (ptr); }

    // Overloading dereferencing operator
    T& operator*() { return *ptr; }

    // Overloading arrow operator so that
    // members of T can be accessed
    // like a pointer (useful if T represents
    // a class or struct or union type)
    T* operator->() { return ptr; }
};

int main()
{
    SmartPtr<int> ptr(new int());
    *ptr = 20;
    cout << *ptr;
    return 0;
}

Output
20

Note: Smart pointers are also useful in the management of resources, such as file handles or network sockets.

Types of Smart Pointers

C++ libraries provide implementations of smart pointers in the following types:

  • auto_ptr
  • unique_ptr
  • shared_ptr
  • weak_ptr

auto_ptr

Using auto_ptr, you can manage objects obtained from new expressions and delete them when auto_ptr itself is destroyed. When an object is described through auto_ptr it stores a pointer to a single allocated object.

Note: This class template is deprecated as of C++11. unique_ptr is a new facility with a similar functionality, but with improved security.

unique_ptr

unique_ptr stores one pointer only. We can assign a different object by removing the current object from the pointer. 

Unique pointers in C++

Example:

C++
// C++ program to demonstrate the working of unique_ptr
// Here we are showing the unique_pointer is pointing to P1.
// But, then we remove P1 and assign P2 so the pointer now
// points to P2.

#include <iostream>
using namespace std;
// Dynamic Memory management library
#include <memory>

class Rectangle {
    int length;
    int breadth;

public:
    Rectangle(int l, int b)
    {
        length = l;
        breadth = b;
    }

    int area() { return length * breadth; }
};

int main()
{
// --\/ Smart Pointer
    unique_ptr<Rectangle> P1(new Rectangle(10, 5));
    cout << P1->area() << endl; // This'll print 50

    // unique_ptr<Rectangle> P2(P1);
    unique_ptr<Rectangle> P2;
    P2 = move(P1);

    // This'll print 50
    cout << P2->area() << endl;

    // cout<<P1->area()<<endl;
    return 0;
}

Output
50
50

shared_ptr

By using shared_ptr more than one pointer can point to this one object at a time and it’ll maintain a Reference Counter using the use_count() method. 

Shared pointer in C++

C++
// C++ program to demonstrate the working of shared_ptr
// Here both smart pointer P1 and P2 are pointing to the
// object Addition to which they both maintain a reference
// of the object
#include <iostream>
using namespace std;
// Dynamic Memory management library
#include <memory>

class Rectangle {
    int length;
    int breadth;

public:
    Rectangle(int l, int b)
    {
        length = l;
        breadth = b;
    }

    int area() { return length * breadth; }
};

int main()
{
    //---\/ Smart Pointer
    shared_ptr<Rectangle> P1(new Rectangle(10, 5));
    // This'll print 50
    cout << P1->area() << endl;

    shared_ptr<Rectangle> P2;
    P2 = P1;

    // This'll print 50
    cout << P2->area() << endl;

    // This'll now not give an error,
    cout << P1->area() << endl;

    // This'll also print 50 now
    // This'll print 2 as Reference Counter is 2
    cout << P1.use_count() << endl;
    return 0;
}

Output
50
50
50
2

weak_ptr 

Weak_ptr is a smart pointer that holds a non-owning reference to an object. It’s much more similar to shared_ptr except it’ll not maintain a Reference Counter. In this case, a pointer will not have a stronghold on the object. The reason is to avoid the circular dependency created by two or more object pointing to each other using shared_ptr.

Weak pointer in C++

C++
// C++ program to demonstrate the working of weak_ptr
// Here both smart pointer P1 and P2 are pointing to the
// object Addition to which they both does not maintain
// a reference of the object
#include <iostream>
using namespace std;
// Dynamic Memory management library
#include <memory>

class Rectangle {
    int length;
    int breadth;

public:
    Rectangle(int l, int b)
    {
        length = l;
        breadth = b;
    }

    int area() { return length * breadth; }
};

int main()
{
    //---\/ Smart Pointer
    shared_ptr<Rectangle> P1(new Rectangle(10, 5));
  
    // create weak ptr
    weak_ptr<Rectangle> P2 (P1);
  
    // This'll print 50
    cout << P1->area() << endl;

    // This'll print 1 as Reference Counter is 1
    cout << P1.use_count() << endl;
    return 0;
}

Output
50
1

C++ libraries provide implementations of smart pointers in the form of auto_ptr, unique_ptr, shared_ptr, and weak_ptr



Previous Article
Next Article

Similar Reads

Trie Data Structure using smart pointer and OOP in C++
We will implement trie using smart pointers in C++ and OOP. Here, We have already discussed the implementation of trie data using recursionIn our implementation node of a trie look like : C/C++ Code class TrieNode{ public: // Use of shared_ptr for storing Children // Pointers of TrieNode shared_ptr children[ALPHABET_SIZE]; // Tracks whether If this
6 min read
Program to reverse an array using pointers
Prerequisite : Pointers in C/C++ Given an array, write a program to reverse it using pointers . In this program we make use of * operator . The * (asterisk) operator denotes the value of variable . The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer .
4 min read
Features and Use of Pointers in C/C++
Pointers store the address of variables or a memory location. Syntax: datatype *var_name; Example: pointer "ptr" holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through "ptr" int *ptr; Features of Pointers: Pointers save memory space.Execution time with pointers is faster beca
2 min read
Move all zeroes to end of array using Two-Pointers
Given an array of random numbers, Push all the zero’s of the given array to the end of the array. For example, if the given arrays is {1, 0, 2, 6, 0, 4}, it should be changed to {1, 2, 6, 4, 0, 0}. The order of all other elements should be the same.Examples: Input: arr[]={8, 9, 0, 1, 2, 0, 3} Output: arr[]={8, 9, 1, 2, 3, 0, 0} Explanation: Swap {0
6 min read
How many levels of pointers can we have in C/C++
Prerequisite: Pointer in C and C++, Double Pointer (Pointer to Pointer) in CA pointer is used to point to a memory location of a variable. A pointer stores the address of a variable and the value of a variable can be accessed using dereferencing of the pointer. A pointer is generally initialized as: datatype *variable name; This above declaration i
7 min read
Why do we need reference variables if we have pointers
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.References: A Reference can be called as a constant pointer that becomes de referenced implicitly. When we access the reference it means we are accessing the storage.Why do w
4 min read
Unusual behaviour with character pointers
In C++, cout shows different printing behaviour with character pointers/arrays unlike pointers/arrays of other data types. So this article will firstly explain how cout behaves differently with character pointers, and then the reason and the working mechanism behind it will be discussed. Example 1: C/C++ Code // C++ program to illustrate difference
5 min read
C++ Modify Pointers
Prerequisite: Pointer in C++ Pointers are an essential part of the C++ language. It allows us to store the memory address of a variable. One thing to note here is that if we change the value that a pointer is pointing to, then the value of the original variable also changes. Now, let's check the approach we are going to use. Approach: In the below
2 min read
C++ Vector of Pointers
Prerequisites Pointers in C++Vectors in C++ Vector of pointers are vectors that can hold multiple pointers. Each pointer within a vector of pointers points to an address storing a value. We can use the vector of pointers to manage values that are not stored in continuous memory. How to Create Vector of Pointers in C++? Similar to any other vector d
6 min read
Pointers in Containers in C++ STL
Prerequisites: Pointers in C++Container in STL There are different containers in C++ having their own features where if are adding extra functionality of pointer it will contribute in a different way. Although not all of the containers are useful in this context so let's see a few of the containers which can be helpful. There are 5 containers that
5 min read
Passing Pointers to Functions In C++
Prerequisites: Pointers in C++Functions in C++ Passing Pointers to functions means declaring the function parameter as a pointer, at the function calling passing the address of the variable and that address will be stored by a parameter that is declared as a pointer. To change the value of any variable in the function we have to pass the address of
4 min read
What are Wild Pointers? How can we avoid?
Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave unexpectedly. Example of Wild PointersIn the below code, p is a wild pointer. C/C++ Code // C program that demonstrated wild pointers int main() { /* wild pointer */ int* p; /* Some unknown memory locatio
2 min read
Declare a C/C++ function returning pointer to array of integer pointers
Declare "a function with argument of int* which returns pointer to an array of 4 integer pointers". At the first glance it may look complex, we can declare the required function with a series of decomposed statements. 1. We need, a function with argument int *, function(int *) 2. a function with argument int *, returning pointer to (*function(int *
2 min read
Difference between Arrays and Pointers
The array and pointers are derived data types that have lots of differences and similarities. In some cases, we can even use pointers in place of an array, and arrays automatically get converted to pointers when passed to a function. So, it is necessary to know about the differences between arrays and pointers to properly utilize them in our progra
7 min read
Pointers vs References in C++
Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and pointers are very similar as both are used to hav
5 min read
Computing Index Using Pointers Returned By STL Functions in C++
Many inbuilt functions in C++ return the pointers to the position in memory which gives an address of the desired number but has no relation with the actual index in a container of the computed value. For example, to find the maximum element in a code, we use std::max_element(), which returns the address in memory, not the index of the desired elem
3 min read
Difference between Iterators and Pointers in C++ with Examples
In C++ programming, we have both pointers and iterators that are used in managing and manipulating data structures. There are many similarities between iterators and pointers in their ability to reference and dereference memory, but there are certain differences between the two. Understanding the difference is very important in C++ programming. Poi
4 min read
Pointers and References in C++
In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a symbolic representation of addresses. They enable
5 min read
C++ Pointers
Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of pointers.  The address of the variable you're working with is assigned to the pointer variable that p
9 min read
Pointers vs Array in C++
Arrays and pointers are two derived data types in C++ that have a lot in common. In some cases, we can even use pointers in place of arrays. But even though they are so closely related, they are still different entities. In this article, we will study how the arrays and pointers are different from each other in C++. What is an Array?An array is the
3 min read
Program to Reverse a String using Pointers
Given a string, the task is to reverse this String using pointers. Examples: Input: GeeksOutput: skeeGInput: GeeksForGeeksOutput: skeeGroFskeeGApproach: This method involves taking two pointers, one that points at the start of the string and the other at the end of the string. The characters are then reversed one by one with the help of these two p
2 min read
How to Avoid Memory Leaks When Using a Vector of Pointers to Dynamically Allocated Objects in C++?
In C++, managing memory properly is very important to avoid memory leaks, especially when working with dynamically allocated objects. When using a std::vector of pointers to dynamically allocated objects, we need to ensure that all allocated memory is properly deallocated. In this article, we will learn different methods to avoid memory leaks in su
6 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings. Exa
8 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Article Tags :
Practice Tags :