A Complete Guide to Smart Pointers in C++


what is the Smart Pointers
smart pointers are wrapper classes that was introduced in c++11
but what is the difference between smart pointers and classic pointers , the main difference between smart pointers and raw pointers is memory management and resource ownership .
but what was the main issue with the raw pointers :
the main issue is that “c++ trust the developer” so when ever you allocate memory heap you are responsible for managing this leak of memory will happened , let’t see an example
// Example 1
#include <iostream>
void func(){
int *ptr = new int(5);
std::cout<<*ptr<<"\n";
return ;
}
int main() {
func();
func();
return 0;
}
as we see in this example we declare a block of memory in heap using “new“ operator and then print the pointer value the return without deallocate the memory now ptr is a leaked memory and every time the function is called this will cause a another memory leak
another example
// Example 2
#include <iostream>
void func(){
int *ptr = new int(5);
std::cout<<*ptr<<"\n";
if(*ptr <= 10 ){
throw 0;
}
delete ptr;
}
int main() {
func();
func();
return 0;
}
in the second example we delete the pointer but also this will cause a memory leak but why!!
this is because the value of of ptr is less than 10 so function will throw 0 and will not continue to delete the pointer and become leak in memory so the main point here is that in large projects maintaining and managing all row pointer in app might be hard and there will be some unknown behaves , so to solve this problem c++ introduce Smart Pointers in c++11 under memory header
but what actually it does smart pointers follow the RAII (Resource Acquisition Is Initialization) this is a It's a core C++ paradigm that ensures automatic and exception-safe resource management
but how this is done ? this is done by when the resources you need is acquired in contractor and release them in Destructor
class myObj{
int *ptr;
public:
myObj(){
ptr = new int(5);
}
~myObj(){
delete ptr;
}
};
in the above example you now don’t care about ptr memory as when the object destroyed or goes out of scope the Destructor will deallocate the heap memory used
so this is the main idea of smart pointer it let you not care about deallocate the heap memory you as this memory is released when object goes out of scope .
other important features in smart pointers is ownership , but what is ownership it’s tell which instance will delete this object and free the heap memory we will talk more in details about it with each type of smart pointers .
smart pointers have 4 types
1 - Shared_ptr
2 - unique_ptr
4 - week_ptr
5 - auto_ptr (Deprecated in C++11, Removed in C++17)
we will discuss each one of them in a separate article
Subscribe to my newsletter
Read articles from muhammad hassan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
