01 / 21

Smart Pointers
in C++

Learn how unique_ptr and shared_ptr manage heap memory automatically, preventing leaks and making your code safer and more expressive.

C++

The Memory Problem

In C++, when you allocate memory on the heap with new, you are responsible for releasing it with delete. If you forget, your program leaks memory: the allocated block is never returned to the operating system.

int* p = new int(42); // ... lots of code ... // Oops! We forgot: delete p; // Memory leaked!

What Are Smart Pointers?

A smart pointer is a C++ object that wraps a raw pointer and automatically deletes the heap memory when the smart pointer goes out of scope. They live in the <memory> header.

unique_ptr
Exclusive ownership: exactly one owner at a time. Cannot be copied, only moved.
shared_ptr
Shared ownership: multiple owners via reference counting. Deleted when the last owner is gone.

Automatic Cleanup in Action

Scope begins ptr created (new) Use *ptr Scope ends delete called automatically!

The unique_ptr Rule

A unique_ptr enforces exclusive ownership. Only one unique_ptr may own a given heap object at any time. When that unique_ptr is destroyed, the object is deleted.

unique_ptr sole owner Heap Object int(42) ✕ Cannot copy Use std::move()
auto p = std::make_unique<int>(42); // auto p2 = p; // ERROR: copy deleted auto p2 = std::move(p); // OK: ownership transferred

The shared_ptr Rule

A shared_ptr uses reference counting. Multiple shared_ptrs can point to the same object. The object is deleted only when the last shared_ptr is destroyed.

shared_ptr A owner 1 shared_ptr B owner 2 shared_ptr C Heap Object Widget rc: 2 deleted when rc hits 0

unique_ptr vs shared_ptr

Feature unique_ptr shared_ptr
Ownership Exclusive (one owner) Shared (many owners)
Copyable? No Yes
Movable? Yes Yes
Overhead Zero extra cost Reference count + control block
Creation std::make_unique std::make_shared
When to use Default choice for ownership When multiple places need the object

Step-by-Step Usage Guide

1
Include the header: Add #include <memory> at the top of your file.
2
Choose the type: Use unique_ptr for sole ownership, shared_ptr when multiple parts of your code need the same object.
3
Create with make functions: Use std::make_unique<T>(args) or std::make_shared<T>(args) instead of raw new.
4
Access the object: Use *ptr to dereference and ptr-> to access members, just like a raw pointer.
5
Never call delete: The smart pointer's destructor handles cleanup automatically when it goes out of scope.

Example 1: unique_ptr Basics

#include <memory> #include <iostream> int main() { // Create a unique_ptr to an int auto ptr = std::make_unique<int>(100); std::cout << *ptr << std::endl; // prints 100 // Transfer ownership auto ptr2 = std::move(ptr); // ptr is now nullptr if (!ptr) std::cout << "ptr is empty\n"; // ptr2 is automatically deleted here return 0; }

Example 2: shared_ptr Counting

#include <memory> #include <iostream> int main() { auto a = std::make_shared<std::string>("hello"); std::cout << a.use_count() << "\n"; // 1 { auto b = a; // copy: ref count +1 std::cout << a.use_count() << "\n"; // 2 } // b destroyed: ref count -1 std::cout << a.use_count() << "\n"; // 1 // string deleted when 'a' goes out of scope return 0; }

Example 3: Smart Pointers with Classes

struct Player { std::string name; int score; Player(std::string n, int s) : name(n), score(s) {} }; int main() { // unique_ptr to a Player auto p1 = std::make_unique<Player>("Alice", 50); std::cout << p1->name << ": " << p1->score << "\n"; // Alice: 50 // shared_ptr for a shared leaderboard entry auto top = std::make_shared<Player>("Bob", 99); auto display = top; // both point to Bob display->score = 100; std::cout << top->score << "\n"; // 100 }

Why Use make_unique and make_shared?

✓ Exception Safety
If code throws between new and the smart pointer constructor, you leak. The make functions prevent this.
✓ Cleaner Syntax
No need to write the type twice: make_unique<int>(5) vs unique_ptr<int>(new int(5)).
✓ Performance
make_shared allocates the object and control block in a single allocation, reducing overhead.
// Prefer this: auto p = std::make_unique<Widget>(10, "test"); // Over this: std::unique_ptr<Widget> p(new Widget(10, "test"));

Passing Smart Pointers to Functions

1
By value (unique_ptr): Transfers ownership into the function. The caller must use std::move().
2
By value (shared_ptr): Increases the reference count. The function becomes a co-owner.
3
By reference or raw pointer: If the function just uses the object without owning it, pass const T& or T* instead.

Ownership Flow Visualized

Need heap allocation? Use stack variable No Yes Shared ownership? No unique_ptr default choice Yes shared_ptr multiple owners Always prefer make_unique / make_shared

Common Mistakes

✕ Using new directly
Writing unique_ptr<int>(new int(5)) instead of make_unique<int>(5). Risks memory leaks if an exception is thrown.
✕ Copying a unique_ptr
Trying auto b = a; with a unique_ptr. This is a compile error. Use std::move() to transfer ownership.
✕ Dangling after move
Using a unique_ptr after moving it. The pointer is now nullptr: dereferencing it is undefined behavior.

Quick Reference Summary

Operation unique_ptr shared_ptr
Create make_unique<T>(args) make_shared<T>(args)
Dereference *ptr, ptr-> *ptr, ptr->
Transfer std::move(ptr) Copy or move
Check null if (ptr) if (ptr)
Get raw ptr.get() ptr.get()
Count owners N/A (always 1) ptr.use_count()
Reset ptr.reset() ptr.reset()

Question 1 of 5

What is the primary advantage of using smart pointers over raw pointers in C++?

Question 2 of 5

Which line of code will cause a compile error?

Question 3 of 5

A shared_ptr is copied 3 times. What is the reference count after all copies are made?

Question 4 of 5

After calling std::move(ptr) on a unique_ptr, what is the value of ptr?

Question 5 of 5

Which function should you prefer for creating a unique_ptr?