General utilities library
A guide to Clause 22: what <utility>, pair, tuple, optional, variant, any, expected, bitset, <functional> and <bit> are each for, plus the Constraints, Mandates, Preconditions and Hardened preconditions elements you need to recognize before reading the wording.
Key points
- Clause 22 collects small components that almost every program uses but that are not containers, algorithms or I/O. Many of them are also building blocks for the rest of the library, such as
std::move,std::pairandstd::invoke. optional,variant,anyandexpectedall hold a value that may be of different kinds in a single object. The first two andexpectednever allocate, and their special member functions are conditionally trivial depending on the element types.- Library function specifications are split into fixed elements: if Constraints are not met, the function drops out of overload resolution; if Mandates are violated, compilation fails; violating Preconditions is undefined behavior.
- C++26 turned unchecked accesses such as
optional::operator*into Hardened preconditions: in a hardened implementation a violation terminates the program; in other implementations it is still undefined behavior.
Map of the clause [utilities.general]#
¶1 This Clause describes utilities that are generally useful in C++ programs; some of these utilities are used by other elements of the C++ standard library.
| Section | Subclause | Header | Contents |
|---|---|---|---|
| 22.2 | [utility] | <utility> |
swap, exchange, move, forward, declval, safe integer comparisons cmp_less etc., to_underlying, unreachable; C++26 constant_wrapper ([const.wrap.class]) |
| 22.3 | [pairs] | <utility> |
pair |
| 22.4 | [tuple] | <tuple> |
tuple, apply, make_from_tuple |
| 22.5 | [optional] | <optional> |
possibly empty value optional<T>; C++26 optional<T&> |
| 22.6 | [variant] | <variant> |
type-safe union variant, visit |
| 22.7 | [any] | <any> |
any, which can hold any copyable type |
| 22.8 | [expected] | <expected> |
C++23 value or error expected<T, E> |
| 22.9 | [bitset] | <bitset> |
fixed-size bit sets |
| 22.10 | [function.objects] | <functional> |
INVOKE, reference_wrapper, bind_front, function, move_only_function, function_ref, hash, etc. |
| 22.11 | [bit] | <bit> |
bit_cast, byteswap, powers of 2, rotations, bit counting |
| 22.12 | [stdbit.h.syn] | <stdbit.h> |
C++26 the C23 bit manipulation header |
Content that has moved
In C++17 and C++20, [utilities] also contained smart pointers and memory utilities, <type_traits>, <ratio>, <charconv>, <format>, execution policies, type_index and so on (C++17 also had <chrono>). They are now spread elsewhere: memory is in [mem], type traits and <ratio> in [meta], <charconv> and <format> in [text], execution policies in [execpol], type_index in [type.index], and the time library in [time]. Keep this in mind when citing subclause numbers from older standards.
Four vocabulary types#
optional, variant, any and expected are often called vocabulary types: when different libraries use the same type to express the same thing, their interfaces fit together. Their design trade-offs can be compared in one table:
optional<T> |
variant<Ts...> |
any |
expected<T, E> |
|
|---|---|---|---|---|
| Holds | a T, or nothing |
exactly one of Ts |
any copyable type | a T, or an error E |
| Storage | inside the object | inside the object | possibly on the heap (the standard encourages avoiding allocation for small objects) | inside the object |
| Empty state | nullopt, a normal state |
valueless_by_exception(), arises only from exceptions |
an empty any, a normal state |
none: always holds a value or an error |
| Accessing the wrong thing | operator* violates a hardened precondition; value() throws bad_optional_access |
get throws bad_variant_access; get_if returns a null pointer |
any_cast throws bad_any_cast or returns a null pointer |
operator* violates a hardened precondition; value() throws bad_expected_access<E> |
| Triviality | special members conditionally trivial depending on T |
depending on all Ts |
not trivial | depending on T and E |
The last row deserves a closer look:
#include <optional>
#include <string>
#include <type_traits>
static_assert( std::is_trivially_copyable_v<std::optional<int>>);
static_assert(!std::is_trivially_copyable_v<std::optional<std::string>>);
int main() {}optional<int> can be copied with memcpy and passed in registers just like int; optional<string> cannot. For a class template to achieve this, it needs language support on two fronts: a union's special member is not deleted only when the corresponding function of every variant member is trivial ([class.union]); and since C++20 a class can declare several prospective destructors (and other special members) with different constraints, and the constraints select one of them ([class.dtor], [special]). See [optional.optional] and [variant.variant] for the details, and [class.prop] for why triviality matters.
Elements to recognize before reading library wording#
Every function in the library wording is written using the elements specified by [structure.specifications]/3. Violating different elements has completely different consequences:
| Element | When not satisfied |
|---|---|
| Constraints | the function does not participate in overload resolution; no error, and it can be detected by a requires expression |
| Mandates | the program is ill-formed and the compiler must diagnose it |
| Constant When | this call is not a constant subexpression |
| Preconditions | undefined behavior |
| Hardened preconditions | a hardened implementation checks the condition before the function has any other observable side effects and terminates on failure; in other implementations it is undefined behavior |
#include <variant>
int main() {
std::variant<int, int> v{std::in_place_index<0>, 1};
return std::get<int>(v); // error: int appears twice in Ts, violating Mandates
}std::get<T>(variant) requires T to occur exactly once in Ts.... This is a Mandates element: violating it fails compilation outright, and the compiler does not fall back to another overload. Getting by index with std::get<0>(v) has no such problem. Conversely, the converting constructor of optional<T> uses Constraints: when the condition is not met, the constructor simply drops out of overload resolution, and is_constructible_v<optional<int>, std::string> quietly yields false. This distinction is what decides whether a library interface can be used in concept checks.
Hardened preconditions C++26#
#include <optional>
int main() {
std::optional<int> o;
return *o; // violates a hardened precondition: has_value() is false
}Unchecked accessors such as optional::operator*, expected::operator-> and bitset::operator[] used to have ordinary preconditions, and violating them was undefined behavior. C++26 changed them to hardened preconditions: the same code, run against a hardened standard library, terminates deterministically at this point. In our tests, compiling the program above against libc++ with -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST makes it terminate at run time with SIGTRAP; without that macro there is no check at all. See [intro.compliance] for which implementations count as hardened.
Another common phrase is Equivalent to: when Effects says a function is equivalent to some code, the semantics of that code (which functions it calls, which exceptions it throws, whether it can be used in constant evaluation) are the semantics of the function ([structure.specifications]/4). std::apply, optional::value_or, expected's and_then and others are all defined this way.
Suggested reading order#
- [utility]:
move,forwardanddeclvalare the basic vocabulary for reading the rest of the wording. - [func.require]: the definition of INVOKE, on which
apply,visit,functionandoptional::and_thenare all built. - [pairs] and [tuple]: the tuple-like protocol and its relationship to structured bindings ([dcl.struct.bind]).
- [optional.optional], [variant.variant], [expected.expected]: the same conditional-triviality technique used three times; [any] is the type-erased contrast.
- [func.wrap]: the trade-offs among the four polymorphic function wrappers.
- [bit]:
bit_castis the standard, legal way to reinterpret an object representation; read it alongside the aliasing rules in [basic.lval].
Questions#
Question
Is std::optional<int> trivially copyable? Where does the standard guarantee this?
Answer
Yes. [optional.ctor] specifies that if is_trivially_copy_constructible_v<T> is true, the copy constructor is trivial; the move constructor, copy assignment, move assignment and destructor ([optional.dtor]) all have similar provisions. int satisfies all of the conditions, so optional<int> meets the definition of a trivially copyable class in [class.prop]. The copy constructor and destructor of std::string are not trivial, so optional<std::string> is not trivially copyable.
Contents
- 22.1General[utilities.general]
- 22.2Utility components[utility]done
- 22.2.1Header <utility> synopsis[utility.syn]
- 22.2.2swap[utility.swap]
- 22.2.3exchange[utility.exchange]
- 22.2.4Forward/move helpers[forward]
- 22.2.5Function template as_const[utility.as.const]
- 22.2.6Function template declval[declval]
- 22.2.7Integer comparison functions[utility.intcmp]
- 22.2.8Function template to_underlying[utility.underlying]
- 22.2.9Undefined behavior[utility.undefined]
- 22.2.10Class template constant_wrapper[const.wrap.class]done
- 22.3Pairs[pairs]done
- 22.4Tuples[tuple]done
- 22.4.1General[tuple.general]
- 22.4.2Header <tuple> synopsis[tuple.syn]
- 22.4.3Concept tuple-like[tuple.like]
- 22.4.4Class template tuple[tuple.tuple]
- 22.4.5Tuple creation functions[tuple.creation]
- 22.4.6Calling a function with a tuple of arguments[tuple.apply]
- 22.4.7Tuple helper classes[tuple.helper]
- 22.4.8Element access[tuple.elem]
- 22.4.9Relational operators[tuple.rel]
- 22.4.10common_reference related specializations[tuple.common.ref]
- 22.4.11Tuple traits[tuple.traits]
- 22.4.12Tuple specialized algorithms[tuple.special]
- 22.5Optional objects[optional]done
- 22.5.1General[optional.general]
- 22.5.2Header <optional> synopsis[optional.syn]
- 22.5.3Class template optional[optional.optional]draft
- 22.5.3.1General[optional.optional.general]
- 22.5.3.2Constructors[optional.ctor]
- 22.5.3.3Destructor[optional.dtor]
- 22.5.3.4Assignment[optional.assign]
- 22.5.3.5Swap[optional.swap]
- 22.5.3.6Iterator support[optional.iterators]
- 22.5.3.7Observers[optional.observe]
- 22.5.3.8Monadic operations[optional.monadic]
- 22.5.3.9Modifiers[optional.mod]
- 22.5.4Partial specialization of optional for reference types[optional.optional.ref]draft
- 22.5.4.1General[optional.optional.ref.general]
- 22.5.4.2Constructors[optional.ref.ctor]
- 22.5.4.3Assignment[optional.ref.assign]
- 22.5.4.4Swap[optional.ref.swap]
- 22.5.4.5Iterator support[optional.ref.iterators]
- 22.5.4.6Observers[optional.ref.observe]
- 22.5.4.7Monadic operations[optional.ref.monadic]
- 22.5.4.8Modifiers[optional.ref.mod]
- 22.5.4.9Exposition only helper functions[optional.ref.expos]
- 22.5.5No-value state indicator[optional.nullopt]
- 22.5.6Class bad_optional_access[optional.bad.access]
- 22.5.7Relational operators[optional.relops]
- 22.5.8Comparison with nullopt[optional.nullops]
- 22.5.9Comparison with T[optional.comp.with.t]
- 22.5.10Specialized algorithms[optional.specalg]
- 22.5.11Hash support[optional.hash]
- 22.6Variants[variant]done
- 22.6.1General[variant.general]
- 22.6.2Header <variant> synopsis[variant.syn]
- 22.6.3Class template variant[variant.variant]done
- 22.6.4variant helper classes[variant.helper]
- 22.6.5Value access[variant.get]
- 22.6.6Relational operators[variant.relops]
- 22.6.7Visitation[variant.visit]done
- 22.6.8Class monostate[variant.monostate]
- 22.6.9monostate relational operators[variant.monostate.relops]
- 22.6.10Specialized algorithms[variant.specalg]
- 22.6.11Class bad_variant_access[variant.bad.access]
- 22.6.12Hash support[variant.hash]
- 22.7Storage for any type[any]done
- 22.8Expected objects[expected]draft
- 22.8.1General[expected.general]
- 22.8.2Header <expected> synopsis[expected.syn]
- 22.8.3Class template unexpected[expected.unexpected]
- 22.8.4Class template bad_expected_access[expected.bad]
- 22.8.5Class template specialization bad_expected_access<void>[expected.bad.void]
- 22.8.6Class template expected[expected.expected]draft
- 22.8.6.1General[expected.object.general]
- 22.8.6.2Constructors[expected.object.cons]
- 22.8.6.3Destructor[expected.object.dtor]
- 22.8.6.4Assignment[expected.object.assign]
- 22.8.6.5Swap[expected.object.swap]
- 22.8.6.6Observers[expected.object.obs]
- 22.8.6.7Monadic operations[expected.object.monadic]
- 22.8.6.8Equality operators[expected.object.eq]
- 22.8.7Partial specialization of expected for void types[expected.void]draft
- 22.8.7.1General[expected.void.general]
- 22.8.7.2Constructors[expected.void.cons]
- 22.8.7.3Destructor[expected.void.dtor]
- 22.8.7.4Assignment[expected.void.assign]
- 22.8.7.5Swap[expected.void.swap]
- 22.8.7.6Observers[expected.void.obs]
- 22.8.7.7Monadic operations[expected.void.monadic]
- 22.8.7.8Equality operators[expected.void.eq]
- 22.9Bitsets[bitset]draft
- 22.10Function objects[function.objects]done
- 22.10.1General[function.objects.general]
- 22.10.2Header <functional> synopsis[functional.syn]
- 22.10.3Definitions[func.def]
- 22.10.4Requirements[func.require]done
- 22.10.5invoke functions[func.invoke]
- 22.10.6Class template reference_wrapper[refwrap]done
- 22.10.6.1General[refwrap.general]
- 22.10.6.2Constructors[refwrap.const]
- 22.10.6.3Assignment[refwrap.assign]
- 22.10.6.4Access[refwrap.access]
- 22.10.6.5Invocation[refwrap.invoke]
- 22.10.6.6Comparisons[refwrap.comparisons]
- 22.10.6.7Helper functions[refwrap.helpers]
- 22.10.6.8common_reference related specializations[refwrap.common.ref]
- 22.10.7Arithmetic operations[arithmetic.operations]
- 22.10.7.1General[arithmetic.operations.general]
- 22.10.7.2Class template plus[arithmetic.operations.plus]
- 22.10.7.3Class template minus[arithmetic.operations.minus]
- 22.10.7.4Class template multiplies[arithmetic.operations.multiplies]
- 22.10.7.5Class template divides[arithmetic.operations.divides]
- 22.10.7.6Class template modulus[arithmetic.operations.modulus]
- 22.10.7.7Class template negate[arithmetic.operations.negate]
- 22.10.8Comparisons[comparisons]
- 22.10.8.1General[comparisons.general]
- 22.10.8.2Class template equal_to[comparisons.equal.to]
- 22.10.8.3Class template not_equal_to[comparisons.not.equal.to]
- 22.10.8.4Class template greater[comparisons.greater]
- 22.10.8.5Class template less[comparisons.less]
- 22.10.8.6Class template greater_equal[comparisons.greater.equal]
- 22.10.8.7Class template less_equal[comparisons.less.equal]
- 22.10.8.8Class compare_three_way[comparisons.three.way]
- 22.10.9Concept-constrained comparisons[range.cmp]
- 22.10.10Logical operations[logical.operations]
- 22.10.11Bitwise operations[bitwise.operations]
- 22.10.12Class identity[func.identity]
- 22.10.13Function template not_fn[func.not.fn]done
- 22.10.14Function templates bind_front and bind_back[func.bind.partial]done
- 22.10.15Function object binders[func.bind]done
- 22.10.16Function template mem_fn[func.memfn]done
- 22.10.17Polymorphic function wrappers[func.wrap]done
- 22.10.17.1General[func.wrap.general]
- 22.10.17.2Class bad_function_call[func.wrap.badcall]
- 22.10.17.3Class template function[func.wrap.func]done
- 22.10.17.3.1General[func.wrap.func.general]
- 22.10.17.3.2Constructors and destructor[func.wrap.func.con]
- 22.10.17.3.3Modifiers[func.wrap.func.mod]
- 22.10.17.3.4Capacity[func.wrap.func.cap]
- 22.10.17.3.5Invocation[func.wrap.func.inv]
- 22.10.17.3.6Target access[func.wrap.func.targ]
- 22.10.17.3.7Null pointer comparison operator functions[func.wrap.func.nullptr]
- 22.10.17.3.8Specialized algorithms[func.wrap.func.alg]
- 22.10.17.4Move-only wrapper[func.wrap.move]draft
- 22.10.17.5Copyable wrapper[func.wrap.copy]draft
- 22.10.17.6Non-owning wrapper[func.wrap.ref]draft
- 22.10.18Searchers[func.search]done
- 22.10.19Class template hash[unord.hash]done
- 22.11Bit manipulation[bit]draft
- 22.11.1General[bit.general]
- 22.11.2Header <bit> synopsis[bit.syn]
- 22.11.3Function template bit_cast[bit.cast]
- 22.11.4byteswap[bit.byteswap]
- 22.11.5Integral powers of 2[bit.pow.two]
- 22.11.6Shifting[bit.shift]
- 22.11.7Rotating[bit.rotate]
- 22.11.8Counting[bit.count]
- 22.11.9Permutation[bit.permute]
- 22.11.10Endian[bit.endian]
- 22.12Header <stdbit.h> synopsis[stdbit.h.syn]draft