Skip to content
Tutorials Center
My learning

Topics

Lesson 148 of 171 ยท Modern C++ and Beyond

Best Practices and Common Mistakes

The habits that keep modern C++ correct and readable - clear ownership, const correctness, no raw new, initialized variables, algorithms, warnings - and the bugs to avoid.

C++ gives you enormous control, and the language will rarely stop you from doing something unwise. The difference between C++ that's a pleasure to maintain and C++ that crashes on Fridays is mostly a set of habits: make ownership obvious, initialize everything, mark what doesn't change as const, let the standard library do the work, and let the compiler check as much as it can. None of these rules is new or clever. They're what experienced C++ developers do automatically, and what tools like the C++ Core Guidelines and clang-tidy encode.

This lesson collects those habits in one place, each with the reason behind it, and then walks through the mistakes that beginners (and plenty of professionals) make most often. Treat it as a checklist to review your own code against. Every section links to the lesson that covers the topic in depth.

Make ownership obvious

Every resource in a program must have exactly one clear owner responsible for releasing it. The single most effective C++ habit is to express ownership in types, so that reading a declaration tells you who cleans up:

You write It means
T (a value or member) I own it; it dies with me
std::vector<T>, std::string I own these elements
std::unique_ptr<T> I own it exclusively; ownership can be moved
std::shared_ptr<T> Ownership is shared; the last owner deletes it
T&, const T& I use it; someone else owns it; it's never null
T* I use it; someone else owns it; it may be null
std::span<const T>, std::string_view I look at data someone else owns

The corollary: don't write new and delete in application code. A raw new leaves ownership to comments and good intentions, and a single early return or exception leaks the object. std::make_unique, std::make_shared and containers do the same job and clean up on every path:

C++ Raw new leaks, unique_ptr doesn't

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.

When you design a class that owns a resource, follow the rule of zero: build it from members that already manage themselves (std::vector, std::unique_ptr, std::string) and write no destructor or copy operations at all (see The Rule of Zero, Three and Five). If you must write a destructor, write or delete all five special members. Function parameters follow the table too: take const T& or a view to read, T& to modify, and std::unique_ptr<T> by value only when the function takes ownership.

Initialize everything

Reading an uninitialized local variable is undefined behavior (see Undefined Behavior and Memory Safety). The program may print garbage, may work in debug builds and fail in release, or may be "optimized" in surprising ways. The habits are simple:

  • Declare variables where you first need them, with their value: const auto total = compute_total(items);.
  • Use brace initialization when the value is a literal or an empty default: int count{}; is zero, and braces reject narrowing conversions such as int n{3.7}; at compile time (see Variables).
  • Give every class member a default member initializer: int retries = 3;, bool enabled = false;, Widget* parent = nullptr;. A constructor that forgets a member then still leaves it in a known state.
  • If a value comes from a branch, compute it with a conditional expression, a switch expression in a small function, or an immediately invoked lambda instead of declaring it empty and filling it in later.
C++
struct Settings {
    int retries = 3;                     // never uninitialized
    double scale = 1.0;
    std::string label;                   // class types initialize themselves
};

const auto level = [&] {                 // computed once, then const
    if (verbose) { return 2; }
    if (quiet) { return 0; }
    return 1;
}();

Use const and constexpr generously

const is documentation the compiler enforces. Mark local variables const when they don't change after initialization, mark member functions const when they don't modify the object, and pass read-only parameters as const T& (see const Member Functions and mutable and const with Pointers and References). A reader who sees const can stop tracking that variable; a reader who doesn't see it must check every following line.

Values known at compile time should be constexpr instead of #define macros: they have a type, a scope and show up in the debugger (see Constants). Name them, too: constexpr int max_players = 8; explains itself, while a bare 8 in a condition is a magic number that someone will update in three places out of four.

Let the type system work for you

A function that takes (int, int, int) invites callers to swap arguments. A function that returns -1 for "not found" invites callers to forget the check. Types can make those mistakes impossible:

  • Use enum class instead of bool or int flags: open(path, Mode::read_only) reads better than open(path, true) (see Enumerations).
  • Return std::optional<T> for "maybe a value" and std::expected<T, E> for "a value or an error", instead of sentinel values (see std::optional, std::variant, std::any and std::expected).
  • Wrap quantities that are easy to confuse in tiny structs, often called strong types.
C++ Types that prevent mistakes

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 structs Meters and Seconds cost nothing at run time: they compile to the same code as plain doubles. What they buy you is that a swapped argument becomes a compile error instead of a wrong answer shipped to production.

Prefer algorithms and ranges to raw loops

A hand-written loop makes the reader reverse-engineer its purpose: is it searching? counting? transforming? A named algorithm states the intent, is tested by your library vendor, and often runs faster. When you catch yourself writing a loop with an index, a flag and a break, check whether std::ranges::find_if, count_if, any_of, sort, transform or a view pipeline already says it (see Ranges and Views and Algorithms: Searching, Sorting and Counting).

C++ The same logic, loops versus algorithms

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.

Projections such as &Order::amount and &Order::paid let algorithms sort and filter by a member without writing a lambda. Loops are still fine when they're the clearest expression, for example when one pass does several unrelated things. The goal is readable intent, not zero loops.

Turn on warnings and use the tools

The compiler is the cheapest code reviewer you'll ever have, but only if you ask. Compile with at least -Wall -Wextra (GCC/Clang) or /W4 (MSVC); add -Wconversion -Wshadow -Wpedantic for stricter checks, and -Werror in CI so warnings can't pile up (see Compilers, Flags and Optimization). Our editor already compiles with -Wall -Wextra. This example contains three real bugs on purpose; press Run and read the warnings before the output:

C++ Warnings that point at real bugs

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.

GCC reports an unused variable, a comparison of integers of different signedness, and "suggest parentheses around assignment used as truth value". Each is a one-line fix: delete bonus, loop with range-based for (or std::size_t), and write ==. Beyond warnings, make these part of your routine:

  • Sanitizers while testing: -fsanitize=address,undefined finds out-of-bounds access, use-after-free and signed overflow the moment they happen (see Assertions and Debugging).
  • Static analysis: clang-tidy (with the cppcoreguidelines-*, bugprone-* and modernize-* checks) and your IDE's analyzer catch patterns warnings don't.
  • A formatter: clang-format ends style debates and keeps diffs small.
  • Tests: even assert-based checks in a small test program catch regressions; frameworks like GoogleTest and Catch2 scale that up.

Common mistakes and their fixes

These bugs show up in code reviews again and again. Several of them compile without a single warning, which is what makes them dangerous.

Unsigned arithmetic surprises. size() returns an unsigned std::size_t, so v.size() - 1 on an empty vector doesn't give -1: it wraps around to the largest possible value, and a loop for (std::size_t i = 0; i < v.size() - 1; ++i) reads far past the end (see Integer Types).

Integer division. 7 / 2 is 3, even when you store the result in a double. Convert one operand first.

Modifying a container while iterating it. push_back can reallocate a vector and invalidate every iterator and reference into it; erase invalidates the erased element's iterator. Use std::erase_if, or the iterator returned by erase (see Iterators).

C++ Classic bugs and their fixes

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.

Dangling references and views. A reference, pointer, iterator, std::string_view or std::span doesn't keep anything alive. If the object it refers to dies first, using it is undefined behavior, and the code usually compiles cleanly:

C++
const std::string& first_name() {
    std::string name = "Ada";
    return name;                         // dangling: name dies at the closing brace
}

std::string_view view = std::string("temporary") + "!";   // dangling at the semicolon

auto& first = items.front();
items.push_back(next);                   // may reallocate: first now dangles

Return by value, store owning types (std::string, std::vector) in members, and use views only as function parameters or for data you know outlives them (see std::string_view and Returning Values).

A few more that every C++ developer learns the hard way:

  • Missing virtual destructor in a base class you delete through, and object slicing when a derived object is copied into a base by value (see Virtual Functions and Polymorphism).
  • using namespace std; in a header, which dumps every standard name into every file that includes it (see Namespaces).
  • Mixing std::cin >> and std::getline without discarding the leftover newline (see Reading User Input).
  • Comparing floating-point values with == after arithmetic: use a tolerance (see Floating-Point Numbers).
  • Signed integer overflow, which is undefined behavior, not wrap-around: choose a wide enough type or check before adding.
  • Passing big objects by value where const T& was meant, or returning std::move(local), which blocks copy elision and is slower than plain return local; (see Move Semantics).
  • std::endl in hot loops: it flushes the stream every time; write '\n' and flush when needed.
  • Macros for constants or functions: they ignore scopes and types; use constexpr variables and functions, or templates.

A review checklist

Before you call a piece of C++ finished, ask:

  1. Does every resource have an owner expressed in a type? Is there any raw new, delete, malloc or free?
  2. Is every variable and member initialized when it's created?
  3. Is everything that doesn't change marked const (or constexpr)?
  4. Can any argument be swapped or misread? Would an enum class, a strong type or std::optional make the mistake impossible?
  5. Is there a hand-written loop that a named algorithm or range pipeline would express more clearly?
  6. Can any reference, view or iterator outlive what it points to?
  7. Does it compile warning-free with -Wall -Wextra, and do tests pass under the sanitizers?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. std::vector<int> v; (empty). What does v.size() - 1 evaluate to?

    size() returns an unsigned std::size_t, and unsigned arithmetic wraps modulo 2^N, so 0 - 1 becomes the maximum value (18446744073709551615 on 64-bit). It's well defined, just almost never what you meant.
  2. 2. A function does Texture* t = new Texture; validate(); delete t; and validate() throws. What happens to the Texture?

    Stack unwinding destroys objects, but a raw pointer is just an address with a trivial destructor. Only std::unique_ptr (or another owning type) would delete the Texture on the throwing path.
  3. 3. Which parameter type tells callers that a function takes ownership of a Widget?

    Taking a unique_ptr by value forces the caller to std::move ownership in. References, raw pointers and spans all mean "I use it, someone else owns it".
  4. 4. What does this print? int total = 7, count = 2; double avg = total / count; std::println("{}", avg);

    total / count is integer division and yields 3 before the conversion to double. std::println prints the double 3.0 as "3". Write static_cast<double>(total) / count to get 3.5.
  5. 5. Which line creates a dangling view?

    The std::string produced by the + expression is a temporary that is destroyed at the end of the full expression, leaving v pointing at freed memory. String literals live for the whole program, and s outlives v in the last option.

Summary

  • Express ownership in types: values and containers own, unique_ptr/shared_ptr own on the heap, references, pointers and views only observe. Avoid raw new/delete, and follow the rule of zero.
  • Initialize every variable and member when it's created; brace initialization rejects narrowing.
  • Mark everything that doesn't change const, and use constexpr instead of macros and magic numbers.
  • Let types prevent mistakes: enum class instead of bool flags, std::optional/std::expected instead of sentinels, strong types for easily confused quantities.
  • Prefer named algorithms and ranges to raw loops when they state the intent more clearly.
  • Compile with warnings on (and -Werror in CI), test with sanitizers, and add static analysis and a formatter.
  • Watch for the classics: unsigned wrap-around, integer division, iterator invalidation, dangling references and views, slicing, missing virtual destructors and using namespace std; in headers.

Next: C and C++: Differences and Interoperability, where you'll see how C++ grew out of C and how to use C libraries from modern C++.