Smart pointers in C++
Smart pointer is a class object that acts like a pointer but it has some additional features.
For ex: in below function:
Each time this function is called it allocates memory from heap but never frees memory. We can sort this out by putting one additional statement before return statement :
delete ps;
We have to remember all the time about memory allocation.
Suppose before deleting ps
if some exception is thrown then we would not be able to delete that memory.
When function func
will terminate then all the local variables will be removed from stack. Memory occupied by pointer ps
will be freed but it would be nice if memory pointed by ps
will also be freed. If ps
had a destructor then we can free the memory pointed by ps
so the main problem is ps
is only a pointer not a class object having a destructor.
This is the idea behind the smart pointers😃.
So smart pointers are like pointer objects in which destructor will call delete when pointer will go out of scope.
Why multiple types of smart pointers??
If p1
and p2
were normal pointers then two pointers will be pointing to same string object and program will try to delete same object twice ,once when p1
will go out of scope and another when p2
will go out of scope.
Here p2
takes the ownership of object and p1
losses ownership so it’s now the responsibility of p2
to delete this object.
But what will happen if program will try to use data pointed by p1
??🤷♀️
Consider this ex:
Segmentation fault will occur in both examples..!!!
Here comes unique pointer in picture:
“If a program attempts to assign one unique_ptr to another, the compiler allows it if the source object is a temporary rvalue and disallows it if the source object has some duration.”
If program needs more than one pointer for an object then shared pointer should be used.
shared_ptr
uses reference counting. For every new pointer to the same object count will be increased by one and will be decreased by one if pointer will expire. When final pointer will expire then delete will be invoked.
Note:
1 . C++11 standard made auto_ptr
deprecated.
2. std::move() function can allow assignment of one unique_ptr to other.
Way ahead: move semantics and rvalue reference.
Thanks for reading!!😃