Inside STL: The Different Types of Shared Pointer Control Blocks -- Raymond Chen

RaymondChen_5in-150x150.jpgIn the realm of C++ standard library shared pointers, a crucial component for managing object lifetime is the control block, which contains reference count information and instructions for disposal and deletion. Depending on whether you use make_shared, allocate_shared, or manually assign an already-constructed pointer, different types of control blocks come into play, each with its own characteristics and optimizations for efficiently handling object management.

Inside STL: The Different Types of Shared Pointer Control Blocks

By Raymond Chen

From the article:

We saw earlier that C++ standard library shared pointers use a control block to manage the object lifetime.

struct control_block
    virtual void Dispose() = 0;
    virtual void Delete() = 0;
    std::atomic<unsigned long> shareds;
    std::atomic<unsigned long> refs;

The control block has pure virtual methods, so it is up to derived classes to establish how to dispose and delete the control block.

If you ask a shared_ptr to take responsibility for an already-constructed pointer, then you get this:

template<typename T>
struct separate_control_block : control_block
    virtual void Destroy() noexcept override
        delete ptr;
    virtual void Delete() noexcept override
        delete this;
    T* ptr;

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.