Sobes.tech
Junior — Middle

Can you explain how the smart pointer std::shared_ptr is implemented and how it manages memory?

sobes.tech AI

Answer from AI

std::shared_ptr is a smart pointer in C++ that implements reference counting to manage the lifetime of an object. It holds a pointer to the object and a reference counter that indicates how many shared_ptrs point to this object.

When a shared_ptr is created, the reference count is initialized to one. When a shared_ptr is copied, the counter increases; when it is destroyed, the counter decreases. When the counter reaches zero, the object is automatically deleted.

Example:

#include <memory>
#include <iostream>

int main() {
    std::shared_ptr<int> p1 = std::make_shared<int>(42); // reference count = 1
    {
        std::shared_ptr<int> p2 = p1; // reference count = 2
        std::cout << *p2 << std::endl; // 42
    } // p2 is destroyed, reference count = 1
    // the object is still alive
} // p1 is destroyed, reference count = 0, object is deleted

Thus, shared_ptr provides automatic and safe management of dynamic memory, preventing leaks and double deletions.