If you learned C++ from an old textbook, you may have seen code full of NULL, raw new/delete, iterator types written out in full, and printf. Open a modern codebase and it looks almost like a different language: auto, range-based loops, lambdas, smart pointers, std::optional, ranges and std::println. The language did not change its spirit — it is still C++ with zero-cost abstractions — but since 2011 it has gained features that make code shorter, safer and faster.
This chapter is a guided tour of the most important additions from C++11 to C++23, standard by standard. You have already studied several of them in depth (lambdas, smart pointers, move semantics, templates with concepts), so for those we only point back to the right chapter. For the rest you get a compact, runnable example. At the end you will find an "old style vs modern style" cheat sheet and a short look at C++26.
How C++ Evolves
C++ is defined by an ISO standard (ISO/IEC 14882) written by the committee WG21. Since C++11 a new standard has been published every three years. Each standard is named after its year, and compilers implement it feature by feature.
| Standard | Nickname | __cplusplus | Headline features |
|---|---|---|---|
| C++98 / C++03 | "classic" C++ | 199711 | Templates, STL, exceptions, namespaces |
| C++11 | start of "modern C++" | 201103 | auto, range-for, lambdas, move semantics, smart pointers, nullptr, constexpr, threads |
| C++14 | minor release completing C++11 | 201402 | Generic lambdas, return type deduction, make_unique, digit separators |
| C++17 | library-rich release | 201703 | Structured bindings, optional, variant, string_view, if constexpr, filesystem |
| C++20 | the "big four" | 202002 | Concepts, ranges, coroutines, modules; also <=>, format, span |
| C++23 | completing C++20 | 202302 | print, expected, deducing this, ranges::to, std module |
Choosing the standard when you compile
A compiler does not automatically use the newest standard. GCC 15, for example, defaults to -std=gnu++17 (C++17 plus GNU extensions). You select a standard with a flag, and the predefined macro __cplusplus tells your code which one is active:
#include <iostream>
int main() {
std::cout << __cplusplus << '\n';
}g++ ver.cpp → 201703 (GCC 15 default: gnu++17)
g++ -std=c++20 ver.cpp → 202002
g++ -std=c++23 ver.cpp → 202302All programs in this chapter were compiled with g++ -std=c++23 -Wall -Wextra using GCC 15. Each feature is labelled with the standard that introduced it; your code needs at least that standard.
C++11: The Birth of Modern C++
C++11 was the biggest change in the language's history. You already met its largest features in separate chapters:
Lambda expressions — see Lambda Expressions.
Move semantics and rvalue references — see Move Semantics & Rvalue References.
std::unique_ptr,std::shared_ptr,std::weak_ptr— see Smart Pointers.Variadic templates — see Templates;
std::unordered_map/setandstd::array— see their STL chapters.
Here are most of the remaining everyday features in one program:
#include <iostream>
#include <map>
#include <string>
#include <vector>
enum class Level { Low, High }; // scoped enum: no implicit int conversion
constexpr int square(int n) { return n * n; }
static_assert(square(4) == 16, "compile-time check");
using Scores = std::map<std::string, std::vector<int>>; // type alias
struct Shape {
virtual double area() const = 0;
virtual ~Shape() = default; // defaulted function
};
struct Square final : Shape { // final: no further derivation
double side;
explicit Square(double s) : side{s} {}
Square() : Square(1.0) {} // delegating constructor
double area() const override { return side * side; } // override checked
};
struct NoCopy {
NoCopy() = default;
NoCopy(const NoCopy&) = delete; // deleted function: copying forbidden
};
int main() {
Scores sc{{"Asha", {90, 85}}, {"Ravi", {70}}}; // brace (uniform) initialization
for (const auto& entry : sc) // auto + range-based for
std::cout << entry.first << " has " << entry.second.size() << " mark(s)\n";
int* p = nullptr; // nullptr instead of NULL
std::cout << (p == nullptr ? "p is null\n" : "p set\n");
constexpr int arr_size = square(3); // computed at compile time
int arr[arr_size] = {};
std::cout << "array size " << sizeof(arr) / sizeof(arr[0]) << '\n';
Square s1, s2{2.5};
std::cout << s1.area() << ' ' << s2.area() << '\n';
Level l = Level::High;
std::cout << static_cast<int>(l) << '\n'; // explicit cast needed
std::string path = R"(C:\new\table)"; // raw string literal
std::cout << path << '\n';
}Output:
Asha has 2 mark(s)
Ravi has 1 mark(s)
p is null
array size 9
1 6.25
1
C:\new\tableWhat each feature gives you:
| Feature (C++11) | What it does | Why it matters |
|---|---|---|
auto | Type deduced from the initializer | No more std::map<std::string, std::vector<int>>::const_iterator |
Range-based for | for (x : container) | No index or iterator bugs |
nullptr | A real null pointer literal of type std::nullptr_t | NULL is just 0 and can pick the int overload |
| Brace initialization | T x{...} works for every type | One syntax everywhere; forbids narrowing |
enum class | Scoped, strongly typed enum | No name leakage, no silent conversion to int |
constexpr | May be evaluated at compile time | Constants and array sizes computed by the compiler |
static_assert | Compile-time assertion | Catches wrong assumptions before running |
using alias | using Name = Type; | Clearer than typedef, and can be templated |
override, final | Check overriding / stop inheritance | A typo in a virtual function's signature becomes a compile error |
= default, = delete | Ask for / forbid special functions | Non-copyable classes without tricks |
| Delegating constructors | One constructor calls another | No duplicated initialization code |
| Raw string literal | R"(...)" | Backslashes in paths and regexes need no escaping |
Brace initialization prevents narrowing
A conversion that may lose information (like double → int) is called narrowing. With = it is silently allowed; inside braces the standard says the program is ill-formed:
int main() {
double price = 99.75;
int a = price; // compiles: silently truncated to 99
int b{price}; // narrowing: ill-formed
int c{3.5}; // narrowing from a constant
return a + b + c;
}nar.cpp:4:11: warning: narrowing conversion of ‘price’ from ‘double’ to ‘int’ [-Wnarrowing]
nar.cpp:5:11: error: narrowing conversion of ‘3.5e+0’ from ‘double’ to ‘int’ [-Wnarrowing]Note a GCC quirk: for a non-constant value GCC only warns by default (Clang and MSVC give an error). Add -pedantic-errors and GCC turns both into errors, matching the standard. Never ignore this warning.
Deleted functions
= delete makes any use of a function a compile-time error. Deleting the copy constructor is the standard way to make a class non-copyable (this is exactly how std::unique_ptr forbids copies):
struct NoCopy {
NoCopy() = default;
NoCopy(const NoCopy&) = delete;
};
int main() {
NoCopy x;
NoCopy y = x; // error
}error: use of deleted function ‘NoCopy::NoCopy(const NoCopy&)’C++11 also brought the memory model and threads (std::thread, std::mutex, std::atomic), <chrono> for time, <random> for good random numbers, std::tuple, decltype and noexcept. These are big topics of their own; just know that they exist and that they are C++11.
C++14: Polishing C++11
C++14 is small but made C++11 features much more pleasant:
#include <iostream>
#include <memory>
#include <string>
auto average(int a, int b) { // C++14: return type deduced (double)
return (a + b) / 2.0;
}
constexpr int factorial(int n) { // C++14: loops allowed in constexpr
int result = 1;
for (int i = 2; i <= n; ++i) result *= i;
return result;
}
int main() {
auto add = [](auto x, auto y) { return x + y; }; // generic lambda
std::cout << add(2, 3) << ' ' << add(1.5, 2.25) << ' '
<< add(std::string("C++"), std::string("14")) << '\n';
std::cout << average(3, 4) << '\n';
static_assert(factorial(5) == 120); // C++17 allows omitting the message
auto p = std::make_unique<std::string>("owned"); // C++14
std::cout << *p << '\n';
int mask = 0b1010'1010; // binary literal + digit separator
long population = 1'428'627'663; // digit separators for readability
std::cout << mask << ' ' << population << '\n';
}Output:
5 3.75 C++14
3.5
owned
170 1428627663Generic lambdas —
autoparameters make a lambda work for any type; behind the scenes itsoperator()is a template.Function return type deduction —
auto average(...); the type comes from thereturnstatements (heredouble). All returns must deduce the same type.Relaxed
constexpr— C++11 allowed only a singlereturnstatement; C++14 allows local variables and loops.std::make_unique— the missing partner of C++11'smake_shared.Binary literals and digit separators —
0b1010'1010,1'428'627'663. The'is ignored by the compiler; it only helps humans.[[deprecated]]attribute — marks old APIs so that users get a warning (shown in the C++17 section below).
The static_assert without a message in this program is actually a C++17 feature; we are compiling as C++23, so it is fine.
C++17: A Richer Toolbox
#include <iostream>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <type_traits>
#include <variant>
std::optional<int> findRoll(const std::map<std::string, int>& m, std::string_view name) {
if (auto it = m.find(std::string(name)); it != m.end()) // if with initializer
return it->second;
return std::nullopt; // "no value"
}
template <typename T>
std::string describe(T value) {
if constexpr (std::is_integral_v<T>) // discarded at compile time for other T
return "integer " + std::to_string(value);
else if constexpr (std::is_floating_point_v<T>)
return "real " + std::to_string(value);
else
return "text " + std::string(value);
}
int main() {
std::map<std::string, int> rolls{{"Asha", 7}, {"Ravi", 12}};
for (const auto& [name, roll] : rolls) // structured bindings
std::cout << name << " -> " << roll << '\n';
if (auto r = findRoll(rolls, "Ravi")) std::cout << "Ravi found: " << *r << '\n';
std::cout << "Meena: " << findRoll(rolls, "Meena").value_or(-1) << '\n';
std::cout << describe(42) << " | " << describe(2.5) << " | " << describe("hi") << '\n';
std::variant<int, std::string> v = 10; // type-safe union
std::cout << "holds int? " << std::holds_alternative<int>(v) << '\n';
v = std::string("ten");
std::cout << "now: " << std::get<std::string>(v) << '\n';
std::pair p{3, 4.5}; // CTAD: pair<int, double>
std::cout << p.first + p.second << '\n';
}Output:
Asha -> 7
Ravi -> 12
Ravi found: 12
Meena: -1
integer 42 | real 2.500000 | text hi
holds int? 1
now: ten
7.5| Feature (C++17) | What it does |
|---|---|
| Structured bindings | auto [name, roll] = pair; unpacks pairs, tuples, arrays and simple structs into named variables |
if / switch with initializer | if (init; condition) — the variable's scope is limited to the if/else |
std::optional<T> | Either holds a T or nothing; replaces magic values like -1 for "not found" |
std::variant<A, B> | A type-safe union: holds exactly one of the listed types and knows which |
std::any | Holds a value of any copyable type (type checked at run time) |
std::string_view | A cheap, non-owning view of characters (pointer + length): no copying |
if constexpr | Compile-time branch inside templates; the false branch is discarded for that instantiation |
| CTAD | Class template argument deduction: std::pair p{3, 4.5}; (see Templates) |
| Fold expressions | (args + ...) for variadic templates (see Templates) |
inline variables | A variable defined in a header without multiple-definition errors |
| Nested namespaces | namespace a::b { } (see Namespaces) |
std::filesystem | Paths, directories, file sizes (see File Handling) |
| Parallel algorithms | std::sort(std::execution::par, ...) (with GCC, real parallelism needs Intel TBB linked with -ltbb) |
| Guaranteed copy elision | Returning a prvalue like return T{...}; creates the object directly in place — no copy or move |
Three precision points worth remembering:
*opton an emptyoptionalis undefined behavior;opt.value()throwsstd::bad_optional_accessinstead;value_or(x)gives a default.std::get<std::string>(v)throwsstd::bad_variant_accessif the variant currently holds anint.A
string_viewdoes not own its characters. If the string it points into is destroyed, the view dangles and using it is undefined behavior. Never return astring_viewinto a localstd::string.
Attributes that catch bugs: [[nodiscard]] and [[deprecated]]
[[deprecated("use average() instead")]] // C++14
int oldAverage(int a, int b) { return (a + b) / 2; }
[[nodiscard]] int computeTax(int income) { return income / 10; } // C++17
int main() {
oldAverage(4, 6); // warning: deprecated
computeTax(50000); // warning: result ignored
}attr.cpp:7:15: warning: ‘int oldAverage(int, int)’ is deprecated: use average() instead [-Wdeprecated-declarations]
attr.cpp:8:15: warning: ignoring return value of ‘int computeTax(int)’, declared with attribute ‘nodiscard’ [-Wunused-result]C++17 also added [[maybe_unused]] (silences unused warnings) and [[fallthrough]] (marks an intentional fall-through in a switch, covered in Switch Statement).
C++20: The Big Four and Much More
C++20 is the second giant release. Its "big four" are concepts, ranges, coroutines and modules. Here are the features you will use most:
#include <compare>
#include <concepts>
#include <format>
#include <iostream>
#include <map>
#include <numbers>
#include <ranges>
#include <span>
#include <string>
#include <vector>
struct Version {
int major, minor, patch;
auto operator<=>(const Version&) const = default; // generates ==, !=, <, <=, >, >=
};
struct Config {
std::string host = "localhost";
int port = 80;
bool secure = false;
};
int sum(std::span<const int> data) { // works with arrays, vectors, ...
int total = 0;
for (int x : data) total += x;
return total;
}
template <std::integral T> // concept constrains T
T half(T x) { return x / 2; }
consteval int cube(int n) { return n * n * n; } // MUST run at compile time
int main() {
Version a{1, 4, 2}, b{1, 10, 0};
std::cout << std::boolalpha << (a < b) << ' ' << (a == b) << '\n';
Config c{.port = 443, .secure = true}; // designated initializers
std::cout << c.host << ':' << c.port << ' ' << c.secure << '\n';
int arr[] = {1, 2, 3};
std::vector<int> vec{10, 20, 30, 40};
std::cout << sum(arr) << ' ' << sum(vec) << '\n';
std::cout << half(9) << '\n';
auto bigSquares = vec | std::views::filter([](int x) { return x > 15; })
| std::views::transform([](int x) { return x * x; });
for (int x : bigSquares) std::cout << x << ' ';
std::cout << '\n';
std::cout << std::format("{:>8}|{:<6}|{:.3f}\n", "right", "left", std::numbers::pi);
std::map<std::string, int> stock{{"pen", 5}};
std::cout << stock.contains("pen") << ' ' << std::string("index.html").ends_with(".html") << '\n';
constexpr int k = cube(3);
std::cout << k << '\n';
}Output:
true false
localhost:443 true
6 100
4
400 900 1600
right|left |3.142
true true
27| Feature (C++20) | What it does |
|---|---|
Three-way comparison <=> | The "spaceship operator". Defaulting it gives all six comparisons (== too, because a defaulted <=> implicitly declares a defaulted ==), compared member by member in declaration order |
| Designated initializers | Config{.port = 443}; members must be named in declaration order, others get their defaults |
std::span<T> | Non-owning view of a contiguous sequence (array, vector, ...): pointer + size in one parameter |
| Concepts | template <std::integral T> — named requirements with readable errors (see Templates) |
| Ranges and views | Algorithms on whole containers (std::ranges::sort(v)) and lazy, composable views joined with | |
std::format | Python-style, type-safe formatting with {} placeholders |
consteval / constinit | Function must run at compile time / variable must be initialized at compile time |
contains, starts_with, ends_with | map.contains(k); str.starts_with("http") |
<numbers> | Mathematical constants: std::numbers::pi, e, sqrt2 |
<bit> | std::popcount, std::bit_width, std::has_single_bit |
using enum | Bring a scoped enum's enumerators into scope (see Namespaces) |
| Abbreviated templates | void f(auto x) is a function template |
Views are lazy
In the program, vec | views::filter(...) | views::transform(...) does no work when it is created. It is a recipe. Elements are filtered and squared one at a time only as the for loop asks for them, and no temporary vector is built. Two consequences: a view must not outlive the container it looks at (it only refers to it), and a view is cheap to create and copy.
consteval really means compile time
consteval int cube(int n) { return n * n * n; }
int main(int argc, char**) {
return cube(argc); // argc is known only at run time
}ce.cpp:3:16: error: call to consteval function ‘cube(argc)’ is not a constant expression
ce.cpp:3:17: error: ‘argc’ is not a constant expressionCompare: a constexpr function may run at compile time but silently runs at run time when given run-time arguments; a consteval function (an "immediate function") must produce a compile-time constant at every call.
Coroutines and modules in one paragraph each
Coroutines are functions that can suspend and later resume, using the keywords co_await, co_yield and co_return. C++20 provides only the low-level machinery; C++23 added the first ready-made coroutine type, std::generator, for lazily producing sequences. They are mainly used for asynchronous I/O and generators.
Modules replace textual #include with import: a module is compiled once, does not leak macros, and is not affected by the order of includes, which can speed up builds dramatically. C++23 adds import std; for the whole standard library. Compiler and build-system support is still maturing (GCC needs the -fmodules flag), so most code you meet today still uses headers.
C++23: Completing the Picture
C++23 fills gaps left by C++20. Many students love it for one reason: finally, a simple print.
#include <expected>
#include <print>
#include <ranges>
#include <string>
#include <utility>
#include <vector>
std::expected<int, std::string> parseAge(const std::string& s) {
if (s.empty()) return std::unexpected("empty input");
int value = 0;
for (char ch : s) {
if (ch < '0' || ch > '9') return std::unexpected("not a number: " + s);
value = value * 10 + (ch - '0');
}
return value;
}
class Grid {
std::vector<int> cells;
int cols;
public:
Grid(int r, int c) : cells(r * c, 0), cols{c} {}
int& operator[](int r, int c) { return cells[r * cols + c]; } // multidimensional subscript
};
struct Counter {
int n = 0;
auto& increment(this Counter& self) { ++self.n; return self; } // deducing this
};
enum class Day : int { Mon = 1, Tue, Wed };
int main() {
std::println("Hello, {}! C++{} is here.", "student", 23);
for (std::string in : {"21", "abc", ""}) {
auto r = parseAge(in);
if (r) std::println("age = {}", *r);
else std::println("error: {}", r.error());
}
Grid g(2, 3);
g[1, 2] = 7;
std::println("g[1, 2] = {}", g[1, 2]);
Counter c;
c.increment().increment().increment();
std::println("counter = {}", c.n);
auto squares = std::views::iota(1, 6)
| std::views::transform([](int x) { return x * x; })
| std::ranges::to<std::vector>(); // range -> container
std::println("{}", squares); // ranges are formattable
std::vector<std::string> names{"Asha", "Ravi", "Meena"};
for (auto [i, name] : std::views::enumerate(names))
std::println("{}: {}", i, name);
std::string msg = "I love C++";
std::println("{} {}", msg.contains("love"), std::to_underlying(Day::Wed));
}Output:
Hello, student! C++23 is here.
age = 21
error: not a number: abc
error: empty input
g[1, 2] = 7
counter = 3
[1, 4, 9, 16, 25]
0: Asha
1: Ravi
2: Meena
true 3| Feature (C++23) | What it does |
|---|---|
std::print / std::println | Formatted output with std::format syntax; println adds a newline. Header <print> |
std::expected<T, E> | Holds either a result T or an error E; error handling without exceptions (compare Exception Handling) |
| Multidimensional subscript | operator[] may take several arguments: g[1, 2] |
Deducing this | Explicit object parameter this Counter& self; one function can replace const/non-const overload pairs and enables recursive lambdas |
std::ranges::to | Turns a range or view into a real container |
| New views | views::enumerate, views::zip, views::chunk, views::slide, views::stride, views::cartesian_product |
| Formatting ranges | std::println("{}", vec) prints [1, 4, 9] |
string::contains | s.contains("love") |
std::to_underlying | Converts a scoped enum to its underlying integer type |
std::flat_map, std::flat_set | Associative containers stored in sorted contiguous arrays: cache-friendly lookups (still O(log n)) and fast iteration, but O(n) insertion and erasure |
std::mdspan | Multidimensional view over contiguous data (not yet in GCC 15's library) |
if consteval, std::unreachable(), uz literal suffix | Smaller utilities |
import std; | The standard library as a module |
A note on std::expected: *r on an object that holds an error is undefined behavior, just like *opt on an empty optional. Always test it first (as the program does) or use r.value(), which throws std::bad_expected_access.
Library support differs between compilers: GCC 14 was the first GCC to ship <print>, and GCC 15 still has no <mdspan>, for example. If a feature is missing, check your compiler version and the support tables on cppreference.
And Next: C++26
The committee completed the technical work on C++26 in March 2026; formal ISO publication follows the approval ballot. Its headline features include static reflection (programs that inspect their own types at compile time), contracts (pre, post and contract_assert), std::execution (a standard framework for asynchronous and parallel work), #embed for including binary files, pack indexing, std::inplace_vector, and = delete("reason"). Compilers are implementing these gradually; GCC 15 accepts -std=c++26 with only part of the features available. For university exams and interviews in 2026, C++17/20 knowledge plus awareness of C++23 is what is expected.
Cheat Sheet: Old Style vs Modern Style
| Task | Old style (C++98) | Modern style | Since |
|---|---|---|---|
| Null pointer | NULL or 0 | nullptr | C++11 |
| Loop over a container | Index or explicit iterator | for (const auto& x : v) | C++11 |
| Own a heap object | new / delete | std::make_unique | C++14 |
| Type alias | typedef | using | C++11 |
| Enumeration | enum | enum class | C++11 |
| Compile-time constant | #define | constexpr | C++11 |
| Unpack a pair | p.first, p.second | auto [a, b] = p; | C++17 |
| "Maybe a value" | Magic value -1 or pointer | std::optional | C++17 |
| Read-only string parameter | const std::string& / const char* | std::string_view | C++17 |
| Array parameter | int* arr, int n | std::span<int> | C++20 |
| Key exists in map? | m.find(k) != m.end() | m.contains(k) | C++20 |
| Comparisons for a struct | Write 6 operators | auto operator<=>(...) const = default; | C++20 |
| Formatted output | printf / iomanip | std::format / std::println | C++20 / C++23 |
| Result or error | Error codes / exceptions | std::expected | C++23 |
Common Mistakes
Assuming the newest standard is the default — GCC 15 compiles as gnu++17 unless you pass
-std=c++20or-std=c++23.auto x = {1};— this is astd::initializer_list<int>, not anint. (auto x{1};isintsince C++17.)for (auto x : bigObjects)copies every element; useconst auto&to read andauto&to modify.Dereferencing an empty
optionalor an error-holdingexpected— undefined behavior; check first or use.value().Dangling
string_view,spanor views — they do not own data; the owner must outlive them.Expecting
constexprto force compile-time evaluation — it only allows it; useconstevalor assign the result to aconstexprvariable.Designated initializers out of order —
Config{.secure = true, .port = 443}is an error in C++ (unlike C).Overusing
auto—auto n = v.size() - 1;is unsigned and wraps around whenvis empty; know the deduced type.
Interview / GATE-Style Questions
Q1. Why was nullptr introduced when NULL already existed?
NULL is an integer constant (typically 0 or 0L), so in f(NULL) with overloads f(int) and f(char*) the int version may be chosen or the call may be ambiguous. nullptr has its own type std::nullptr_t, converts to any pointer type but not to integers, so the pointer overload is chosen.
Q2. What is the difference between constexpr, consteval and constinit?
constexpr (C++11) function: can be evaluated at compile time if the arguments are constants, otherwise runs at run time; constexpr variable: a compile-time constant. consteval (C++20): every call must be evaluated at compile time. constinit (C++20): a static-storage variable must be initialized at compile time, but it is not const and can change later.
Q3. What does auto operator<=>(const T&) const = default; give you?
All six relational operators. The defaulted three-way comparison compares base classes and then members in declaration order (lexicographically), and a defaulted <=> also implicitly declares a defaulted operator==; !=, <, <=, >, >= are rewritten in terms of == and <=>.
Q4. When would you use std::optional, std::variant and std::expected?
optional<T>: a value may be absent with no reason needed (lookup that may fail). variant<A, B, ...>: the value is exactly one of several types (a token that is a number or a name). expected<T, E> (C++23): an operation returns a result or an explanation of why it failed.
Q5. What is printed? auto v = std::views::iota(1, 5) | std::views::transform([](int x){ return x * 10; }); then for (int x : v) std::cout << x << ' ';
10 20 30 40. iota(1, 5) produces 1, 2, 3, 4 (the end is excluded), and the view multiplies each element lazily as the loop requests it.
Q6. Which standard introduced: structured bindings, generic lambdas, concepts, std::print, enum class?
Structured bindings — C++17; generic lambdas — C++14; concepts — C++20; std::print — C++23; enum class — C++11.
Q7. Why is std::string_view faster than const std::string& for parameters, and what is the risk?
Passing a string literal or a substring to const std::string& may construct a temporary std::string (a heap allocation for long text). A string_view is just a pointer and length, so it never allocates. The risk is lifetime: it does not own the characters, so storing or returning it after the underlying string is gone leaves it dangling.
Summary
C++ is standardized by ISO every three years; choose the standard with
-std=c++XXand check__cplusplus.C++11:
auto, range-for,nullptr, brace initialization,enum class,constexpr,override/final,= default/= delete, lambdas, move semantics, smart pointers, threads.C++14: generic lambdas, return type deduction, relaxed
constexpr,make_unique, digit separators.C++17: structured bindings,
ifwith initializer,if constexpr,optional,variant,string_view, CTAD, fold expressions, filesystem,[[nodiscard]].C++20: concepts, ranges, coroutines, modules,
<=>, designated initializers,span,format,consteval.C++23:
print/println,expected, deducingthis, multidimensional[],ranges::to, new views,import std.C++26 (technically complete since March 2026) brings reflection, contracts and
std::execution.Non-owning types (
string_view,span, views) are fast but must never outlive the data they refer to.