Sobes.tech
Junior — Middle

Can you explain how the std::shared_ptr smart pointer works in C++?

sobes.tech AI

Answer from AI

std::shared_ptr is a smart pointer in C++ that implements reference counting for objects in dynamic memory. It allows multiple pointers to jointly own an object, automatically freeing memory when the last shared_ptr stops referencing the object.

Main points of std::shared_ptr operation:

  • When creating a shared_ptr, an object is allocated and a reference count of 1 is created.
  • When copying a shared_ptr, the reference count increases.
  • When destroying or assigning a shared_ptr, the reference count decreases.
  • When the reference count 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
    std::cout << *p1 << std::endl; // 42
} // p1 is destroyed, reference count = 0, memory is freed

Thus, shared_ptr helps prevent memory leaks and simplifies object lifetime management.