C++ ยท Chapter 49 of 49

C++ Best Practices

Writing good C++ means favouring safety and clarity: prefer `std::vector`/`std::string` over raw arrays, use smart pointers over raw new/delete, and always initialise variables. Enabling compiler warnings (`-Wall -Wextra`) catches many bugs before runtime.

Follow consistent naming and formatting (tools like `clang-format` help), keep functions small and focused, and use `const` and references wherever a value shouldn't be copied or modified โ€” the compiler will help enforce your intentions.

Safety-first idioms

Prefer RAII (Resource Acquisition Is Initialisation) โ€” let objects like std::vector, std::string and smart pointers manage their own cleanup instead of manual new/delete. This is the single biggest source of safety in modern C++.

Tooling and style

Use `-Wall -Wextra -Werror` to catch subtle bugs at compile time. Format code consistently with clang-format, and use static analysers (clang-tidy) to catch common mistakes automatically.

Example 1 (cpp)
// Prefer this:
std::vector<int> nums = {1, 2, 3};
// Over raw arrays with manual new/delete
Output
(no direct output โ€” a design guideline)

std::vector manages its own memory safely, following RAII.

Example 2 (bash)
g++ -Wall -Wextra -std=c++17 main.cpp -o main
Output
(compiles with extra warnings enabled)

Compiler flags catch common mistakes like unused variables or shadowing.

Key points

  • Prefer std::vector/std::string over raw arrays/pointers.
  • Use smart pointers instead of manual new/delete (RAII).
  • Compile with -Wall -Wextra to catch bugs early.
  • Keep functions small, use const, and format consistently.
๐Ÿ’ก Note: Modern C++ (C++17/20) offers much safer alternatives to old idioms โ€” always prefer the modern approach unless you have a specific reason not to.

๐Ÿ“ Quick Quiz

1. What does RAII stand for the idea of?

2. Which flag set helps catch bugs at compile time?

3. Which is generally preferred in modern C++?