Skip to content

Chapter 6 of 8

Modern C++ Utilities and Language Features

Modern C++ introduces a host of utilities that improve expressiveness and safety. Lambda expressions are anonymous function objects defined inline with the syntax [capture](params) -> return_type { body }. The capture clause controls how local variables are pulled in: [x] captures x by value, [&x] by reference, [=] captures all used variables by value, [&] captures all by reference, and combinations such as [=, &x] capture all by value except x by reference. std::function<R(Args...)> is a polymorphic function wrapper that can store any callable, including lambdas, function pointers, functors, and bind expressions. std::bind in <functional> produces a new callable with arguments partially bound using placeholders, though lambdas usually make std::bind unnecessary. std::ref and std::cref wrap a reference into a copyable object so that parameter templates can bind by reference rather than copy.

Several header-only types model possibly absent or one-of-several values without resorting to raw pointers or error codes. std::optional<T> may or may not contain a T and replaces sentinel-based or out-parameter patterns. std::variant is a type-safe union holding one of the listed alternative types, queried with std::holds_alternative and accessed with std::get. std::any is a type-safe single-value container for any copy-constructible type, retrieved with std::any_cast. std::string_view is a non-owning reference to a contiguous character sequence, cheap to pass by value and ideal for read-only string parameters. std::span extends the same idea to arbitrary element types, providing a safe pointer-plus-size view over contiguous memory such as a std::vector or a C array. Structured bindings in C++17 unpack aggregates, pairs, and tuples into named variables, as in auto [key, value] = *map.begin, replacing std::tie in many cases. C++17 also introduces init statements in if and switch, allowing scoped variables such as if (auto it = m.find(k); it != m.end()) to live for the entire branch. C++20 adds coroutines, where functions can be suspended and resumed using co_await, co_yield, and co_return, enabling generators, lazy pipelines, and asynchronous I/O without callback chains; the std::format facility, modeled on Python's, for type-safe text formatting; and modules, which replace header inclusion with export module math and import math, providing faster builds, better isolation, and freedom from macro leakage. std::bit_cast in C++20 reinterprets an object's bit representation as another type at compile time with well-defined results, replacing the older memcpy-based type punning trick. std::launder blocks the compiler from assuming a pointer still refers to the old object after placement new has revived the memory underneath it.

Several long-standing idioms in C++ center on grouping and qualifying names. A namespace groups related identifiers to avoid name collisions, accessed with the scope resolution operator or pulled into scope with using namespace. The enum class introduced in C++11 provides type-safe scoped enumerations whose values do not implicitly convert to integers and do not pollute the enclosing scope, accessed as Color::Red. The std::chrono library offers type-safe durations and clocks; std::system_clock reports wall-clock time, std::steady_clock is monotonic and ideal for measuring intervals, and std::high_resolution_clock provides the smallest tick period available. The std::filesystem library, standardized in C++17, offers portable paths and directory traversal, including std::filesystem::directory_iterator. Strings themselves are managed by std::string, which provides size and length queries, substr, find, replace, append, concatenation via operator+, and element access through operator[] or the bounds-checked at(); the in-memory std::stringstream supports stream-style insertion and extraction for building and parsing strings, and std::regex in <regex> provides standard-library regular expression support through std::regex_match, std::regex_search, and std::regex_replace, although it is widely regarded as cumbersome and slow compared with dedicated libraries.

All chapters
  1. 1Object-Oriented Foundations in C++
  2. 2Inheritance and Polymorphism
  3. 3Object Lifecycle and Resource Management
  4. 4Templates and Generic Programming
  5. 5Standard Library Containers and Iterators
  6. 6Modern C++ Utilities and Language Features
  7. 7Memory Management, Pointers, and Casting
  8. 8Error Handling, Concurrency, and the Compilation Model

Drill it

Reading is not remembering. These come from the Cpp Programming deck:

Q

What are the four main principles of OOP in C++?

The four pillars of OOP are:Encapsulation – bundling data and methods togetherAbstraction – hiding complex implementation detailsInheritance – deriving new clas...

Q

What is a class in C++?

A class is a user-defined type that encapsulates data members and member functions. Defined with the class keyword:class MyClass { public: int x; void show(); }...

Q

What is the difference between a class and a struct in C++?

The only default difference is access control:class members are private by defaultstruct members are public by defaultBoth can have methods, constructors, and i...

Q

What is inheritance in C++?

Inheritance allows a derived class to inherit members from a base class:class Dog : public Animal { };This promotes code reuse and establishes an is-a relations...