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

Contenido del Curso

C++ Smart Pointers

C++ Smart Pointers

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

bookWhat Are Shared Pointers?

Shared pointers, defined as std::shared_ptr, are another type of smart pointer that helps in automatic memory management. They have been a part of the C++ Standard Library since C++11, and are a fundamental concept that every C++ developer should master.

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.

Remember

Creating a new shared pointer for a dynamic object sets the reference count to 1. Adding another shared pointer increases the count to 2, and so forth.

Similarly, 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. This is a foolproof way to ensure safe shared ownership of dynamic data in C++. As, even when sharing data, the program is less susceptible to memory leaks/corruption, and you don’t need to manually call delete.

A real world example

Let’s look at a practical use case of shared pointers. Suppose you are building a complex multimedia application that processes large images. You have written tens of C++ classes to efficiently handle parsing and processing of the image files. Each class needs access to the same image data.

The safest way to go about this would be to use shared pointers. They will ensure that the memory is automatically released when none of the classes need the image data anymor

When is the reference count of a shared pointer incremented?

When is the reference count of a shared pointer incremented?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 1
some-alt