A Very Simple Smart Pointer

smart pointer

In modern C++ programming, the Standard Library includes smart pointers, which are used to help ensure that programs are free of memory and resource leaks and are exception-safe.

Whats are Smart Pointers

Smart pointers are defined in the std namespace in the header file. They are crucial to the RAII or Resource Acquisition Is Initialization programming idiom. The main goal of this idiom is to ensure that resource acquisition occurs at the same time that the object is initialized so that all resources for the object are created and made ready in one line of code. In practical terms, the main principle of RAII is to give ownership of any heap-allocated resource—for example, dynamically-allocated memory or system object handles—to a stack-allocated object whose destructor contains the code to delete or free the resource and also any associated cleanup code.

In most cases, when you initialize a raw pointer or resource handle to point to an actual resource, pass the pointer to a smart pointer immediately. In modern C++, raw pointers are only used in small code blocks of limited scope, loops, or helper functions where performance is critical and there is no chance of confusion about ownership.

Understand With Examples

Let’s see the code bellow about a basic implementation of a primitive Smart Pointer in C++ to illustrate how it works.

#include <bits/unique_ptr.h>
#include <iostream>

template <typename T>
class MySmartPointer {

    T *ptr;
public:
    explicit MySmartPointer(T *p=0) {
        this->ptr = p;
    }

    ~MySmartPointer() {
        std::cout << "*destroying object...\n"; delete(ptr); } T &operator *() { return *ptr; } T *operator ->() {
        return ptr;
    }

};

What we do here is just to create a class that accepts any generic object to handle his allocation. When the class will not be more in scope, the object is automatically freed by the destructor.

See the following code that complements the example:

#include <iostream>

#include "Cars.h"
#include "MySmartPointer.h"



int main() {

    {
        MySmartPointer<int> p(new int());
        *p=100;
        std::cout << "attrib:" << *p << "\n";
    }


    {
        MySmartPointer<int> p1(new int());
        MySmartPointer<int> p2(new int());
        MySmartPointer<int> p3(new int());
        MySmartPointer<int> p4(new int());
        *p1=100;
        std::cout << "attrib:" << *p1 << "\n";
    }


    {
        MySmartPointer<int> p(new int());
        *p=100;
        std::cout << "attrib:" << *p << "\n";
    }

    return 0;
}

If you execute this code will see that for each block the class MySmartPointer call the destructor as the object is not more useful.

In a very simple way, this is how the smart pointer available since version 11 of C++ works.