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
- Stack allocation (default) - fastest, automatic cleanup
unique_ptr- single owner on the heapshared_ptr- shared ownership (use sparingly)- Raw
new/delete- almost never needed
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.
Factory Functions
Return unique_ptr from factory functions:
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:
auto shape = create_shape("circle"); // unique ownershipstd::shared_ptr<Shape> shared = create_shape("rect"); // upgrade to sharedHand 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:
class Engine {public: void rev() { std::cout << "Vroom!" << std::endl; }};
class Car { std::unique_ptr<Engine> engine; // Car owns the enginepublic: 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.
int *bad() { int x = 42; return &x; // x is destroyed when function returns!}Use-after-move: accessing an object after moving from it.
auto v = std::make_unique<std::vector<int>>();auto v2 = std::move(v);// v->size(); // BUG: v is now nullptrCircular references: shared_ptr cycles that never free.
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_uniquefor anything that has to live on the heapconst &for read-only parameters- Pass by value and
std::movewhen a function takes ownership - Return by value, the compiler will move it for you
- Raw
new/deletehas no place in application code
Challenges
Use unique_ptr to manage a dynamically allocated integer.