Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Introduction to Shared Pointers | Shared Pointers
C++ Smart Pointers
course content

Course Content

C++ Smart Pointers

C++ Smart Pointers

1. Introduction to Smart Pointers
2. Unique Pointers
3. Shared Pointers
4. Weak Pointers
5. Advanced topics

book
Introduction to Shared Pointers

Just like a unique pointer, a shared pointer is used to allocate and hold the address of a dynamically allocated object. The main differentiating factor between the two pointer types is that a shared pointer is shareable by design. It can safely have more than one owner. In fact, it should only be used when you need an object to have multiple owners.

How do Shared Pointers Work?

Unlike unique pointers, shared pointers maintain a reference count. The reference count of a shared pointer tracks the number of shared pointers that are currently referencing (owning) the same object.

When a shared pointer goes out of scope, or is explicitly reset, the reference count is automatically decremented. As soon as the reference count reaches 0, it means that no shared pointer is referencing the object any more, and the object's memory is automatically deallocated.

h

shared_pointer

copy
1234567891011121314151617181920212223242526272829303132333435363738394041
#include <iostream> template <typename T> class SharedPointer { public: explicit SharedPointer(T* ptr = nullptr) : pointer(ptr), reference_count(new int(1)) {} SharedPointer(const SharedPointer& other) : pointer(other.pointer), reference_count(other.reference_count) { (*reference_count)++; } SharedPointer& operator=(const SharedPointer& other) { if (this != &other) { if (--(*reference_count) == 0) { delete pointer; delete reference_count; } pointer = other.pointer; reference_count = other.reference_count; (*reference_count)++; } return *this; } ~SharedPointer() { if (--(*reference_count) == 0) { delete pointer; delete reference_count; } } T* operator->() const { return pointer; } T& operator*() const { return *pointer; } private: T* pointer; int* reference_count; };

This is a foolproof way to ensure safe shared ownership of dynamic data. As, even when sharing data, the program is less susceptible to memory leaks/corruption, and you don't need to manually call delete.

question mark

When is the reference count of a shared pointer incremented?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 1
We're sorry to hear that something went wrong. What happened?
some-alt