Sobes.tech
Junior

What is the difference between unique_ptr and shared_ptr?

sobes.tech AI

Answer from AI

unique_ptr — exclusive ownership of a resource, shared_ptr — shared ownership with reference counting.

unique_ptr:

  • Cannot be copied, only moved (std::move).
  • Low overhead (similar to raw pointer).
  • Resource is released when unique_ptr is destroyed.
#include <memory>

// Creating a unique_ptr
std::unique_ptr<int> up1(new int(10));

// Attempting to copy (compile error)
// std::unique_ptr<int> up2 = up1;

// Moving ownership
std::unique_ptr<int> up3 = std::move(up1); // now up1 is empty

// Resource will be released when up3 goes out of scope

shared_ptr:

  • Can be copied.
  • Uses reference counting: resource is deleted when the last shared_ptr to it is destroyed.
  • Higher overhead (stores reference count and pointer to resource).
  • Cyclic references are possible (solved with weak_ptr).
#include <memory>

// Creating a shared_ptr
std::shared_ptr<int> sp1(new int(20));

// Copying shared_ptr (increments reference count)
std::shared_ptr<int> sp2 = sp1;

// Getting the number of references
// sp1.use_count() == 2

// Resource will be released when both sp1 and sp2 are destroyed

Comparison:

Attribute unique_ptr shared_ptr
Ownership Exclusive Shared
Copying No (only move) Yes
Overhead Low High
Cyclic links Impossible Possible (weak_ptr)
Usage For objects with a single owner For objects with multiple owners