In C++, the
shared_ptr is commonly used to manage reference-counted pointers, typically pointing to objects that get deleted when the last reference expires. However, it's possible to create
shared_ptr instances where the managed object and the stored pointer are different, enabling scenarios like accessing sub-objects or creating aliasing shared pointers. This article explores various ways to achieve this, including type conversions and special helper functions like
dynamic_pointer_cast, shedding light on some nuances in the process.
By Raymond Chen
From the article:
The C++ shared_ptr manages a reference-counted pointer. Usually, it’s a pointer to an object that will be
delete‘d when the last reference expires. But it doesn’t have to be that way.
Recall that a
shared_ptris really two pointers.
- A pointer to a control block which manages the shared and weak reference counts, and which destroys an object (commonly known as the managed object) when the shared reference count drops to zero.
- A pointer to return from the get() method, commonly know as the stored pointer.
Most of the time, the stored pointer points to the managed object, because that what you get when you construct a
shared_ptrsfrom a raw pointer or when you call
make_shared. But what is the use case for a
shared_ptrwhere the managed object and the stored pointer are different?