In C++, memory allocated from heap has to be freed manually. But there could be situations where the programmer forgets to deallocate the memory and causes what is known as memory leakage.
Smart Pointers in C++ are wrapper template classes for pointers that conforms to RAII principle and releases the memory when they go out of scope. This is done by allocating the memory in the constructor and freeing it in the destructor. Operators including ‘*’ and ‘->’ have been overloaded within these classes. Smart Pointers were introduced into the standard in C++ 11 and are available within the ‘memory’ header.
There are three types of Smart Pointers in C++. Unique_ptr, Shared_ptr and Weak_ptr.
A Unique_ptr object maintains exclusive ownership to the heap memory it holds. When the unique_ptr object goes out of scope, the heap memory held by it is released. The only way to give another unique_ptr access to this memory is via the move operation.
Shared_ptr objects share the ownership to the heap memory. Memory is freed only when all the owners go out of scope.
Weak_ptr are used along with shared_ptr. They are used to get a pointer to a memory location without taking the ownership of it. Weak pointers are usually used to remove cyclic dependencies, solve dangling pointer problems etc. The member methods, expired() and lock() are used to work with weak pointers.