Skip to content

Module 9 · Modern C++ — topic 2 of 3

Smart Pointers

unique_ptr, shared_ptr and weak_ptr manage heap objects automatically. Learn ownership models, make_unique/make_shared, transferring ownership and breaking cycles.

Beginner 16 min read·Lesson 39 of 40 in C++ Programming

Learning objectives

  • Use unique_ptr for exclusive ownership
  • Use shared_ptr and weak_ptr correctly
  • Transfer ownership with std::move

Definition

Smart pointers are RAII class templates in <memory> that own dynamically allocated objects: std::unique_ptr has sole ownership, std::shared_ptr shares ownership with reference counting, and std::weak_ptr observes a shared object without owning it.

Introduction

Manual new/delete leaks when an exception or early return skips the delete. Smart pointers delete the object in their destructor, so memory is released on every path — the RAII idea applied to heap objects.

Why it matters

Modern C++ guidelines say: no naked new/delete in application code.

Polymorphic containers, trees and graphs are built with smart pointers.

Detailed explanation

std::unique_ptr<T>: exactly one owner; not copyable, only movable (std::move). Zero overhead compared with a raw pointer. Create with std::make_unique<T>(args).

std::shared_ptr<T>: several owners; a reference count tracks them and the object is deleted when the last one goes away. Create with std::make_shared<T>(args) (one allocation for object and count).

std::weak_ptr<T>: a non-owning reference to a shared object. lock() returns a shared_ptr if the object still exists. Use it to break cycles (parent ↔ child).

Pass smart pointers by value only to transfer or share ownership; otherwise pass T& or T* to functions that merely use the object.

Syntax

C++
auto doc = std::make_unique<Document>("notes");
std::unique_ptr<Document> other = std::move(doc); // doc is now null
auto shared = std::make_shared<Config>();
std::shared_ptr<Config> copy = shared; // count == 2
std::weak_ptr<Config> watcher = shared;
if (auto p = watcher.lock()) { /* still alive */ }
  • Prefer unique_ptr by default.
  • Never create two shared_ptrs from the same raw pointer.
  • .get() returns the raw pointer without releasing ownership.

Code examples

unique_ptr frees automatically

C++
#include <iostream>
#include <memory>
#include <string>
struct Report {
explicit Report(std::string n) : name(std::move(n)) { std::cout << "open " << name << '\n'; }
~Report() { std::cout << "close " << name << '\n'; }
std::string name;
};
int main() {
{
auto r = std::make_unique<Report>("sales");
std::cout << "using " << r->name << '\n';
}
std::cout << "after scope\n";
return 0;
}
Output
open sales
using sales
close sales
after scope

Moving ownership

C++
#include <iostream>
#include <memory>
int main() {
auto a = std::make_unique<int>(42);
std::unique_ptr<int> b = std::move(a);
std::cout << (a ? "a owns" : "a empty") << ", b = " << *b << '\n';
return 0;
}
Output
a empty, b = 42

More examples

shared_ptr counts and weak_ptr breaking a cycle

C++
#include <iostream>
#include <memory>
#include <string>
#include <vector>
struct Employee;
struct Team {
std::string name;
std::vector<std::shared_ptr<Employee>> members;
~Team() { std::cout << "team " << name << " destroyed\n"; }
};
struct Employee {
std::string name;
std::weak_ptr<Team> team; // weak: no ownership cycle
~Employee() { std::cout << name << " destroyed\n"; }
};
int main() {
{
auto t = std::make_shared<Team>();
t->name = "Platform";
auto e = std::make_shared<Employee>();
e->name = "Asha";
e->team = t;
t->members.push_back(e);
std::cout << "employee owners: " << e.use_count() << '\n';
if (auto team = e->team.lock()) std::cout << e->name << " works in " << team->name << '\n';
}
std::cout << "scope ended\n";
return 0;
}
Output
employee owners: 2
Asha works in Platform
team Platform destroyed
Asha destroyed
scope ended

Step-by-step explanation

  • The employee is owned by e and by the team's vector: use_count 2.
  • The employee points back to its team with a weak_ptr, so there is no ownership cycle.
  • lock() temporarily obtains a shared_ptr to read the team.
  • At scope end, e is released first (declared later), then t; the team's destructor drops the last owner of the employee.

Expected output

Running “shared_ptr counts and weak_ptr breaking a cycle” prints exactly:

TextOutput
employee owners: 2
Asha works in Platform
team Platform destroyed
Asha destroyed
scope ended

Practical applications

  • GUI widget trees use unique_ptr children.
  • Caches hand out shared_ptrs to shared resources.
  • Observer patterns use weak_ptr to avoid keeping subjects alive.

Best practices

  • Default to unique_ptr; use shared_ptr only for genuinely shared ownership.
  • Create with make_unique/make_shared.
  • Pass raw references to functions that don't own.

Common mistakes

Two owners of one raw pointer

Avoid

auto* raw = new Widget;
std::shared_ptr<Widget> a(raw), b(raw); // double delete

Prefer

auto a = std::make_shared<Widget>();
auto b = a;

Each shared_ptr created from a raw pointer starts its own count; both delete.

shared_ptr cycles

Avoid

struct Node { std::shared_ptr<Node> next, prev; };

Prefer

struct Node { std::shared_ptr<Node> next; std::weak_ptr<Node> prev; };

Two shared_ptrs pointing at each other keep both objects alive forever — a leak.

Important notes

  • shared_ptr reference counting is thread-safe, but access to the pointed-to object is not.
  • unique_ptr supports arrays (std::unique_ptr<int[]>) and custom deleters (e.g. for FILE*).

Key takeaways

  • unique_ptr: sole owner, movable only.
  • shared_ptr: reference-counted shared ownership.
  • weak_ptr: observe without owning; breaks cycles.

Try it yourself

  1. 1
    Build a binary tree with std::unique_ptr<Node> children and compute its height.
  2. 2
    Use std::unique_ptr<FILE, decltype(&fclose)> to close a C file automatically.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhich smart pointer expresses sole ownership and cannot be copied?
  • BeginnerWhat is printed?
  • ModerateWhat is printed?
Practise this topic