C++ Best Practices
Guidelines for modern C++ code
Interview Relevant: Code quality
C++ Best Practices
Writing modern C++ requires unlearning "C with Classes" habits.
Modern Guidelines
- No Raw Pointers: Use
unique_ptrandshared_ptr. - RAII: Manage resources (memory, file handles) via object lifetime.
- const Correctness: Make variables
constunless modification is needed. - Use STL: Prefer standard algorithms (
std::sort,std::find) over raw loops.
Code Examples
Essential C++ best practices.
cpp
1// 1. Use smart pointers instead of raw pointers
2auto ptr = make_unique<MyClass>(); // Not: MyClass* ptr = new MyClass();
3
4// 2. Prefer const by default
5const auto& value = getValue();
6void process(const string& str);
7
8// 3. Use auto judiciously
9auto it = container.begin(); // Good
10auto x = 42; // Questionable - int is clear
11
12// 4. Initialize at declaration
13int count = 0; // Not: int count;
14
15// 5. Use range-based for
16for (const auto& item : collection) { }
17
18// 6. Prefer algorithms over raw loops
19auto it = find(begin(v), end(v), target);
20
21// 7. RAII for resource management
22class File {
23 FILE* handle;
24public:
25 File(const char* name) : handle(fopen(name, "r")) {}
26 ~File() { if (handle) fclose(handle); }
27};
28
29// 8. Use noexcept for move operations
30MyClass(MyClass&& other) noexcept;
31
32// 9. Prefer composition over inheritance
33
34// 10. Use explicit for single-argument constructors
35explicit MyClass(int value);