Phantom and Indulgent Shared Pointers -- Raymond Chen

RaymondChen_5in-150x150.jpgIn our exploration of shared_ptr variations, we've previously covered cases where the stored pointer was either empty or pointed to a managed object. Now, we delve into the intriguing cases of phantom shared pointers, where the stored pointer is null but secretly manages an object, and indulgent shared pointers, which point to something but own nothing, offering unique utility for scenarios like static storage duration, with methods like use_count() and get() aiding in their detection.

Phantom and Indulgent Shared Pointers

By Raymond Chen

From the article:

Last time, we looked at various ways to convert among different shared_ptrs. We finished with this diagram:

2023-10-02_14-15-23.png

 

 

 

You are familiar with an empty shared pointer, which manages no object and has no stored pointer. You are also familiar with a full shared pointer, which manages an object and has a non-null stored pointer (to the managed object, or something whose lifetime is controlled by the managed object). But what about those other two guys?

In the upper right corner, you have the case of a shared pointer that manages an object but whose stored pointer is null, which I’ve called a phantom shared pointer. If you convert the shared pointer to a bool, it produces false, because you can’t use it to access anything. The phantom shared pointer looks empty at a casual glance, but it secretly manages an object behind the scenes. That secretly-managed object remains alive for no visible reason. There is no way to access that secretly-managed object, but it’s still there. It’s a phantom which follows you around.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.