Sobes.tech
Junior — Middle

How is memory management handled when creating an object using std::shared_ptr?

sobes.tech AI

Answer from AI

When creating an object using std::shared_ptr, memory management is handled through reference counting. When a shared_ptr is created, it holds a pointer to the object and a separate control block where the reference count is stored. Each time the shared_ptr is copied, the counter increases, and when it is destroyed — it decreases. When the counter reaches zero, the object and the control block are automatically deleted, freeing memory.

Example:

#include <memory>
#include <iostream>

struct Foo {
    Foo() { std::cout << "Foo created\n"; }
    ~Foo() { std::cout << "Foo destroyed\n"; }
};

int main() {
    std::shared_ptr<Foo> sp1 = std::make_shared<Foo>(); // object created, counter = 1
    {
        std::shared_ptr<Foo> sp2 = sp1; // counter increases to 2
    } // sp2 is destroyed, counter decreases to 1
    // when main exits, sp1 is destroyed, counter becomes 0, object is deleted
}

Thus, std::shared_ptr provides automatic and safe management of an object's lifetime through reference counting.