Skip to content

RAII and smart pointers: who frees the memory

Working knowledgeConcept

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.

C++
void save(const std::string& path) {
char* buf = new char[4096];
if (!fill(buf)) return; // leak: delete[] never runs
write(path, buf); // throws? leak again
delete[] buf;
}

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.

scope.cpp
#include <iostream>
#include <string>
struct File {
std::string name;
explicit File(std::string n) : name(std::move(n)) {
std::cout << "open " << name << '\n';
}
~File() { std::cout << "close " << name << '\n'; }
};
void work() {
File a("a.txt");
{
File b("b.txt");
} // b's scope ends here
Leaving a scope runs the destructors
Step 1 of 7
Objects alive in work()
Empty
Printed
Empty
  • just happened
  • alive or done

work() is called. No object exists yet and nothing is printed.

work() { line

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.

throw.cpp
#include <iostream>
#include <stdexcept>
#include <string>
struct File {
std::string name;
explicit File(std::string n) : name(std::move(n)) {
std::cout << "open " << name << '\n';
}
~File() { std::cout << "close " << name << '\n'; }
};
void work() {
File a("a.txt");
throw std::runtime_error("disk full");
}
Text
open a.txt
close a.txt
caught: disk full

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.

Raw new
Node* n = new Node(1);
use(n); // throws?
delete n; // skipped
unique_ptr
auto n = std::make_unique<Node>(1);
use(*n); // throws? still freed
// no delete anywhere
unique.cpp
#include <iostream>
#include <memory>
#include <utility>
struct Node {
int value;
explicit Node(int v) : value(v) {}
~Node() { std::cout << "~Node " << value << '\n'; }
};
int main() {
auto a = std::make_unique<Node>(1);
// auto b = a; // does not compile: one owner only
auto b = std::move(a); // ownership moves to b
std::cout << (a ? "a owns" : "a is empty") << '\n';
std::cout << "b->value = " << b->value << '\n';
Text
a is empty
b->value = 1
~Node 1

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.

05 shared_ptr: the last one out frees it

Sometimes several parts of a program need the same object and none of them clearly outlives the rest. std::shared_ptr<T> keeps a reference count next to the object. Copies add one, destructors subtract one, and the copy that brings it to zero deletes the object.

shared.cpp
#include <iostream>
#include <memory>
struct Node {
~Node() { std::cout << "~Node\n"; }
};
int main() {
auto a = std::make_shared<Node>();
auto b = a;
std::cout << "count " << a.use_count() << '\n';
{
auto c = b;
std::cout << "count " << a.use_count() << '\n';
}
std::cout << "count " << b.use_count() << '\n';
shared_ptr: the last owner frees it
Step 1 of 7
shared_ptr objects in main()
Empty
Heap
no Node
  • just made
  • count changed
  • destroyed or freed
  • not allocated yet

main starts. No shared_ptr exists and the heap has no Node.

0 use_count

The count is updated with atomic operations, so copies on different threads are safe. That makes copying a shared_ptr slower than copying a raw pointer. Pass it by const&, or pass a plain reference to the object, when the callee does not need to keep it.

06 Which one to reach for

std::unique_ptrOne ownerThe default. Moves, never copies. No count to maintain.
std::shared_ptrMany ownersWhen ownership is truly shared. Pays for a control block and atomic counting.
T& or T*No ownerFor code that only uses an object someone else owns. It never deletes.
RAII beyond memory, in the standard library
TypeAcquiresDestructor releases
std::unique_ptr<T>a heap objectdelete
std::vector<T>a heap arraythe elements and the array
std::ifstreaman open filecloses it
std::lock_guard<std::mutex>a locked mutexunlocks 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.

08 Check yourself

Question

A function creates std::lock_guard<std::mutex> g(m); and then a call inside it throws. What happens to the lock?

Question

auto a = std::make_shared<Node>(); auto b = a; a.reset(); Is the Node freed?

Question

Why does auto b = a; fail to compile when a is a unique_ptr?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?