Skip to content

Module 9 · Modern C++ — topic 3 of 3

Modern C++ Fundamentals

The features that define idiomatic C++11 to C++20: auto, range-for, move semantics, constexpr, structured bindings, optional, variant, string_view, enum class, and a look at C++20 ranges and concepts.

Beginner 16 min read·Lesson 40 of 40 in C++ Programming

Learning objectives

  • Use enum class, std::optional and std::variant
  • Explain move semantics at a practical level
  • Recognise C++20 ranges and concepts

Definition

Modern C++ refers to the language and library features introduced from C++11 onward and the idioms built on them — value semantics, RAII, type deduction and expressive, safe abstractions with no run-time overhead.

Introduction

C++ in 2026 looks very different from the C++ of 1998. Modern features replace error-prone patterns: enum class instead of plain enums, std::optional instead of magic "not found" values, std::variant instead of unsafe unions, and smart pointers instead of manual delete.

Why it matters

Industry codebases and interviews expect modern idioms.

These features eliminate whole categories of bugs while keeping performance.

Detailed explanation

enum class (C++11): scoped, strongly typed enumerations — Color::Red — that don't convert implicitly to int.

Move semantics: objects can transfer their resources instead of copying (std::move). Returning containers by value is cheap.

std::optional<T> (C++17): either a T or nothing; replaces sentinel values like -1. std::variant<A, B>: a type-safe union that knows which type it holds; visit it with std::visit.

std::string_view (C++17): non-owning view of characters for read-only parameters.

C++20 ranges: std::ranges::sort(v), views like v | std::views::filter(pred) | std::views::transform(f) compose lazily. Concepts constrain templates: template <std::integral T>.

Syntax

C++
enum class Status { Ok, NotFound };
std::optional<int> find_index(const std::vector<int>& v, int x);
std::variant<int, double, std::string> value = 3.5;
auto [key, val] = *map.begin();
if (auto r = find_index(v, 7)) std::cout << *r;
  • value_or(default) reads an optional with a fallback.
  • std::holds_alternative<T>(var) checks a variant's type.
  • Compile with -std=c++20 for ranges/concepts.

Code examples

enum class and optional

C++
#include <iostream>
#include <optional>
#include <vector>
enum class Level { Low, Medium, High };
std::optional<std::size_t> find_index(const std::vector<int>& v, int x) {
for (std::size_t i = 0; i < v.size(); ++i)
if (v[i] == x) return i;
return std::nullopt;
}
int main() {
Level l = Level::High;
std::cout << static_cast<int>(l) << '\n';
std::vector<int> v{4, 8, 15};
if (auto i = find_index(v, 8)) std::cout << "found at " << *i << '\n';
std::cout << find_index(v, 99).value_or(999) << '\n';
return 0;
}
Output
2
found at 1
999

std::variant with std::visit

C++
#include <iostream>
#include <string>
#include <variant>
#include <vector>
int main() {
std::vector<std::variant<int, double, std::string>> cells{42, 3.5, std::string("hello")};
for (const auto& c : cells)
std::visit([](const auto& x) { std::cout << x << ' '; }, c);
std::cout << '\n' << std::holds_alternative<double>(cells[1]) << '\n';
return 0;
}
Output
42 3.5 hello 
1

More examples

Move semantics in action

C++
#include <iostream>
#include <string>
#include <utility>
#include <vector>
struct Tracker {
std::string label;
explicit Tracker(std::string l) : label(std::move(l)) {}
Tracker(const Tracker& o) : label(o.label) { std::cout << "copy " << label << '\n'; }
Tracker(Tracker&& o) noexcept : label(std::move(o.label)) { std::cout << "move " << label << '\n'; }
};
std::vector<Tracker> build() {
std::vector<Tracker> v;
v.reserve(3);
v.emplace_back("a"); // constructed in place: no copy, no move
Tracker b("b");
v.push_back(b); // copy: b is still used later
v.push_back(std::move(b)); // move: we are done with b
return v; // returned without copying the vector
}
int main() {
auto v = build();
std::cout << v.size() << " trackers\n";
return 0;
}
Output
copy b
move b
3 trackers

Step-by-step explanation

  • emplace_back builds the element inside the vector — no copy or move printed.
  • push_back(b) copies because b is an lvalue.
  • push_back(std::move(b)) moves: the string's buffer is transferred.
  • Returning v uses move/elision, so no element copies happen; reserve prevented reallocation moves.

Expected output

Running “Move semantics in action” prints exactly:

TextOutput
copy b
move b
3 trackers

Practical applications

  • Configuration parsers return optional values.
  • JSON libraries represent values with variants.
  • High-performance code relies on moves to avoid copying buffers.

Best practices

  • Use enum class for all new enumerations.
  • Return std::optional instead of sentinel values.
  • Prefer value semantics; let moves make them cheap.

Common mistakes

Dereferencing an empty optional

Avoid

std::optional<int> r = find_index(v, 99);
std::cout << *r;

Prefer

if (r) std::cout << *r;
// or r.value_or(-1)

* on an empty optional is undefined behaviour; value() would throw.

Using a moved-from object as if unchanged

Avoid

std::string s = "data";
auto t = std::move(s);
std::cout << s.size(); // expecting 4

Prefer

std::string s = "data";
auto t = std::move(s);
s = "new"; // reassign before reuse

After a move, the source is valid but unspecified; only assign to it or destroy it.

Important notes

  • Ranges and concepts need -std=c++20; this course's examples compile as C++17 unless stated.
  • std::expected<T, E> (C++23) returns either a value or an error.

Key takeaways

  • enum class is scoped and type-safe.
  • optional and variant model 'maybe' and 'one of'.
  • Moves transfer resources instead of copying.

Try it yourself

  1. 1
    Rewrite a function that returns -1 for 'not found' to return std::optional.
  2. 2
    Model a shape as std::variant<Circle, Square> and compute areas with std::visit.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat advantage does `enum class Color { Red };` have over a plain enum?
  • BeginnerWhat is printed?
  • ModerateWhat is printed?
Practise this topic