Sobes.tech
Junior — Middle

What is the purpose of using std::shared_ptr in C++ and how does it differ from other smart pointers?

sobes.tech AI

Answer from AI

std::shared_ptr in C++ is used for shared ownership of a dynamically allocated object. It maintains a reference count — the number of shared_ptrs pointing to the same object. When the last shared_ptr is destroyed or reassigned, the object is automatically deleted.

Differences from other smart pointers:

  • std::unique_ptr owns the object exclusively, does not support copying, only moving.
  • std::weak_ptr is a weak reference to an object managed by shared_ptr, does not increase the reference count, and does not own the object. It is used to prevent cyclic references.

Example usage:

#include <memory>
#include <iostream>

int main() {
    std::shared_ptr<int> p1 = std::make_shared<int>(42);
    {
        std::shared_ptr<int> p2 = p1; // reference count increases
        std::cout << *p2 << std::endl; // 42
    } // p2 is destroyed, reference count decreases
    std::cout << *p1 << std::endl; // 42
} // p1 is destroyed, object is deleted

Thus, shared_ptr is convenient for shared ownership of resources with automatic management of the object's lifetime.