Coding Techniques
Modern C++ Features (C++11 to C++23) · Study material
Attributes that catch bugs
[[nodiscard]] makes the compiler warn when a result is ignored; [[likely]]/[[unlikely]] give branch hints; [[maybe_unused]] silences warnings for intentionally unused names. Digit separators and binary literals make numbers readable.
#include <iostream>
#include <string>
[[nodiscard]] bool save(const std::string& file) { return !file.empty(); } // ignoring the result → warning
[[nodiscard("check the error code")]] int connect(int port) { return port == 443 ? 0 : 1; }
int classify(int marks) {
if (marks >= 40) [[likely]] return 1; // hint for the optimiser
else [[unlikely]] return 0;
}
int main() {
[[maybe_unused]] int debug_level = 2; // no "unused variable" warning
bool ok = save("notes.txt");
int rc = connect(443);
auto big = 1'000'000; // C++14 digit separators
std::cout << ok << ' ' << rc << ' ' << classify(75) << classify(12) << ' ' << big << ' ' << 0b1010 << '\n';
return 0;
}
1 0 10 1000000 10
Using auto well
auto n = 10; // int
auto s = std::string("hi"); // std::string (not const char*)
const auto& big = huge_vector; // no copy
for (auto& x : v) x *= 2; // modify elements
for (const auto& [k, val] : m) … // structured bindings over a map
auto it = m.find(key); // iterator types are long – auto is ideal
auto copy = v[0]; // ✘ copies the element (auto drops & and const)
auto& ref = v[0]; // ✔ refers to it
auto x = {1, 2, 3}; // std::initializer_list<int>, probably not what you want Returning "maybe" results
// Absent value: optional
std::optional<User> find_user(int id);
if (auto u = find_user(7)) greet(*u);
// Value or a reason: expected (C++23)
std::expected<Config, std::string> load(std::string_view path);
auto cfg = load("app.toml");
if (!cfg) log(cfg.error());
// One of several types: variant + visit
using Shape = std::variant<Circle, Rect>;
double a = std::visit([](const auto& s) { return s.area(); }, shape); Modern C++ style checklist
- No naked new/delete; use smart pointers and containers.
- nullptr, enum class, using aliases, brace initialisation.
- auto for obvious or verbose types; const auto& in loops.
- optional/expected/variant instead of sentinel values and unions.
- string_view and span for read-only parameters.
- std::format/print for text; ranges and algorithms instead of raw loops.
- constexpr/consteval for compile-time work; [[nodiscard]] on important results.