Modern C++ RAII: Stop Writing Cleanup Code

The Leak You Can’t See

It’s 3 a.m., and your phone buzzes. The order service crashed again. It ran out of memory, as it did twice already this week.

You restart it, and it’s fine, for now. You pull up the memory graph and see the same shape as last time: a slow, steady climb over a few days. There’s no big spike and no bad deploy to blame. And nobody on the team can make it happen on their own laptop.

Days later, someone finally finds the cause. It’s a few lines of code that look fine:

void process(const Request& req) {

   Buffer* buf = new Buffer(req.size());

   parse(req, *buf);      // may throw

   publish(*buf);         // may throw

   delete buf;

}

See the delete at the end? It’s right there. The problem is the two lines above it. If either one hits a bad request, it throws an exception. An exception is C++’s way of saying “something went wrong, stop and jump to the error handler.” Your program skipped the rest of the functions, including the delete.

So every bad request leaves one buffer behind. A few bad requests a minute add up to that slow climb on the graph.

Here’s the frustrating part: this isn’t a rookie mistake. Microsoft’s C++ code checker warns about this pattern. Good engineers write this bug often, because the code looks right.

The usual fix is a smart pointer:

void process(const Request& req) {

   auto buf = std::make_unique<Buffer>(req.size());

   parse(req, *buf);

   publish(*buf);

}   // buf is freed here, no matter how we leave

A unique_ptr owns the memory. When the function ends, it frees the buffer for you. It doesn’t matter how the function ends: a normal return, an early return or an exception. You don’t have to remember to delete it.

Most people learn this and stop there. “Smart pointers fix memory leaks. Got it.” But that’s only half the lesson. Memory isn’t the only thing your code borrows and has to give back.

Let Objects Clean Up After Themselves

The trick behind unique_ptr has a name: RAII in C++. It stands for Resource Acquisition Is Initialization. It’s an awkward name for a simple idea:

When you get something you’ll need to give back, wrap it in an object, and let that object give it back.

Every C++ object can have a destructor. That’s a special function that runs automatically when the object goes out of scope. A local object goes away when it is out of scope, indicated by the closing brace of the block. C++ promises the destructor will run even when an exception skips the rest of the function.

So instead of writing “close this” at every exit, you write it once, in the destructor. After that, you don’t think about it again.

That works for much more than memory. Here’s what it looks like for the usual troublemakers.

Files

C++ file streams like std::ofstream already close themselves.

But, there are plenty of code still uses C-style FILE* handles. You can give unique_ptr a custom deleter for those:

struct FileCloser {

   void operator()(std::FILE* file) const noexcept { std::fclose(file); }

};

using File = std::unique_ptr<std::FILE, FileCloser>;

File open_file(const char* path, const char* mode) {

   return File{std::fopen(path, mode)};

}

The program now closes the File automatically when it destroys the object. If opening failed, it holds nothing and does nothing.

We pass a custom deleter to the unique_ptr template, i.e., FileCloser. So, when the object returned by open_file goes out of scope, the FileCloser() operator is called, which invokes fclose on the file.

Database connections

Database libraries usually give you a handle and a function to close it. In PostgreSQL’s C library, that’s PGconn* and PQfinish.

It is the same pattern as the file:

struct PgFinish {

   void operator()(PGconn* c) const noexcept { PQfinish(c); }

};

using PgConnection = std::unique_ptr<PGconn, PgFinish>;

There’s a catch that trips people up. Even when the connection fails, the library still hands you a handle, and you still have to close it. Hand-written code often forgets that. PgConnection doesn’t.

Database transactions

A transaction is a group of database changes that either all happen or none happen. Once you start one, you must either commit it (keep the changes) or roll it back (undo them). A small class can make “undo” the default:

class Transaction {
public:
    explicit Transaction(Db& db) : db_(db) { db_.execute("BEGIN"); }
    ~Transaction() {
        if (!committed_) {
            try { db_.execute("ROLLBACK"); } catch (...) {}
        }
    }
    void commit() { db_.execute("COMMIT"); committed_ = true; }
private:
    Db& db_;
    bool committed_ = false;
};

If anything goes wrong before commit(), the destructor rolls everything back. You can’t accidentally leave a half-finished transaction hanging. (The try/catch in the destructor is on purpose. More on that below.)

Network connections

A network socket is an integer file descriptor. However, unique_ptr expects to manage a raw pointer and delete it with delete.

So, we write a tiny class:

class Socket {

public:

   explicit Socket(int fileDescriptor) : fileDescriptor_(fileDescriptor) {}

   ~Socket() { if (m_fileDescriptor >= 0) ::close(m_fileDescriptor); }

   // Preventing copying

   Socket(const Socket&) = delete;  

   // Preventing assignment so only one owner

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

   int get() const { return m_fileDescriptor; }

private:

   int m_fileDescriptor;

};

Blocking copies matter. If two objects thought they owned the same socket, it would close twice. In real code, you’d also add move support so that you can pass a Socket around. Either way, you write this class once and reuse it everywhere.

Locks and threads

The standard library already handles these. std::scoped_lock unlocks a mutex when it goes away. C++20’s std::jthread waits for its thread to finish when it goes out of scope. The older std::thread calls std::terminate if it is still joinable when destroyed.

Everything else

Sometimes the cleanup is just a one-off action, like deleting a temp file. For that, use a scope guard: an object that runs a bit of code when it goes away. The Guidelines Support Library has one called gsl::finally:

auto cleanup = gsl::finally([&] { std::filesystem::remove(tmp_path); });

So, when the function ends, the temp file gets deleted.

The bonus: classes with no cleanup code

Once each resource has its own wrapper, something nice happens. A class that holds a Socket and a std::vector doesn’t need a destructor at all. Its members already clean up after themselves. This is known as the rule of zero. Most of your classes should have zero cleanup code, because their parts already handle it.

Why You Can Trust It

This isn’t a style choice. A few solid reasons back it up.

The language promises it. C++ guarantees that local objects are destroyed when they go out of scope, on every path out. They’re also destroyed in reverse order. If you open a connection and then start a transaction, the transaction rolls back before the connection closes, and you didn’t have to arrange that.

The experts agree. The C++ Core Guidelines say that releasing resources by hand is error-prone and that RAII is the simplest way to prevent leaks. Microsoft’s own documentation for that leak warning suggests swapping manual delete for vector and unique_ptr. CERT’s secure coding rules even treat unclosed files as a security risk, because an attacker can use them to exhaust system resources.

It handles a case manual cleanup can’t. If a constructor fails halfway through, that object’s destructor never runs. Cleanup code written there never happens. But any members that were already built do get cleaned up. So a class built from RAII parts stays safe even when its own constructor fails.

RAII does have a few rules you need to follow:

  • Destructors shouldn’t throw. If one throws while another error is already being handled, your program stops. That’s why Transaction catches its own errors.
  • Destructors can’t tell you something failed. Closing a file can fail, and so can a clean database disconnect. When you need to know, call close() or commit() yourself, and let the destructor be the backup.
  • Always name your lock. std::scoped_lock(m); with no variable name unlocks right away. It needs a name, like std::scoped_lock lock(m);, to last until the end of the block.

A Thousand Open Files

Back in 2009, a developer posted on the Arch Linux forums with a strange problem. A library they were writing kept leaking file handles. One function opened a log file, wrote to it and closed it, and it ran thousands of times. After a while, the file couldn’t be opened anymore. When they checked, the program was holding about a thousand copies of that log file open. A coworker had added a return that kept the file open before it closed.

Nobody did anything wrong, exactly. Someone made a normal, sensible edit, and the cleanup quietly stopped happening. That’s how manual cleanup breaks. It doesn’t fail the day you write it. It fails the day someone changes the code around it.

Here’s that same kind of bug in a function that juggles three things:

bool sync_orders(const char* conninfo, const char* path) {

   PGconn* conn = PQconnectdb(conninfo);

   if (PQstatus(conn) != CONNECTION_OK) { PQfinish(conn); return false; }

   std::FILE* out = std::fopen(path, "w");

   if (!out) { PQfinish(conn); return false; }

   auto* rows = new OrderBatch;

   if (!load_orders(conn, *rows)) {

       delete rows; std::fclose(out); PQfinish(conn);

       return false;

   }

   write_orders(out, *rows);   // if this throws, all three leak

   delete rows; std::fclose(out); PQfinish(conn);

   return true;

}

And here it is with RAII:

bool sync_orders(const char* conninfo, const char* path) {

   PgConnection conn{PQconnectdb(conninfo)};

   if (PQstatus(conn.get()) != CONNECTION_OK) return false;

   File out = open_file(path, "w");

   if (!out) return false;

   auto rows = std::make_unique<OrderBatch>();

   if (!load_orders(conn.get(), *rows)) return false;

   write_orders(out.get(), *rows);   // a throw is safe now

   return std::fclose(out.release()) == 0;

}

All the cleanup lines are gone. You could add five more return statements, and nothing would leak. The last line closes the file by hand on purpose. If the final write didn’t save properly, the caller should find out.

Your Next Step

Think of the resource in your code that has bitten you before. Maybe it’s a connection that never closes, a lock that gets stuck or a file that fills up a disk. Wrap it in a unique_ptr or a small class, and switch your code over to use it.

Then turn it into a team habit. When you see delete, close(), unlock() or disconnect() written by hand in a code review, ask one question: “What object should own this?”

Credit: Header Image by Luan Nguyen from Pixabay

Share the Post: