How to improve C++ code quality
C++ gives you enough rope to write extremely fast code and enough rope to leak memory doing it. Most of the patterns worth fixing are about ownership and error handling — here are the ones that matter most, with real before/after code.
Raw new/delete
Manual new/delete pairs are the single most common source of leaks and double-frees in C++: every path through the function — including early returns and thrown exceptions — has to reach the matching delete, and it's easy to miss one.
Before — leaks if validate() throws
Widget* w = new Widget();
w->validate();
w->run();
delete w;
After — freed automatically on every path
auto w = std::make_unique<Widget>();
w->validate();
w->run();
using namespace std; in a header
Inside a .cpp file, this is a matter of taste. Inside a header, it pollutes the global namespace of every single translation unit that includes that header, which can cause subtle name collisions in files that never intended to opt into it.
Before — widget.h
#include <string>
using namespace std;
string describe(int id);
After — widget.h
#include <string>
std::string describe(int id);
Catch-all catch(...)
An empty ellipsis catch block swallows every exception — including ones the code has no idea how to actually recover from — and discards the information about what went wrong, which makes the next debugging session much harder.
Before — silent failure
try {
process(request);
} catch (...) {
}
After — specific, logged
try {
process(request);
} catch (const std::exception& e) {
log_error(e.what());
}
Magic numbers in conditions
A bare literal in a comparison forces the reader to guess what it means and makes the value harder to find and change consistently later.
Before
if (retries > 3) {
giveUp();
}
After
constexpr int kMaxRetries = 3;
if (retries > kMaxRetries) {
giveUp();
}
How REPO-SIGHT checks for these
These four are REPO-SIGHT's actual C++ rules — cpp-raw-new-delete, cpp-using-namespace-std-header, cpp-catch-all-ellipsis, and cpp-magic-number-literal — alongside long-function, deep-nesting, and TODO-without-ticket checks. Run it on a C++ repository to see which show up in yours.