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.
#include <memory> | |
using namespace std; | |
int main(){ | |
unique_ptr<int> a(new int(4)); // correct | |
unique_ptr<int> b = a; //compiler error | |
unique_ptr<int> b = move(a); //correct. 'a' is invalidated. | |
return 0; | |
} |
Shared_ptr objects share the ownership to the heap memory. Memory is freed only when all the owners go out of scope.
#include <memory> | |
#include <iostream> | |
using namespace std; | |
int main(){ | |
shared_ptr<int> a(new int(4)); //correct | |
{ | |
shared_ptr<int> b = a; //correct. | |
std::cout<<*b<<std::endl; //correct. | |
} | |
std::cout<<*a<<std::endl; //correct. 'a' still valid although 'b' went out of scope. | |
return 0; | |
} |
Output:
4 4
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.
#include <memory> | |
using namespace std; | |
int main(){ | |
shared_ptr<int> a(new int(4)); // correct | |
weak_ptr<int> b = a; //correct | |
return 0; | |
} |
Leave a Reply