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

Smart Pointers in C++

Last Updated : 11 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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
    // 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 scope It 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 if suppose pointers are holding the object and requesting for other objects then they may form a Deadlock. 

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

Difference between constant pointer, pointers to constant, and constant pointers to constants
In this article, we will discuss the differences between constant pointer, pointers to constant &amp; constant pointers to constants. Pointers are the variables that hold the address of some other variables, constants, or functions. There are several ways to qualify pointers using const. Pointers to constant.Constant pointers.Constant pointers to c
3 min read
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
How to Create a Smart Pointer in C++?
A smart pointer in C++ simulates a pointer while also providing automatic garbage collection as it deallocates or frees associated memory when it goes out of scope, which helps prevent memory leaks and dangling pointers. In this article, we will learn how to create a smart pointer in C++. Creating a Smart Pointer in C++ The C++ libraries provide th
4 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
C++ Program to compare two string using pointers
Given two strings, compare the strings using pointers Examples: Input: str1 = geeks, str2 = geeks Output: Both are equal Input: str1 = hello, str2 = hellu Output: Both are not equal As their length are same but characters are different The idea is to dereference given pointers, compare values and advance both of them. C/C++ Code // C++ Program to c
1 min read
Program to Reverse a String using Pointers
Given a string, the task is to reverse this String using pointers. Examples: Input: Geeks Output: skeeG Input: GeeksForGeeks Output: skeeGroFskeeG Approach: 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 t
2 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
Article Tags :
Practice Tags :
three90RightbarBannerImg