Modern C++ (C++11 to C++20)
“Modern C++” refers to the massive evolution of the language starting with C++11. It emphasizes safety, expressiveness, and performance. If you are writing C++ like it’s 1998, you are working too hard.1. Type Inference (auto)
Let the compiler deduce types for you. It prevents typos and makes refactoring easier.
2. Smart Pointers (Memory Safety)
We covered this in the Memory chapter, but it bears repeating: Never usenew and delete.
std::unique_ptr: The default choice. Fast, safe, exclusive ownership.std::shared_ptr: Use only when ownership is truly shared.
3. Move Semantics (Performance)
Before C++11, returning large objects (like avector with 1M items) involved copying the entire object. This was slow.
Move Semantics allow resources to be “stolen” from temporary objects. Instead of copying the data, we just copy the pointer to the data. It’s like handing over the keys to a house instead of building a replica house.
4. Structured Bindings (C++17)
Allows you to unpack tuples, pairs, and structs directly into variables. It’s similar to destructuring in JavaScript/Python.5. std::optional (C++17)
Express that a value might be missing without using “magic numbers” (like returning -1 for error) or null pointers. It forces you to handle the “empty” case.
6. std::variant (C++17)
A type-safe union. It can hold one of several types. Useful for state machines or parsing.
7. Concepts (C++20)
Concepts allow you to constrain template parameters. Instead of getting a 100-line error message when you pass the wrong type to a template, you get a clear, readable error.8. Ranges (C++20)
Ranges allow you to compose algorithms using the pipe operator (|). It makes code read like a data processing pipeline.
Summary
Modern C++ is a different beast from “C with Classes”.- Safety: Smart pointers and
std::optionaleliminate common bugs. - Expressiveness:
auto, structured bindings, and ranges make code readable. - Performance: Move semantics ensure abstractions are zero-cost.