What is smart pointer and implementation of Smart pointer in C++. This simple smart pointer implementation in C++ is asked in technical interview to know if we know the concept of smart pointer and able to implement it.
Smart pointers are a pointers that get de-allocated by itself, when it goes out of scope and we don’t need to to delete it manually. Generally , in C++ programming we use new and delete to allocate and deallocate memory dynamically / at run time.
When we use “new” to allocate memory, the programmer is responsible to free the memory using delete keyword. Where as this is not the case of smart pointers. In fact, smart pointers are objects which store pointers to dynamically allocated objects.
Lets see a simple example to create a smart pointer class.
Consider a class called “Car” having a method Run () as shown below. We will create a smart pointer for this class named CarSP. This smart pointer in C++ program will handle automatic deallocation of memory i.e. for Car object allocated dynamically.
Car Class :
//Car class for which we have to implement
// a Smart pointer.
Implementation of Smart pointer in C++
In CarSP smart pointer class, we’ll have a field Car *sp, that hold the pointer of Car object. In the destructor of CarSP, we will write code to delete object of Car class.
To call the function of car class we have to overload arrow operator -> operator, that returns pointer of object Car. Note that After overloading -> only we would be able to use -> on class CarSP that act as a pointer.
Smart pointer class and testing code
//Smart pointer for class Car
Car * sp;
//Initialize Car pointer when Car
//object is createdy dynamically
CarSP(Car * cptr):sp(cptr)
// Smart pointer destructor that will de-allocate
//The memory allocated by Car class.
printf("Deleting dynamically allocated car object\n");
//Overload -> operator that will be used to
//call functions of class car
Car* operator-> ()
//Create car object and initialize to smart pointer
CarSP ptr(new Car());
//Memory allocated for car will be deleted
//Once it goes out of scope.
Deleting dynamically allocated car object