Skip to main content
Be Bitwise
C++Smart Pointers & Memory

Memory Management Patterns

Modern C++ comes with a clear playbook for memory. Stick to it and the entire category of "I forgot to free that" bugs basically vanishes.

The Ownership Hierarchy

  1. Stack allocation (default) - fastest, automatic cleanup
  2. unique_ptr - single owner on the heap
  3. shared_ptr - shared ownership (use sparingly)
  4. Raw new/delete - almost never needed
cpp
void example() {
int x = 42; // stack
auto up = std::make_unique<Widget>(); // unique ownership
auto sp = std::make_shared<Widget>(); // shared ownership
// auto raw = new Widget(); // avoid!
}

Here's some legacy code that breaks every rule in that list: a raw new with a forgotten delete, a vector of owning raw pointers, and a shared_ptr cycle. Widget counts its live instances, so the last line tells you how many leaked.

Try itRefactor until the last line reports 0 live widgets: a local or unique_ptr for the first, vector<unique_ptr<Widget>> for the second, weak_ptr for the cycle.
C++ (GCC 9.2.0)

Factory Functions

Return unique_ptr from factory functions:

cpp
std::unique_ptr<Shape> create_shape(const std::string &type) {
if (type == "circle") return std::make_unique<Circle>(5.0);
if (type == "rect") return std::make_unique<Rectangle>(3.0, 4.0);
return nullptr;
}

The caller decides how to manage the returned object:

cpp
auto shape = create_shape("circle"); // unique ownership
std::shared_ptr<Shape> shared = create_shape("rect"); // upgrade to shared
Key Concept

Hand back unique_ptr from your functions, never shared_ptr. The caller can promote a unique_ptr to a shared_ptr whenever they want; the reverse is impossible. Returning the cheaper one keeps every door open.

The Observer Pattern

Non-owning access uses raw pointers or references:

cpp
class Engine {
public:
void rev() { std::cout << "Vroom!" << std::endl; }
};
class Car {
std::unique_ptr<Engine> engine; // Car owns the engine
public:
Car() : engine(std::make_unique<Engine>()) {}
Engine *get_engine() { return engine.get(); } // non-owning access
};

Whoever calls get_engine() is borrowing, not owning. They mustn't delete it, and they mustn't outlive the Car still holding it.

Avoiding Common Bugs

Dangling pointers: a raw pointer to a deleted object.

cpp
int *bad() {
int x = 42;
return &x; // x is destroyed when function returns!
}

Use-after-move: accessing an object after moving from it.

cpp
auto v = std::make_unique<std::vector<int>>();
auto v2 = std::move(v);
// v->size(); // BUG: v is now nullptr

Circular references: shared_ptr cycles that never free.

cpp
struct Node {
std::shared_ptr<Node> next; // Use weak_ptr to break cycles
};

The Short List

When you're unsure which tool fits, walk this from the top:

  • Default to the stack
  • make_unique for anything that has to live on the heap
  • const & for read-only parameters
  • Pass by value and std::move when a function takes ownership
  • Return by value, the compiler will move it for you
  • Raw new/delete has no place in application code

Challenges

Use unique_ptr to manage a dynamically allocated integer.

C++ (GCC 9.2.0)