Course Content
C++ Smart Pointers
C++ Smart Pointers
Creating and Sharing Shared Pointers
Just like unique pointers, we can create shared pointers in two ways: using std::make_shared
or the new
operator. The latter is discouraged, but for the sake of understanding, we will cover both approaches.
The recommended approach
The recommended way to create a shared pointer is through the std::make_shared
function. This approach is generally more efficient and expressive compared to using new
. It allocates memory for the object and the control block (reference count) in a single step. For example:
The above line allocates a dynamic integer and also initializes a shared pointer to it with a reference count of 1.
The discouraged approach
You can also create shared pointers using new
, but this method is discouraged because it is neither expressive nor efficient. The syntax for this approach requires you to pass the object to the shared pointer constructor.
In the above code, we are allocating a dynamic integer and then passing it to the constructor of the shared pointer. However, the control block (reference count) will get initialized inside the constructor.
This means that we are doing two separate initializations, which is inefficient and error-prone.
Passing around shared pointers
Shared pointers are purpose-built for safe sharing. Let’s explore a few ways we can pass them around.
By direct assignment
You can share a shared pointer by directly assigning it to another shared pointer. This increases the reference count.
In the above code, we allocate a dynamic integer which is owned by ptr1
. In the next line, we create another shared pointer ptr2
which also starts to reference the same dynamic integer.
Returning from a function
When you return a shared pointer from a function in the following way, the caller is given its ownership.
In the above function, we are allocating a dynamic integer inside a function, and then transferring its ownership to the caller.
Sharing custom objects
It’s also possible to share custom objects using shared pointers. Consider this example:
main
#include <memory> #include <iostream> class MyClass { public: MyClass(int value) : data(value) {} //constructor int getData() { return data; } private: int data; }; int main() { // Creating a shared pointer to a custom object using make_shared std::shared_ptr<MyClass> obj1 = std::make_shared<MyClass>(42); // Creating another shared pointer that shares ownership with obj1 std::shared_ptr<MyClass> obj2 = obj1; // Both obj1 and obj2 now own the same custom object std::cout << "Data from obj1: " << obj1->getData() << std::endl; //prints 42 std::cout << "Data from obj2: " << obj2->getData() << std::endl; //also prints 42 }
Thanks for your feedback!