The shared_ptr is one type of smart pointers of C that contains the shared ownership of the object created by the pointer. It shares the ownership of the object when storing the pointer into another object, and the shared reference counter counts the number of owners. The shared_ptr increases the reference counter by one after copying the object and decreases the reference counter by one after destroying the object. The memory owned by the object is reallocated if the object owned by the last shared_ptr is destroyed, or the reset() function is called to assign another pointer for the object. When the shared_ptr does not own any object, then it is called an empty shared pointer. Different uses of the shared_ptr have been shown in this tutorial.

Example 1: Declare Shared Pointer in Different Ways

Three different ways to declare a shared pointer are shown in the following example. A class with a constructor and a public method have been declared in the code. The constructor will print a message when a new shared object is created with the constructor. The Display() method will print messages based on the calling shared pointer object. Here, the first shared pointer object has been created without calling the constructor. The second shared pointer object has been created by calling the constructor. The third shared pointer has created by assigning the first shared pointer. The Display() method has been called three times by using three shared pointer objects.

//Include necessary libraries

#include

#include

usingnamespacestd;

//Define the class


classMyClass {


    public:


    //Declare the constructor


    MyClass() {


        cout<<“The constructor is called.n;


    }


    //Declare a method to print text


    voidDisplay(string str)


    {


        cout<<“The Display() method is called from the “<< str <<” pointer.n;


    }

};

intmain()

{


    //Initialize shared_ptr without calling constructor


    shared_ptr p1 = make_shared();


    p1->Display(“first”);


    //Initialize shared_ptr by calling constructor


    shared_ptr p2 = shared_ptr(newMyClass);


    p2->Display(“second”);

    //Initialize shared_ptr by assignment


    shared_ptr p3 = p1;


    p3->Display(“third”);


    return0;

}

Output:

The following output will appear after executing the above code. The constructor has called at the time of second object creation only. So, the message of the constructor has been printed only one time:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-176.png" data-lazy- height="498" src="data:image/svg xml,” width=”973″>

Example 2: Print the Stored Shared Pointer Location

The get() function shared pointer is used to return the stored, shared pointer location. The following example will print the location of the stored, shared pointers that are created by the class and the function. Here, a class with a constructor has been defined to be used for creating a shared pointer. A function has been declared to create a shared pointer and print the shared pointer location using the get() function. In this code, the first shared pointer has been created using the class, the second shared pointer has been created using the function, and the third shared pointer has been created by assigning the first pointer.

//Include necessary libraries

#include

#include

usingnamespacestd;

//Define the class


classMyClass

{


    public:


    //Declare the constructor


    MyClass() {


        cout<<“The constructor is called.n;


    }

};

//Define function to initialize the pointer


voidInit_shared_ptr()

{


    shared_ptr p2 (newMyClass);


    cout<<p2.get() <<n;

}

intmain()

{


    //Initialize shared_ptr by calling constructor


    shared_ptr p1 = shared_ptr(newMyClass);


    cout<<p1.get() <<n;

    //Initialize shared_ptr by calling function


    Init_shared_ptr();

    //Initialize shared_ptr by assignment


    shared_ptr p3 = p1;


    cout<<p3.get() <<n;


    return0;

}

Output:

The following similar output will appear after executing the above code. In the output, the returned value of the get() function for the first and third shared pointers are the same. However, the second shared pointer is different:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-177.png" data-lazy- height="496" src="data:image/svg xml,” width=”966″>

Example 3: Count the Shared Pointer Objects

The following example depicts a way to count the number of objects pointed by a shared pointer after creating and destroying the pointer. A class with a constructor has been declared in the code. The first shared pointer has been created using the class, and the second shared pointer has been created using the first shared pointer. The number of objects pointed by both shared pointers before and after calling the reset() function has been printed later.

//Include necessary libraries

#include

#include

usingnamespacestd;

//Define the class


classMyClass {


    public:


    //Declare the constructor


    MyClass() {


        cout<<“The constructor is called.n;


    }

};


intmain()

{


    //Initialize the first shared_ptr by calling constructor


    shared_ptr p1(newMyClass);

    //Display the number of shared_ptr objects by the first pointer


    cout<<“p1 pointing to “<< p1.use_count() <<” object(s).n;


    //Initialize the second shared_ptr using the first shared_ptr


    shared_ptr p2(p1);


    //Display the number of shared_ptr objects by the first and second pointers


    cout<<“p2 pointing to “<< p2.use_count() <<” object(s).n;


    cout<<“p1 pointing to “<< p1.use_count() <<” object(s).n;


    //Remove the ownership of the first pointer from the shared_ptr object


    p1.reset();


    //Display the number of shared_ptr objects by the second pointer


    cout<<“p2 pointing to “<< p2.use_count() <<” object(s).n;


    return0;

}

Output:

The following output will appear after executing the above code. The first pointer, p1, is pointing to one object after creation. After creating the second pointer, p2, using the first pointer, p1, both pointers are pointing to two objects for sharing the pointer. After calling the reset() function for the pointer, p1, one object has been destroyed, and the pointer, p2, is now pointing to one object only.

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-178.png" data-lazy- height="531" src="data:image/svg xml,” width=”993″>

Conclusion:

The purposes of using a shared pointer in C have been explained in this tutorial by using simple examples. Creating shared pointers in different ways, getting stored shared pointer location, and counting the number of objects pointed by the shared pointers. I hope the C coders will be able to use the shared pointer in their code after reading this tutorial.

About the author

<img alt="" data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/channel-logo-150×150.jpg610b52789bfd3.jpg" height="112" src="data:image/svg xml,” width=”112″>

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.