Sobes.tech
Junior — Middle

How do different types of smart pointers differ and how to choose the appropriate one depending on the situation?

sobes.tech AI

Answer from AI

In C++, there are different types of smart pointers that help manage object lifetimes and prevent memory leaks:

  • std::unique_ptr — owns the object exclusively. The object is deleted when the unique_ptr is destroyed. Cannot be copied, only moved. Used when there is a single owner of the resource.

  • std::shared_ptr — shares ownership of the object among multiple pointers. The object is deleted when the last shared_ptr is destroyed. Suitable when the resource needs to be shared among multiple owners.

  • std::weak_ptr — a weak reference to an object managed by shared_ptr. Does not affect the object's lifetime, used to prevent cyclic references and to check if the object exists.

The choice of smart pointer depends on the situation:

  • Use unique_ptr if the object should have a single owner.
  • Use shared_ptr if the object should be shared among multiple owners.
  • Use weak_ptr if you need to refer to an object without increasing the reference count (e.g., for caching or back-references).

Example of using unique_ptr:

#include <memory>
#include <iostream>

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

int main() {
    std::unique_ptr<Foo> p1 = std::make_unique<Foo>();
    // std::unique_ptr<Foo> p2 = p1; // Compilation error
    std::unique_ptr<Foo> p2 = std::move(p1); // Transfer ownership
}

Example of shared_ptr and weak_ptr:

#include <memory>
#include <iostream>

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

int main() {
    std::shared_ptr<Foo> sp1 = std::make_shared<Foo>();
    std::shared_ptr<Foo> sp2 = sp1; // shared owner
    std::weak_ptr<Foo> wp = sp1; // weak reference

    if (auto spt = wp.lock()) { // check if the object exists
        std::cout << "Object is available\n";
    }
}