Sobes.tech
Middle

What components does shared_ptr consist of?

sobes.tech AI

Answer from AI

shared_ptr consists of two main components:

  1. Pointer to the managed resource: Raw pointer to the object that shared_ptr manages.

  2. Pointer to the control block: An object containing meta-information about the managed resource. This block is dynamically allocated when the first shared_ptr or weak_ptr pointing to the resource is created.

The control block typically contains:

  • Strong reference count: The number of shared_ptr instances pointing to the resource. When this count reaches zero, the resource is deleted.
  • Weak reference count: The number of weak_ptr instances pointing to the resource. The resource is only deleted when the strong reference count is zero, regardless of this count's value. However, the control block is only deleted when both counts reach zero.
  • Deleter information: An optional user-defined functor or function for deleting the resource. If not specified, delete is used.
  • Allocator information: An optional allocator for allocating resources and the control block.

Example of creating a shared_ptr and its components at a conceptual level:

// Assume there is a class MyClass
class MyClass {
public:
    MyClass() { std::cout << "MyClass created\n"; }
    ~MyClass() { std::cout << "MyClass destroyed\n"; }
};

// Creating a shared_ptr:
// Allocating a MyClass object
// Allocating a control block
// Setting the pointer to MyClass in shared_ptr
// Setting the pointer to the control block in shared_ptr
// Initializing counters (strong = 1, weak = 0) in the control block
std::shared_ptr<MyClass> ptr1 = std::make_shared<MyClass>();

// When creating a copy of shared_ptr:
// ptr2 points to the same MyClass object
// ptr2 points to the same control block
// Incrementing the strong reference count in the control block (now 2)
std::shared_ptr<MyClass> ptr2 = ptr1;

// When one shared_ptr is destroyed (e.g., ptr1 goes out of scope):
// Decrementing the strong reference count in the control block (now 1)
// The resource is NOT deleted, as the strong count > 0

// When the last shared_ptr is destroyed (ptr2 goes out of scope):
// Decrementing the strong reference count in the control block (now 0)
// The MyClass object is deleted
// Decrementing the weak reference count in the control block (here 0)
// Both counts are 0, the control block is deleted

Visual representation:

  • shared_ptr |-> [ Its data (Pointer to resource, Pointer to control block) ]
    • [ Pointer to resource ] -> [ Object of type T ]
    • [ Pointer to control block ] -> [ Control block object (Counters, Deleter, Allocator) ]