C++ Reference ยท Preprocessor, Tools and Concepts
Common C++ idioms
A catalogue of classic C++ idioms with complete programs: RAII scope guards, pimpl, CRTP, the non-virtual interface, and the erase-remove idiom.
An idiom is a small, well-known way of using the language to solve a recurring problem. C++ has many of them, because the language gives you control over lifetimes, types and the build model, and a few patterns turn that control into safe and fast code. Experienced readers recognize them at a glance, which makes code easier to review.
This page collects the idioms you will meet most often: RAII, the scope guard, pimpl, CRTP, the non-virtual interface (NVI) and erase-remove. Each has a full program below. Some have their own reference page, linked at the end.
struct Guard { ~Guard() { /* cleanup runs on every exit path */ } };
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
The idioms
RAII and the scope guard
Resource Acquisition Is Initialization ties a resource to an object's lifetime: acquire in the constructor, release in the destructor. Because destructors run on every exit path, including exceptions and early returns, the resource cannot leak. Standard types such as std::unique_ptr, std::lock_guard and std::fstream are all RAII. A scope guard generalizes this to "run any function when leaving this scope", with a dismiss() to cancel on success. See RAII.
Pimpl
The "pointer to implementation" idiom hides private members behind a pointer to a type that is only forward-declared in the header. Changing the private data then no longer forces every includer to recompile. With std::unique_ptr<Impl> you must declare the destructor (and move operations) in the header and define them in the .cpp file, where Impl is complete; otherwise unique_ptr cannot instantiate its deleter. Details are on the pimpl page.
CRTP
The curiously recurring template pattern has a class derive from a base template instantiated with itself. The base can call derived functions through static_cast<Derived&>(*this), resolved at compile time. Use it for mixins (comparison, printing, counting instances) and static polymorphism when virtual calls would be too costly or the types are known at compile time. C++23 "deducing this" removes the need for CRTP in many cases. See CRTP.
Non-virtual interface
Make public functions non-virtual and put the customization points in private virtual functions. The base class keeps control of invariants, logging and pre/postconditions in one place, and derived classes only override the steps. Overriding a private virtual function is legal.
Erase-remove
std::remove and std::remove_if cannot shrink a container; they shift the kept elements forward and return the new logical end. You then call erase on that range. Since C++20, std::erase and std::erase_if do both in one call for the standard containers. See erase-remove.
Usage notes
- Rule of zero first. Most classes should own nothing directly. Wrap resources in RAII types and let the compiler generate special members.
- Pimpl costs an allocation and an indirection per object. Use it at library boundaries, not for small value types.
- CRTP errors are loud. If the derived class lacks the member the base calls, the error appears at instantiation, often with long messages. A
static_assertor a concept can improve them. - Do not CRTP-derive with the wrong type.
struct A : Printable<B>compiles and then casts to the wrong type. Making the base constructor private and the derived afriendprevents it. - Scope guards must not throw from their destructor. Destructors are
noexceptby default; an escaping exception callsstd::terminate. - Copy-and-swap, tag dispatch, type erasure and the factory are other common idioms; see the design patterns lesson.