What it means when you convert between different shared_ptrs -- Raymond Chen

RaymondChen_5in-150x150.jpgIn 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 static_pointer_cast, const_pointer_cast, reinterpret_pointer_cast, and dynamic_pointer_cast, shedding light on some nuances in the process.

What it means when you convert between different shared_ptrs

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_ptr is 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_ptrs from a raw pointer or when you call make_shared. But what is the use case for a shared_ptr where the managed object and the stored pointer are different?

 

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.