In C++, a shared pointer is one of the smart pointers. The shared pointer maintains a reference count which is incremented when another shared pointer points to the same object. So, when the reference count is equal to zero (i.e., no pointer points to this object), the object is destroyed.
You need to include this library:
#include <memory>
In the code below, two pointers (i.e., ptr1
and ptr2
) point to the same string object. Their reference counts are obtained using the use_count()
operation:
#include <iostream>#include <memory>using namespace std;int main(){// creating shared pointershared_ptr<string> ptr1 = make_shared<string>();*ptr1 = "Educative";// Only one pointer points to string objectcout << "ptr1 count = " << ptr1.use_count() << endl;// Now second pointer points to the same int objectshared_ptr<string> ptr2(ptr1);cout << "ptr2 is pointing to the same object as ptr1. Now counts are:" << endl;// Shows the count after two pointer points to the same object.cout << "ptr2 count = " << ptr2.use_count() << endl;cout << "ptr1 count = " << ptr1.use_count() << endl;}
Similarly, we can reset the pointer by using the reset()
function:
#include <iostream>#include <memory>using namespace std;int main(){// creating shared pointershared_ptr<string> ptr1 = make_shared<string>();;*ptr1 = "Educative";// Only one pointer points to string objectcout << "ptr1 count = " << ptr1.use_count() << endl;// Reseting the shared pointerptr1.reset();// Count after resetting the pointercout << "ptr1 count = " << ptr1.use_count() << endl;}
The two codes above are explained below:
Free Resources