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.
// Prefer this:
std::vector<int> nums = {1, 2, 3};
// Over raw arrays with manual new/delete(no direct output โ a design guideline)std::vector manages its own memory safely, following RAII.
g++ -Wall -Wextra -std=c++17 main.cpp -o main(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.
