std::shared_ptr Deep Dive (Shared Reference Counting)

🔴 Advanced

📖 Definition & Control Block Architecture

std::shared_ptr<T> manages shared ownership of a heap resource using a dynamically allocated Control Block. The control block contains an atomic reference counter (strong count) and weak reference counter (weak count). Copying a shared_ptr increments the reference count. When the strong reference count drops to 0, the heap object is deleted.

🛠️ Key Mechanics & Factory Helper

  • std::make_shared<T>(args...): Allocates the control block and target object in a single contiguous memory block, improving cache locality and reducing heap allocations.
  • sPtr.use_count(): Returns current strong reference count.
  • sPtr.unique(): Returns true if use_count() == 1.

💡 Complete Code Example

#include <iostream>
#include <memory>

class Texture {
public:
    Texture() { std::cout << "Texture Loaded into VRAM\n"; }
    ~Texture() { std::cout << "Texture Unloaded from VRAM\n"; }
};

int main() {
    std::shared_ptr<Texture> tex1 = std::make_shared<Texture>();
    std::cout << "Ref Count: " << tex1.use_count() << "\n"; // 1

    {
        std::shared_ptr<Texture> tex2 = tex1; // Copy increments ref count
        std::cout << "Inner Scope Ref Count: " << tex1.use_count() << "\n"; // 2
    } // tex2 destroyed -> Ref count decremented back to 1

    std::cout << "Outer Scope Ref Count: " << tex1.use_count() << "\n"; // 1
    return 0; // tex1 destroyed -> Ref count reaches 0 -> VRAM freed
}

👀 Expected Output

Texture Loaded into VRAM
Ref Count: 1
Inner Scope Ref Count: 2
Outer Scope Ref Count: 1
Texture Unloaded from VRAM