Skip to content
  • Best Practices & Idioms · C++

Best Practices & Idioms

LearnViaNotes @learnvianotes· 2 min read

A condensed set of rules (drawn from the C++ Core Guidelines) that keep modern C++ safe, readable and fast.

Resource management

Types & interfaces

  • Make things const by default — variables, parameters (const T&), member functions.

  • Prefer enum class, std::array/std::vector, std::string_view/std::span for views, std::optional for “maybe”.

  • Mark single-argument constructors explicit; mark overrides override; give polymorphic bases a virtual destructor.

  • Pass cheap types by value, others by const&; return by value (move/elision make it cheap).

  • Use strong types instead of bool/int soup: setTimeout(Seconds{5}), not setTimeout(5).

Expressions & control

  • Initialise every variable at declaration; prefer {} to catch narrowing.

  • Use auto to avoid repeating types, not to hide important ones.

  • Prefer algorithms and range-for over index loops; prefer std::ranges:: versions in C++20.

  • Use named casts (static_cast) and minimise them; never C-style casts.

  • Keep functions short and single-purpose; limit scope of variables (if (auto x = …; cond)).

Tooling

ToolWhy
-Wall -Wextra -Wpedantic -WerrorCatch mistakes at compile time
ASan / UBSan / TSanCatch memory errors, UB and races in tests
clang-tidyStatic analysis, modernisation checks (modernize-*, cppcoreguidelines-*)
clang-formatConsistent formatting, no style debates
CMake + a package manager (vcpkg/Conan)Reproducible builds and dependencies
GoogleTest / Catch2Unit tests

Idioms worth knowing

C++
#include <iostream>

template <typename Derived>
struct Shape {                                           // CRTP base
    double area() const { return static_cast<const Derived&>(*this).areaImpl(); }
    void describe() const { std::cout << "area " << area() << '\n'; }
};
struct Square : Shape<Square> {
    double s;
    explicit Square(double x) : s(x) {}
    double areaImpl() const { return s * s; }
};

int main() { Square{3}.describe(); }                     // resolved at compile time, no vtable
Output
area 9

What is CRTP and why use it?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report