RAII and smart pointers: who frees the memory
Every new needs exactly one delete, on every path out of the function, exceptions included. RAII hands that job to the compiler by tying the delete to an object going out of scope.
01 The leak you cannot see
Raw new hands you memory and a promise: call delete exactly once, on every path out of the function. Early returns and exceptions are paths too.
The delete[] at the bottom only runs if control reaches it. Each extra return and every function that might throw is another place to remember. Files, locks and sockets have the same problem: something must be released, and the release is easy to skip.
02 Tie the resource to an object’s lifetime
C++ guarantees one thing you can lean on: when a local object goes out of scope, its destructor runs. That holds for a normal }, a return, a break, and an exception passing through on its way to a catch. RAII (Resource Acquisition Is Initialisation) puts that guarantee to work. The constructor acquires the resource and the destructor releases it.
- just happened
- alive or done
work() is called. No object exists yet and nothing is printed.
03 Exceptions take the same exit
When an exception leaves a function, C++ unwinds the stack: it destroys each local object on the way out, in reverse order, before the catch runs. So the RAII object cleans up even on the path you forgot about.
Whether the stack is unwound when no catch matches is up to the implementation; the program then ends with std::terminate. In practice you always have a handler somewhere, so this rarely matters.
04 unique_ptr: exactly one owner
std::unique_ptr<T> is RAII for one heap object. It holds the pointer, and its destructor calls delete. It cannot be copied, because two owners would both delete. It can be moved: ownership passes to the new variable and the old one becomes empty.
Node* n = new Node(1);use(n); // throws?delete n; // skipped
auto n = std::make_unique<Node>(1);use(*n); // throws? still freed// no delete anywhere
With the default deleter, a unique_ptr is typically the same size as a raw pointer and costs nothing extra at run time. That is why it should be your default for owning heap objects.
06 Which one to reach for
| Type | Acquires | Destructor releases |
|---|---|---|
| std::unique_ptr<T> | a heap object | delete |
| std::vector<T> | a heap array | the elements and the array |
| std::ifstream | an open file | closes it |
| std::lock_guard<std::mutex> | a locked mutex | unlocks it |
07 When it bites
ana->friend_ = bo;
bo->friend_ = ana;A cycle of shared_ptrEach object holds the other, so neither count reaches zero and neither destructor ever runs. Make one side a std::weak_ptr, which watches without owning.Node* raw = new Node;
std::shared_ptr<Node> a(raw);
std::shared_ptr<Node> b(raw);Two owners from one raw pointera and b each get their own control block with count 1. Both will delete raw: a double free. Make the second one a copy of the first, or use make_shared.auto b = std::move(a);
a->value;Using a unique_ptr after moving itAfter the move a is empty (null). Dereferencing it is undefined behaviour.delete p.get();Deleting what a smart pointer ownsget() lends you the raw pointer to use, not to free. The smart pointer will delete it again later.A shared_ptr cycle is a leak that no tool flags at compile time. Parent-to-child links can be shared_ptr; child-to-parent links should be weak_ptr or a plain pointer.