Modern Idioms That Pay Rent
string_view parameters, structured bindings, constexpr tables, and exhaustive switches over enum class.
Modern C++ is mostly removing footguns. Four idioms pay rent immediately.
- Narrow interfaces with types. A
std::string_viewparameter acceptsstd::string, a literal, or a slice without copying:
#include <string_view>
bool is_command(std::string_view s) {
return s.starts_with("--"); // C++20
}
Views do not own; they must not outlive the underlying string.
-
Structured bindings for pair/tuple/struct unpacking —
for (const auto& [k, v] : map)beats.first/.secondfor readability. -
constexprfor tables and limits — magic numbers move to named, compile-time-checked constants. -
Exhaustive
switchoverenum classwith nodefault— the compiler then forces you to update every switch when the enum grows. That is free maintenance.
And one deprecation to know: std::auto_ptr and throwing std::vector::operator[]
are history; dynamic exception specifications (throw(...)) are gone from
the language. Modern code catches specific exception types — Module 10's job.