C++ Smart Pointers

C++ smart pointers are objects that own dynamically allocated memory and free it automatically. They replace manual new and delete, which are a common source of leaks and crashes.

The Problem with new and delete

With raw new you must call delete exactly once on every path, including when exceptions are thrown. It is easy to forget, so modern C++ almost never calls delete directly.

std::unique_ptr

unique_ptr is the sole owner of an object. When it goes out of scope, the object is deleted. It cannot be copied, only moved.

#include <iostream>
#include <memory>
#include <string>

struct Player {
    std::string name;
    explicit Player(std::string n) : name(std::move(n)) { std::cout << name << " created\n"; }
    ~Player() { std::cout << name << " destroyed\n"; }
};

int main() {
    auto p = std::make_unique<Player>("Hero");
    std::cout << "Playing as " << p->name << '\n';
    auto q = std::move(p);   // ownership transferred
    std::cout << std::boolalpha << (p == nullptr) << '\n';
}
Hero created
Playing as Hero
true
Hero destroyed

std::shared_ptr

shared_ptr allows several owners. It keeps a reference count and deletes the object when the last owner disappears.

#include <iostream>
#include <memory>

int main() {
    auto a = std::make_shared<int>(10);
    {
        auto b = a;
        std::cout << "owners: " << a.use_count() << '\n';
    }
    std::cout << "owners: " << a.use_count() << '\n';
}
owners: 2
owners: 1

Which Smart Pointer to Use

  • Default to std::unique_ptr; it has zero overhead compared with a raw pointer.
  • Use std::shared_ptr only when ownership is truly shared.
  • Use std::weak_ptr to observe a shared object without owning it and to break reference cycles.
  • Create them with std::make_unique and std::make_shared.
  • Pass a plain reference or raw pointer to functions that only use the object.

Frequently asked questions

What is the difference between unique_ptr and shared_ptr?

unique_ptr has exactly one owner and cannot be copied. shared_ptr can be copied, and the object is deleted when the last copy is destroyed, at the cost of a reference count.

Should I ever use new and delete in modern C++?

Rarely. Use containers and smart pointers created with make_unique or make_shared. Raw new/delete is mainly for low-level library code.

What is weak_ptr used for?

weak_ptr refers to an object owned by shared_ptr without increasing the count. It prevents memory leaks from cyclic references and lets you check whether the object still exists.