Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Programming Shortcut: C++

Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about ownership and resource lifetime, by convention.

Many languages wearing one name

C++ has a reputation, and it earned it. It is enormous. It contains all of C, a system of classes, a second language for writing code that writes code, a standard library the size of a small city, and forty-odd years of features added on top of each other, with very few ever taken away.

Nobody uses all of it. Not the people who write the compilers, not the committee that designs it. Every team that writes C++ picks a dialect, a sensible subset they agree to live in, and ignores the rest. You get to do the same, starting today.

So this article picks for you. It skips the city and visits one building, the idea C++ gave the rest of programming: a resource belongs to an object, and when the object’s life ends, the resource goes back. Memory, open files, network connections, locks: in the C++ most people write today, almost none of them are ever released by hand. They are released by a closing brace.

Bjarne Stroustrup started the work that became C++ in 1979. He wanted the speed and control of C for programs too big to keep in your head, and the problem of remembering to clean up was one of the first he solved. It is also the part of C++ that will still be useful to you if you never write another line of it, because once you see it here, you will spot it in every language you use.

What you already have

Most of what you know carries over without a fuss:

What you knowluxC++
a recordstruct Point { x: int, y: int }struct Point { int x; int y; };
a growable array[1, 2, 3]std::vector<int>{1, 2, 3}
textstringstd::string
a value that might be missingOptionstd::optional (and * reads it without checking)
an error you expectResultstd::expected (C++23), or an exception
printing a lineprint(...)std::println(...) (C++23)
cleanup when you’re donenothing to clean: readFile closes the file for youa destructor

Variables, conditionals, loops, functions and recursion look the way they look in C or Java, braces and semicolons included. You know them. The last row is the one that’s new, and it’s the rest of this article.

Edit, compile, run

C++ is compiled: a program called a compiler reads your whole source file and turns it into a machine-code program you then run. This article uses one compiler, g++, from the GNU Compiler Collection (GCC). The steps are shown on Linux. On Debian or Ubuntu, one command installs it:

sudo apt install g++

For macOS, Windows and other compilers, see isocpp.org/get-started.

Make a file called hello.cpp:

#include <print>

int main() {
    std::println("Hello from C++");
}

Then compile it and run it with one line:

g++ -std=c++23 -Wall -Wextra -Werror -fsanitize=address,undefined -o hello hello.cpp && ./hello

That’s a long line, so here’s what it says. -std=c++23 asks for the 2023 edition of the language. -Wall -Wextra turn on the compiler’s warnings, and -Werror makes every warning stop the build, so you can’t scroll past one. -fsanitize=... adds sanitizers: extra checks compiled into your program that watch it run and stop it loudly when it touches memory it shouldn’t. They’ll matter later. -o hello names the program, and && ./hello runs it if the build worked.

After this, every change is three keystrokes: edit the file, press the up arrow, press Enter. Keep this terminal open; every example below runs the same way.

Things you borrow from the machine

Start with a word. A resource is anything your program borrows from the operating system and has to give back. Memory is one. An open file is another: the system keeps a little record for every file a program has open, and it only has so many. A network connection, a lock that keeps two threads out of each other’s way, a window on the screen: all resources.

Every resource has a lifetime, the stretch of time between getting it and giving it back. Get it, use it, return it. The rule is simple. Following it is not, because programs don’t run in a straight line. Here’s the shape, in C++ that looks a lot like C:

bool save(const char* path, int score) {
    FILE* f = std::fopen(path, "w");
    if (!f) return false;
    if (score < 0) return false;        // oops: f is never closed
    std::fprintf(f, "%d\n", score);
    std::fclose(f);
    return true;
}

One fopen, one fclose, and already a path that leaks. Every return is an exit, and every exit has to remember. In C, remembering is your job; the C article is about living with that. Add a few more resources and a few more exits and you get code where more lines are about cleaning up than about doing anything.

You’ve probably met a fix for this already. Python has with. Java has try-with-resources, C# has using, Go has defer. Each one is a way of saying “when this block ends, however it ends, do this.” If your first language was lux, you met the problem from the other side: readFile opens, reads and closes in one call, so you never held a file long enough to forget it.

C++ answers it differently. It doesn’t add a cleanup statement. It ties the resource to an object, and gives every object an ending.

The closing brace does work

A class in C++ is a type with fields and functions attached. (A struct is the same thing, except that its fields are visible from outside by default.) Two of those functions are special. The constructor has the class’s name and runs when an object is made. The destructor has the class’s name with a ~ in front, and it runs, automatically, when the object’s lifetime ends.

For an ordinary local variable, its lifetime ends at the closing brace of the block it was declared in. You never call a destructor. The brace calls it for you.

#include <print>
#include <string>

class Noisy {
public:
    Noisy(std::string name) : name(name) { std::println("hello, {}", name); }
    ~Noisy() { std::println("goodbye, {}", name); }
private:
    std::string name;
};

int main() {
    Noisy outer("outer");
    {
        Noisy first("first");
        Noisy second("second");
        std::println("inside the block");
    }
    std::println("after the block");
}

It prints:

hello, outer
hello, first
hello, second
inside the block
goodbye, second
goodbye, first
after the block
goodbye, outer

Look at the order. Objects are destroyed in reverse: last made, first gone. That isn’t a quirk. If second was built using first, then second has to go while first is still there, the way you’d take down a tower of blocks from the top.

(The : name(name) bit is how a constructor fills in a field before its body runs. It does what this.name = name does in Java.)

Now try the exits that broke save. An early return and an exception, which is C++’s way of stopping a function partway and jumping out to whoever is willing to handle the problem (the Java article is the place to learn exceptions properly):

#include <print>
#include <stdexcept>

struct Guard {
    const char* name;
    ~Guard() { std::println("cleaned up after {}", name); }
};

void leave_early() {
    Guard g{"leave_early"};
    std::println("returning early");
    return;
    std::println("never printed");
}

void blow_up() {
    Guard g{"blow_up"};
    throw std::runtime_error("something broke");
}

int main() {
    leave_early();
    try {
        blow_up();
    } catch (const std::exception& e) {
        std::println("caught: {}", e.what());
    }
}
returning early
cleaned up after leave_early
cleaned up after blow_up
caught: something broke

Both exits ran the destructor. The exception didn’t even reach the catch before blow_up’s guard cleaned up, because leaving a function by an exception still ends the lives of everything inside it. No matter which way out a block takes, its objects are destroyed on the way. (The & in catch (const std::exception& e) means the handler looks at the exception itself rather than a copy; references come up again below.)

The pattern has a name with a famous handicap: RAII, for Resource Acquisition Is Initialization. Read it as two halves of a promise. The constructor gets the resource. The destructor gives it back. Since the language guarantees the destructor runs, the resource can’t outlive the object that holds it. (Some people call it scope-bound resource management, which says more and is said less.)

Here it is holding something real, a C file handle:

#include <cstdio>
#include <print>

class File {
public:
    File(const char* path) : f(std::fopen(path, "w")) {}
    ~File() {
        if (f) std::fclose(f);
        std::println("closed");
    }
    void write(const char* text) { std::fputs(text, f); }
private:
    std::FILE* f;
};

bool save(const char* path, int score) {
    File out(path);
    if (score < 0) return false;
    out.write("a good score\n");
    return true;
}

int main() {
    save("score.txt", -1);
    save("score.txt", 10);
}

Same function, same early return, and now there’s nothing to forget. The file closes on both paths, because the object that holds it ends on both paths.

One owner

RAII raises a question it can’t answer on its own. If an object gives its resource back when it dies, what happens when there are two of them?

Picture a copy of out. Two File objects, each holding the same FILE*, each with a destructor that closes it. The first destructor closes the file. The second closes it again. Closing a file twice is a bug in C, and in C++ it’s the same bug with a nicer coat on. (What a copy actually contains, the value itself or just a way to reach it, is the subject of the C# article.)

The answer is a rule you’ve probably followed without naming it, the one about library books. Lots of people can read a book, but exactly one person checked it out, and that person brings it back. That person is the owner. Ownership means: for every resource, there is one object responsible for releasing it.

C++ lets you write that rule into a class. You can forbid copies outright:

#include <cstdio>

class File {
public:
    File(const char* path) : f(std::fopen(path, "w")) {}
    ~File() { if (f) std::fclose(f); }
    File(const File&) = delete;
    File& operator=(const File&) = delete;
private:
    std::FILE* f;
};

int main() {
    File a("a.txt");
    File b = a;
}

File(const File&) is the copy constructor, the function that would make a copy. (The & means it receives the original itself rather than a copy of it; more on that below.) = delete removes it. Now the compiler refuses:

error: use of deleted function ‘File::File(const File&)’

That’s the first time in this article the compiler has helped, and it’s a fair deal: one line in the class, and nobody can make the double-close mistake with it.

Handing it over

A thing that can never be copied is a bit stuck, though. You want to make a file in one function and hand it to another, or keep several in a std::vector. Library books get passed between friends, too; the point is that only one person has the book at a time.

That’s a move. Moving an object hands its resource to a new object. For a class written like this one, or for unique_ptr, the old object is left empty, so its destructor has nothing to give back. (Other standard types promise less: a moved-from object is safe to destroy or assign to, and nothing more.) C++ writes it with std::move:

#include <memory>
#include <print>
#include <utility>

int main() {
    std::unique_ptr<int> mine = std::make_unique<int>(42);
    std::println("mine holds {}", *mine);

    std::unique_ptr<int> yours = std::move(mine);
    std::println("yours holds {}", *yours);
    std::println("mine is empty: {}", mine == nullptr);
}

std::unique_ptr is the standard library’s ready-made owner for memory. A pointer is a value that holds a memory address (the C article has the full story), and a unique_ptr is a pointer with a destructor that frees what it points to. It can’t be copied. It can be moved. std::make_unique<int>(42) asks for room for one int, puts 42 in it, and gives you the owner.

The name std::move is a little misleading, so here’s what it does: nothing, by itself. It’s a label that says “I’m finished with this; whoever receives it may take what’s inside.” The receiving object does the taking.

That’s enough to say what a function wants just by looking at its parameters. The types tell you who owns what:

void keep(std::unique_ptr<Photo> photo);   // takes ownership: you hand it over
void show(const Photo& photo);             // borrows: just looking
std::unique_ptr<Photo> load(const char* path);  // gives ownership to you

The & makes a reference, a second name for an object that lives somewhere else. A reference owns nothing; when it goes away, nothing is released. Passing one is called borrowing: you get to use the thing, and its owner still has to give it back.

And for the rare thing that really does have several owners, there’s std::shared_ptr. It keeps a count of how many owners exist, and the last one to leave turns off the lights:

#include <memory>
#include <print>

int main() {
    auto first = std::make_shared<int>(7);
    std::println("owners: {}", first.use_count());
    {
        auto second = first;
        std::println("owners: {}", first.use_count());
    }
    std::println("owners: {}", first.use_count());
}

That prints 1, then 2, then 1. When first goes away too, the count hits zero and the memory goes back. Copying a shared_ptr is allowed, because copying is how you add an owner.

Put these together and something quiet happens. Most classes in modern C++ don’t need a destructor at all. A class that holds a std::string, a std::vector and a std::unique_ptr already cleans up after itself, because each of its fields is an owner, and the fields’ destructors run when the class’s does. People call this the rule of zero: write no cleanup code, and build from parts that already know how. You’ll write a destructor yourself only at the bottom of the tower, where something like a FILE* from C first comes in.

Nobody is checking

Here’s where C++ parts company with some of the languages you may know. Ownership in C++ is a convention: a set of habits the language makes easy and the standard library follows. The compiler enforces some of it, like the deleted copy. Most of it, it doesn’t check at all.

Using a unique_ptr after you’ve moved out of it compiles without a murmur:

#include <memory>
#include <print>
#include <utility>

int main() {
    auto note = std::make_unique<int>(42);
    auto other = std::move(note);
    std::println("{}", *note);
}

So does borrowing from something that’s about to move. A std::vector that grows gets a bigger block of memory and moves its elements there, which leaves every reference into the old block pointing at memory that has been given back:

#include <print>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> names = {"Ada"};
    std::string& first = names[0];
    names.push_back("Grace");
    std::println("{}", first);
}

-Wall -Wextra -Werror said nothing about either one. The sanitizers caught both, but only while the program ran, and only because the bad line actually ran. That’s the trade C++ makes: you get the ownership ideas, and you keep the job of following them. The Rust article shows the other choice, a compiler that checks every move and every borrow before your program runs, and turns down both of these programs.

The habit that keeps you safe is short. Never write new or delete; use std::make_unique and let an owner do it. Don’t use something after you’ve moved it. Don’t hold a reference into something that might grow, move or die before you’re done with it.

Beware of trying to learn all of it. C++ has a feature for everything and three ways to do most things, and every corner has a passionate expert. Don’t chase the corners. Pick the small dialect this article used: classes that own things, std::unique_ptr, std::vector, std::string, references for borrowing, and nothing raw that owns. That dialect is real C++, it’s what good code looks like, and it will carry you a long way. When an old tutorial hands you new and delete, close it and find a newer one.

A file that tidies up after itself

The project is one file: a class called Scratch that makes a temporary file, lets you write to it, and deletes it from the disk when its lifetime ends. It’s built so you can watch, because the file appears in the directory and then disappears.

Copy projects/cpp/scratch.cpp into a folder of its own and build it the same way as before:

g++ -std=c++23 -Wall -Wextra -Werror -fsanitize=address,undefined -o scratch scratch.cpp && ./scratch

Here’s the class. It’s the File from earlier, grown up: it refuses copies, it can be moved, and its destructor closes the file and then removes it.

class Scratch {
public:
    explicit Scratch(std::string name) : name_(std::move(name)), file_(std::fopen(name_.c_str(), "w")) {
        if (!file_) {
            throw std::runtime_error("could not create " + name_);
        }
        std::println("  [open   {}]", name_);
    }

    ~Scratch() {
        if (!file_) {
            return;
        }
        std::fclose(file_);
        std::filesystem::remove(name_);
        std::println("  [remove {}]", name_);
    }

    Scratch(const Scratch&) = delete;
    Scratch& operator=(const Scratch&) = delete;

    Scratch(Scratch&& other) noexcept
        : name_(std::move(other.name_)), file_(std::exchange(other.file_, nullptr)) {}

    Scratch& operator=(Scratch&&) = delete;
    // ...

The new piece is Scratch(Scratch&& other), the move constructor. The && marks an object someone has said they’re finished with. The move constructor takes that object’s name and file handle, and std::exchange leaves nullptr (no file) in its place. That’s why the destructor starts by checking file_: an emptied object has nothing to give back. The noexcept promises that the move can’t throw, which lets a growing std::vector move its elements instead of trying to copy them. The two operator= lines turn off assignment, by copy and by move, to keep the class small.

If fopen fails, the constructor throws. An object whose constructor didn’t finish gets no destructor call, and that’s right: it has no file, so there’s nothing to clean up.

The rest of the file is a main that runs four little scenes. When you run it you’ll see:

1. A block:
  [open   notes.tmp]
  notes.tmp exists? true
  [remove notes.tmp]
  notes.tmp exists? false
2. An exception:
  [open   work.tmp]
  work.tmp exists? true
  [remove work.tmp]
  caught: step two failed
  work.tmp exists? false
3. A move:
  [open   draft.tmp]
  [open   log.tmp]
  draft.tmp exists? true
  log.tmp exists? true
4. The end of main:
  [remove draft.tmp]
  [remove log.tmp]

Read it scene by scene. In the first, the file lives as long as the block, and no longer. In the second, a function throws halfway through its work, and the file is gone before the catch even prints. In the third, a function makes a file and returns it, and main moves another into a std::vector. Neither is removed when the function or the variable that made it ends, because neither was the owner by then. They go at the very end, when the vector does, once each.

Count the [remove] lines: four files opened, four removed, and no line in main that removes anything.

What I left out

Almost everything. Templates, inheritance and virtual functions, operator overloading, the many kinds of constructor, const in all its moods, namespaces, headers and building programs from more than one file, and the long list of rules about when the compiler writes copy and move functions for you. Also left out: how && works in detail, which deserves a sitting of its own. Every one of those is real, and you can write good C++ for a while without any of them.

When you want more, go to the people who make the language. A Tour of C++ is Stroustrup’s own short overview. cppreference.com is the reference everyone uses, and its RAII page is a good next read. The C++ Core Guidelines have a whole section of rules on resource management, written by Stroustrup and Herb Sutter, and the first rule in it is the idea from this article.

Look at what the brace costs

Is all this cleanup free? Ask the compiler. Save these two functions as owners.cpp. They do the same work, one by hand and one with an owner:

#include <memory>

void use(int* p);

void by_hand() {
    int* p = new int(42);
    use(p);
    delete p;
}

void by_owner() {
    auto p = std::make_unique<int>(42);
    use(p.get());
}

Then ask g++ to stop before making a program and show you the machine instructions it would have used, with full optimization:

g++ -std=c++23 -O2 -S owners.cpp

Open owners.s. Under _Z7by_handv and _Z8by_ownerv (the compiler’s spelled-out names for your two functions), compare the instructions from the first call to the jmp at the end. Then look for the one thing by_owner has that by_hand doesn’t, near _Unwind_Resume, and bring this question: if use throws an exception, where does by_hand free its memory?

  • C: memory, pointers and the data structures built on them; what the machine does when nobody owns anything.
  • Rust: ownership and borrowing again, checked by the compiler before the program runs.
  • Java: exceptions, the other way out of a function.
  • C#: value and reference semantics, or what a copy contains.

Tested with G++ 14.2 (-std=c++23), November 2026.