Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pointer
c++

Shared pointers in C++

Educative Answers Team

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.

Library

You need to include this library:

#include <memory> 

Code

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 pointer
    shared_ptr<string> ptr1 = make_shared<string>();
    *ptr1 = "Educative";
    // Only one pointer points to string object
    cout << "ptr1 count = " << ptr1.use_count() << endl;
    // Now second pointer points to the same int object
    shared_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 pointer
    shared_ptr<string> ptr1 = make_shared<string>();;
    *ptr1 = "Educative";
    // Only one pointer points to string object
    cout << "ptr1 count = " << ptr1.use_count() << endl;
    // Reseting the shared pointer
    ptr1.reset();
    // Count after resetting the pointer
    cout << "ptr1 count = " << ptr1.use_count() << endl;
}

Illustration

The two codes above are explained below:

1 of 4

RELATED TAGS

pointer
c++
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring