code
stringlengths
2.5k
150k
kind
stringclasses
1 value
cpp Comparison operators Comparison operators ==================== Compares the arguments. | Operator name | Syntax | [Over​load​able](operators "cpp/language/operators") | Prototype examples (for `class T`) | | --- | --- | --- | --- | | As member function | As free (namespace) function | | equal to | `a == b` | Yes | `bool T::operator ==(const T2 &b) const;` | `bool operator ==(const T &a, const T2 &b);` | | not equal to | `a != b` | Yes | `bool T::operator !=(const T2 &b) const;` | `bool operator !=(const T &a, const T2 &b);` | | less than | `a < b` | Yes | `bool T::operator <(const T2 &b) const;` | `bool operator <(const T &a, const T2 &b);` | | greater than | `a > b` | Yes | `bool T::operator >(const T2 &b) const;` | `bool operator >(const T &a, const T2 &b);` | | less than or equal to | `a <= b` | Yes | `bool T::operator <=(const T2 &b) const;` | `bool operator <=(const T &a, const T2 &b);` | | greater than or equal to | `a >= b` | Yes | `bool T::operator >=(const T2 &b) const;` | `bool operator >=(const T &a, const T2 &b);` | | three-way comparison (C++20) | `a <=> b` | Yes | `/*R*/ T::operator <=>(const T2 &b) const;` | `/*R*/ operator <=>(const T &a, const T2 &b);` | | **Notes*** Where built-in operators return `bool`, most [user-defined overloads](operators "cpp/language/operators") also return `bool` so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including `void`). * `T2` can be any type including `T`. * `/*R*/` is the return type of `operator <=>` ([see below](#Three-way_comparison)). | ### Two-way comparison The two-way comparison operator expressions have the form. | | | | | --- | --- | --- | | lhs `<` rhs | (1) | | | lhs `>` rhs | (2) | | | lhs `<=` rhs | (3) | | | lhs `>=` rhs | (4) | | | lhs `==` rhs | (5) | | | lhs `!=` rhs | (6) | | 1) Returns `true` if lhs is less than rhs, `false` otherwise. 2) Returns `true` if lhs is greater than rhs, `false` otherwise. 3) Returns `true` if lhs is less than or equal to rhs, `false` otherwise. 4) Returns `true` if lhs is greater than or equal to rhs, `false` otherwise. 5) Returns `true` if lhs is equal to rhs, `false` otherwise. 6) Returns `true` if lhs is not equal to rhs, `false` otherwise. In all cases, for the built-in operators, lhs and rhs must have either. * arithmetic or enumeration type (see arithmetic comparison operators below) * pointer type (see pointer comparison operators below) after the application of the [lvalue-to-rvalue](implicit_conversion#Lvalue_to_rvalue_conversion "cpp/language/implicit conversion"), [array-to-pointer](implicit_conversion#Array_to_pointer_conversion "cpp/language/implicit conversion") and [function-to-pointer](implicit_conversion#Function_to_pointer "cpp/language/implicit conversion") standard conversions. The comparison is deprecated if both operands have array type prior to the application of these conversions. (since C++20). In any case, the result is a `bool` prvalue. #### Arithmetic comparison operators If the operands have arithmetic or enumeration type (scoped or unscoped), *usual arithmetic conversions* are performed on both operands following the rules for [arithmetic operators](operator_arithmetic "cpp/language/operator arithmetic"). The values are compared after conversions: ##### Example ``` #include <iostream> int main() { std::cout << std::boolalpha; int n = -1; int n2 = 1; std::cout << " -1 == 1? " << (n == n2) << '\n' << "Comparing two signed values:\n" << " -1 < 1? " << (n < n2) << '\n' << " -1 > 1? " << (n > n2) << '\n'; unsigned int u = 1; std::cout << "Comparing signed and unsigned:\n" << " -1 < 1? " << (n < u) << '\n' << " -1 > 1? " << (n > u) << '\n'; static_assert(sizeof(unsigned char) < sizeof(int), "Can't compare signed and smaller unsigned properly"); unsigned char uc = 1; std::cout << "Comparing signed and smaller unsigned:\n" << " -1 < 1? " << (n < uc) << '\n' << " -1 > 1? " << (n > uc) << '\n'; } ``` Output: ``` -1 == 1? false Comparing two signed values: -1 < 1? true -1 > 1? false Comparing signed and unsigned: -1 < 1? false -1 > 1? true Comparing signed and smaller unsigned: -1 < 1? true -1 > 1? false ``` #### Pointer comparison operators Comparison operators can be used to compare two pointers. Only equality operators (`operator==` and `operator!=`) can be used to compare the following pointer pairs: * two pointers-to-members * a null pointer constant with a pointer or a pointer-to-member | | | | --- | --- | | * a `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` value with a null pointer constant (which can also be a `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` value) | (since C++11) | First, [pointer conversions](implicit_conversion "cpp/language/implicit conversion") (pointer to member conversions if the arguments are pointers to members), function pointer conversions, (since C++17) and [qualification conversions](implicit_conversion "cpp/language/implicit conversion") are applied to both operands to obtain the *composite pointer type*, as follows. | | | | --- | --- | | 1) If both operands are null pointer constants, the composite pointer type is `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` | (since C++11) | 2) If one operand is a null pointer constant, and the other is a pointer, the composite type is exactly the pointer type 3) If the operands are * a pointer to *cv1* `void`, and * a pointer to *cv2* `T`, where `T` is an object type or `void`, the composite type is "pointer to *cv12* `void`", where *cv12* is the union of *cv1* and *cv2* 4) If the types of the operands are * `P1`, a pointer to (possibly cv-qualified) `T1`, and * `P2`, a pointer to (possibly cv-qualified) `T2`, and if `T1` is the same as `T2` or is a base class of `T2`, then the composite pointer type is the *cv-combined* type of `P1` and `P2`. Otherwise, if `T2` is a base class of `T1`, then the composite pointer type is the *cv-combined* type of `P2` and `P1`. 5) If the types of the operands are * `MP1`, pointer to member of `T1` of type (possibly cv-qualified) `U1`, and * `MP2`, pointer to member of `T2` of type (possibly cv-qualified) `U2`, and if `T1` is the same as or derived from `T2`, then the composite pointer type is the *cv-combined* type of `MP1` and `MP2`. Otherwise, if `T2` is derived from `T1`, then the composite pointer type is the cv-combined type of `MP2` and `MP1`. 6) If the types of the operands `P1` and `P2` are multi-level mixed pointer and pointer to member types with the same number of levels that only differ by cv-qualifications at any of the levels, the composite pointer type is the cv-combined type of `P1` and `P2`. In the definition above, *cv-combined* type of two pointer types `P1` and `P2` is a type `P3` that has the same number of levels and type at every level as `P1`, except that cv-qualifications at every level are set as follows: a) at every level other than top level, the union of the cv-qualifications of `P1` and `P2` at that level b) if the resulting cv-qualification at any level is different from `P1`'s or `P2`'s cv-qualification at the same level, then `const` is added to every level between the top level and this one. For example, the composite pointer type of `void*` and `const int*` is `const void*`. The composite pointer type of `int**` and `const int**` is `const int* const*`. Note that until [resolution of CWG1512](https://wg21.link/n3624), `int**` and `const int**` could not be compared. | | | | --- | --- | | In addition to the above, the composite pointer type between pointer to function and pointer to noexcept function (as long as the function type is the same) is pointer to function. | (since C++17) | Note that this implies that any pointer can be compared with `void*`. The result of comparing two pointers to objects (after conversions) is defined as follows: 1) If two pointers point to different elements of the same array, or to subobjects within different elements of the same array, the pointer to the element with the higher subscript *compares greater*. In other words, the results of comparing the pointers is the same as the result of comparing the indexes of the elements they point to. 2) If one pointer points to an element of an array, or to a subobject of the element of the array, and another pointer points one past the last element of the array, the latter pointer *compares greater*. Pointers to non-array objects are treated as pointers to arrays of one: `&obj+1` compares greater than `&obj`. 3) If, within an object of non-union class type, two pointers point to different [non-zero-sized](attributes/no_unique_address "cpp/language/attributes/no unique address") (since C++20) non-static data members with the same [member access](access "cpp/language/access") (until C++23), or to subobjects or array elements of such members, recursively, the pointer to the later declared member *compares greater*. In other words, class members in each of the three member access modes are positioned in memory in order of declaration. The result of equality comparison of two pointers (after conversions) is defined as follows: 1) If the pointers are both null pointer values, they *compare equal* 2) If the pointers are pointers to function and point to the same function, they *compare equal* 3) If the pointers are pointers to object and represent the same address, they *compare equal* (this includes two pointers to non-static members of the same union, pointers to standard-layout struct and to its first member, pointers related by [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast"), etc) 4) All other pointers compare unequal The result of comparing two pointers to members (after conversions) is defined as follows: 1) If both pointers to member are null member pointer values, they *compare equal*. 2) Otherwise, if only one of two pointers to member is the null member pointer value, they compare unequal. 3) Otherwise, if either is a pointer to a virtual member function, the result is unspecified. 4) Otherwise, if one refers to a member of class `C1` and the other refers to a member of a different class `C2`, where neither is a base class of the other, the result is unspecified. ``` struct A {}; struct B : A { int x; }; struct C : A { int x; }; int A::*bx = (int(A::*)) &B::x; int A::*cx = (int(A::*)) &C::x; bool b1 = (bx == cx); // unspecified ``` 5) Otherwise, if both refer to (possibly different) members of the same union, they compare equal. 6) Otherwise, two pointers to member compare equal if and only if they would refer to the same member of the same most derived object or the same subobject if they were dereferenced with a hypothetical object of the associated class type. 7) Otherwise they compare unequal. ``` struct B { int f(); }; struct L : B {}; struct R : B {}; struct D : L, R {}; int (B::*pb)() = &B::f; int (L::*pl)() = pb; int (R::*pr)() = pb; int (D::*pdl)() = pl; int (D::*pdr)() = pr; bool x = (pdl == pdr); // false bool y = (pb == pl); // true ``` If a pointer `p` *compare equal* to pointer `q`, `p<=q` and `p>=q` both yield `true` and `p<q` and `p>q` both yield `false`. If a pointer `p` *compares greater* than a pointer `q`, then `p>=q`, `p>q`, `q<=p`, and `q<p` all yield `true` and `p<=q`, `p<q`, `q>=p`, and `q>p` all yield `false`. If two pointers are not specified to compare greater or compare equal, the result of the comparison is unspecified. An unspecified result may be nondeterministic, and need not be consistent even for multiple evaluations of the same expression with the same operands in the same execution of the program: ``` int x, y; bool f(int* p, int* q) { return p < q; } assert(f(&x, &y) == f(&x, &y)); // may fire in a conforming implementation ``` In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for every pair of promoted arithmetic types `L` and `R`, including enumeration types, the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` bool operator<(L, R); ``` | | | | ``` bool operator>(L, R); ``` | | | | ``` bool operator<=(L, R); ``` | | | | ``` bool operator>=(L, R); ``` | | | | ``` bool operator==(L, R); ``` | | | | ``` bool operator!=(L, R); ``` | | | For every type `P` which is either pointer to object or pointer to function, the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` bool operator<(P, P); ``` | | | | ``` bool operator>(P, P); ``` | | | | ``` bool operator<=(P, P); ``` | | | | ``` bool operator>=(P, P); ``` | | | | ``` bool operator==(P, P); ``` | | | | ``` bool operator!=(P, P); ``` | | | For every type `MP` that is a pointer to member object or pointer to member function or `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")`, the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` bool operator==(MP, MP); ``` | | | | ``` bool operator!=(MP, MP); ``` | | | ##### Example ``` #include <iostream> struct Foo { int n1; int n2; }; union Union { int n; double d; }; int main() { std::cout << std::boolalpha; char a[4] = "abc"; char* p1 = &a[1]; char* p2 = &a[2]; std::cout << "Pointers to array elements:\n" << "p1 == p2? " << (p1 == p2) << '\n' << "p1 < p2? " << (p1 < p2) << '\n'; Foo f; int* p3 = &f.n1; int* p4 = &f.n2; std::cout << "Pointers to members of a class:\n" << "p3 == p4? " << (p3 == p4) << '\n' << "p3 < p4? " << (p3 < p4) << '\n'; Union u; int* p5 = &u.n; double* p6 = &u.d; std::cout << "Pointers to members of a union:\n" << "p5 == (void*)p6? " << (p5 == (void*)p6) << '\n' << "p5 < (void*)p6? " << (p5 < (void*)p6) << '\n'; } ``` Output: ``` Pointers to array elements: p1 == p2? false p1 < p2? true Pointers to members of a class: p3 == p4? false p3 < p4? true Pointers to members of a union: p5 == (void*)p6? true p5 < (void*)p6? false ``` #### Notes Because these operators group left-to-right, the expression `a<b<c` is parsed `(a<b)<c`, and not `a<(b<c)` or `(a<b)&&(b<c)`. ``` #include <iostream> int main() { int a = 3, b = 2, c = 1; std::cout << std::boolalpha << ( a < b < c ) << '\n' // true; maybe warning << ( ( a < b ) < c ) << '\n' // true << ( a < ( b < c ) ) << '\n' // false << ( ( a < b ) && ( b < c ) ) << '\n'; // false } ``` A common requirement for [user-defined operator<](operators#Comparison_operators "cpp/language/operators") is [strict weak ordering](https://en.wikipedia.org/wiki/Strict_weak_ordering "enwiki:Strict weak ordering"). In particular, this is required by the standard algorithms and containers that work with [Compare](../named_req/compare "cpp/named req/Compare") types: `[std::sort](../algorithm/sort "cpp/algorithm/sort")`, `[std::max\_element](../algorithm/max_element "cpp/algorithm/max element")`, `[std::map](../container/map "cpp/container/map")`, etc. Although the results of comparing pointers of random origin (e.g. not all pointing to members of the same array) is unspecified, many implementations provide [strict total ordering](https://en.wikipedia.org/wiki/Total_order#Strict_total_order "enwiki:Total order") of pointers, e.g. if they are implemented as addresses within continuous virtual address space. Those implementations that do not (e.g. where not all bits of the pointer are part of a memory address and have to be ignored for comparison, or an additional calculation is required or otherwise pointer and integer is not a 1 to 1 relationship), provide a specialization of `[std::less](../utility/functional/less "cpp/utility/functional/less")` for pointers that has that guarantee. This makes it possible to use all pointers of random origin as keys in standard associative containers such as `[std::set](../container/set "cpp/container/set")` or `[std::map](../container/map "cpp/container/map")`. For the types that are both [EqualityComparable](../named_req/equalitycomparable "cpp/named req/EqualityComparable") and [LessThanComparable](../named_req/lessthancomparable "cpp/named req/LessThanComparable"), the C++ standard library makes a distinction between *equality*, which is the value of the expression `a == b` and *equivalence*, which is the value of the expression `!(a < b) && !(b < a)`. Comparison between pointers and null pointer constants was removed by the resolution of [CWG issue 583](https://cplusplus.github.io/CWG/issues/583.html) included in [N3624](https://wg21.link/N3624). ``` void f(char* p) { if (p > 0) { /*...*/ } // Error with N3624, compiled before N3624 if (p > nullptr) { /*...*/ } // Error with N3624, compiled before N3624 } int main() {} ``` | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | Three-way comparison The three-way comparison operator expressions have the form. | | | | | --- | --- | --- | | lhs `<=>` rhs | | | The expression returns an object such that.* `(a <=> b) < 0` if `lhs < rhs` * `(a <=> b) > 0` if `lhs > rhs` * `(a <=> b) == 0` if `lhs` and `rhs` are equal/equivalent. If one of the operands is of type `bool` and the other is not, the program is ill-formed. If both operands have arithmetic types, or if one operand has unscoped enumeration type and the other has integral type, the usual arithmetic conversions are applied to the operands, and then.* If a narrowing conversion is required, other than from an integral type to a floating point type, the program is ill-formed. * Otherwise, if the operands have integral type, the operator yields a prvalue of type [`std::strong_ordering`](../utility/compare/strong_ordering "cpp/utility/compare/strong ordering"): + `std::strong_ordering::equal` if both operands are arithmetically equal, + `std::strong_ordering::less` if the first operand is arithmetically less than the second + `std::strong_ordering::greater` otherwise. * Otherwise, the operands have floating-point type, and the operator yields a prvalue of type [`std::partial_ordering`](../utility/compare/partial_ordering "cpp/utility/compare/partial ordering"). The expression `a <=> b` yields + `std::partial_ordering::less` if `a` is less than `b` + `std::partial_ordering::greater` if `a` is greater than `b` + `std::partial_ordering::equivalent` if `a` is equivalent to `b` (`-0 <=> +0` is equivalent) + `std::partial_ordering::unordered` (`NaN <=> anything` is unordered). If both operands have the same enumeration type `E`, the operator yields the result of converting the operands to the underlying type of E and applying `<=>` to the converted operands. If at least one of the operands is a pointer or pointer-to-member, array-to-pointer conversions, derived-to-base pointer conversions, function pointer conversions, and qualification conversions are applied as necessary to convert both operands to the same pointer type, and the resulting pointer type is an object pointer type, `p <=> q` returns a prvalue of type [`std::strong_ordering`](../utility/compare/strong_ordering "cpp/utility/compare/strong ordering"):* `std::strong_ordering::equal` if `p == q`, * `std::strong_ordering::less` if `p < q`, * `std::strong_ordering::greater` if `p > q`. * unspecified result if comparison is unspecified for these pointer values (such as when they do not point into the same object or array). Otherwise, the program is ill-formed. In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for pointer or enumeration type `T`, the following function signature participates in overload resolution: | | | | | --- | --- | --- | | ``` R operator<=>(T, T); ``` | | | Where `R` is the ordering category type defined above. Example ``` #include <compare> #include <iostream> int main() { double foo = -0.0; double bar = 0.0; auto res = foo <=> bar; if (res < 0) std::cout << "-0 is less than 0"; else if (res > 0) std::cout << "-0 is greater than 0"; else if (res == 0) std::cout << "-0 and 0 are equal"; else std::cout << "-0 and 0 are unordered"; } ``` Output: ``` -0 and 0 are equal ``` Notes Three-way comparison can be automatically generated for class types, see [default comparisons](default_comparisons "cpp/language/default comparisons"). If both of the operands are arrays, three-way comparison is ill-formed. ``` unsigned int i = 1; auto r = -1 < i; // existing pitfall: returns ‘false’ auto r2 = -1 <=> i; // Error: narrowing conversion required ``` | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_three_way_comparison`](../feature_test#Library_features "cpp/feature test") | | (since C++20) | ### Standard library Comparison operators are overloaded for many classes in the standard library. | | | | --- | --- | | [operator==operator!=](../types/type_info/operator_cmp "cpp/types/type info/operator cmp") (removed in C++20) | checks whether the objects refer to the same type (public member function of `std::type_info`) | | [operator==operator!=operator<operator<=>](../error/error_code/operator_cmp "cpp/error/error code/operator cmp") (removed in C++20)(removed in C++20)(C++20) | compares two `error_code`s (function) | | [operator==operator!=operator<operator<=>](../error/error_condition/operator_cmp "cpp/error/error condition/operator cmp") (removed in C++20)(removed in C++20)(C++20) | compares `error_condition`s and `error_code`s (function) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../utility/pair/operator_cmp "cpp/utility/pair/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the pair (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../utility/tuple/operator_cmp "cpp/utility/tuple/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the tuple (function template) | | [operator==operator!=](../utility/bitset/operator_cmp "cpp/utility/bitset/operator cmp") (removed in C++20) | compares the contents (public member function of `std::bitset<N>`) | | [operator==operator!=](../memory/allocator/operator_cmp "cpp/memory/allocator/operator cmp") (removed in C++20) | compares two allocator instances (public member function of `std::allocator<T>`) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../memory/unique_ptr/operator_cmp "cpp/memory/unique ptr/operator cmp") (removed in C++20)(C++20) | compares to another `unique_ptr` or with `nullptr` (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../memory/shared_ptr/operator_cmp "cpp/memory/shared ptr/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | compares with another `shared_ptr` or with `nullptr` (function template) | | [operator==operator!=](../utility/functional/function/operator_cmp "cpp/utility/functional/function/operator cmp") (removed in C++20) | compares a `[std::function](../utility/functional/function "cpp/utility/functional/function")` with `nullptr` (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../chrono/duration/operator_cmp "cpp/chrono/duration/operator cmp") (C++11)(C++11)(removed in C++20)(C++11)(C++11)(C++11)(C++11)(C++20) | compares two durations (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../chrono/time_point/operator_cmp "cpp/chrono/time point/operator cmp") (C++11)(C++11)(removed in C++20)(C++11)(C++11)(C++11)(C++11)(C++20) | compares two time points (function template) | | [operator==operator!=](../memory/scoped_allocator_adaptor/operator_cmp "cpp/memory/scoped allocator adaptor/operator cmp") (removed in C++20) | compares two scoped\_allocator\_adaptor instances (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../types/type_index/operator_cmp "cpp/types/type index/operator cmp") (removed in C++20)(C++20) | compares the underlying `[std::type\_info](../types/type_info "cpp/types/type info")` objects (public member function of `std::type_index`) | | [operator==operator!=operator<operator>operator<=operator>=operator<=>](../string/basic_string/operator_cmp "cpp/string/basic string/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares two strings (function template) | | [operator==operator!=](../locale/locale/operator_cmp "cpp/locale/locale/operator cmp") (removed in C++20) | equality comparison between locale objects (public member function of `std::locale`) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/array/operator_cmp "cpp/container/array/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the array (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/deque/operator_cmp "cpp/container/deque/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the deque (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/forward_list/operator_cmp "cpp/container/forward list/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the forward\_list (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/list/operator_cmp "cpp/container/list/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the list (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/vector/operator_cmp "cpp/container/vector/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the vector (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/map/operator_cmp "cpp/container/map/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the map (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/multimap/operator_cmp "cpp/container/multimap/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the multimap (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/set/operator_cmp "cpp/container/set/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the set (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/multiset/operator_cmp "cpp/container/multiset/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | lexicographically compares the values in the multiset (function template) | | [operator==operator!=](../container/unordered_map/operator_cmp "cpp/container/unordered map/operator cmp") (removed in C++20) | compares the values in the unordered\_map (function template) | | [operator==operator!=](../container/unordered_multimap/operator_cmp "cpp/container/unordered multimap/operator cmp") (removed in C++20) | compares the values in the unordered\_multimap (function template) | | [operator==operator!=](../container/unordered_set/operator_cmp "cpp/container/unordered set/operator cmp") (removed in C++20) | compares the values in the unordered\_set (function template) | | [operator==operator!=](../container/unordered_multiset/operator_cmp "cpp/container/unordered multiset/operator cmp") (removed in C++20) | compares the values in the unordered\_multiset (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/queue/operator_cmp "cpp/container/queue/operator cmp") (C++20) | lexicographically compares the values in the queue (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../container/stack/operator_cmp "cpp/container/stack/operator cmp") (C++20) | lexicographically compares the values in the stack (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../iterator/reverse_iterator/operator_cmp "cpp/iterator/reverse iterator/operator cmp") (C++20) | compares the underlying iterators (function template) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../iterator/move_iterator/operator_cmp "cpp/iterator/move iterator/operator cmp") (C++11)(C++11)(removed in C++20)(C++11)(C++11)(C++11)(C++11)(C++20) | compares the underlying iterators (function template) | | [operator==operator!=](../iterator/istream_iterator/operator_cmp "cpp/iterator/istream iterator/operator cmp") (removed in C++20) | compares two `istream_iterator`s (function template) | | [operator==operator!=](../iterator/istreambuf_iterator/operator_cmp "cpp/iterator/istreambuf iterator/operator cmp") (removed in C++20) | compares two `istreambuf_iterator`s (function template) | | [operator==operator!=](../numeric/complex/operator_cmp "cpp/numeric/complex/operator cmp") (removed in C++20) | compares two complex numbers or a complex and a scalar (function template) | | [operator==operator!=operator<operator<=operator>operator>=](../numeric/valarray/operator_cmp "cpp/numeric/valarray/operator cmp") | compares two valarrays or a valarray with a value (function template) | | [operator==operator!=](../numeric/random/linear_congruential_engine/operator_cmp "cpp/numeric/random/linear congruential engine/operator cmp") (C++11)(C++11)(removed in C++20) | compares the internal states of two pseudo-random number engines (function) | | [operator==operator!=](../numeric/random/poisson_distribution/operator_cmp "cpp/numeric/random/poisson distribution/operator cmp") (C++11)(C++11)(removed in C++20) | compares two distribution objects (function) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](../regex/sub_match/operator_cmp "cpp/regex/sub match/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | compares a `sub_match` with another `sub_match`, a string, or a character (function template) | | [operator==operator!=](../regex/match_results/operator_cmp "cpp/regex/match results/operator cmp") (removed in C++20) | lexicographically compares the values in the two match result (function template) | | [operator==operator!=](../regex/regex_iterator/operator_cmp "cpp/regex/regex iterator/operator cmp") (removed in C++20) | compares two `regex_iterator`s (public member function of `std::regex_iterator<BidirIt,CharT,Traits>`) | | [operator==operator!=](../regex/regex_token_iterator/operator_cmp "cpp/regex/regex token iterator/operator cmp") (removed in C++20) | compares two `regex_token_iterator`s (public member function of `std::regex_token_iterator<BidirIt,CharT,Traits>`) | | [operator==operator!=operator< operator<= operator> operator>= operator<=>](../thread/thread/id/operator_cmp "cpp/thread/thread/id/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | compares two `thread::id` objects (function) | The namespace [`std::rel_ops`](../utility/rel_ops/operator_cmp "cpp/utility/rel ops/operator cmp") provides generic operators `!=`, `>`, `<=`, and `>=`: | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | --- | | Defined in namespace `std::rel_ops` | | [operator!=operator>operator<=operator>=](../utility/rel_ops/operator_cmp "cpp/utility/rel ops/operator cmp") (deprecated in C++20) | automatically generates comparison operators based on user-defined `operator==` and `operator<` (function template) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 583](https://cplusplus.github.io/CWG/issues/583.html) | C++98 | all six comparison operators could be used tocompare a pointer with a null pointer constant | only equality operators allowed | | [CWG 661](https://cplusplus.github.io/CWG/issues/661.html) | C++98 | the actual semantics of arithmetic comparisons (e.g.whether 1 < 2 yields `true` or `false`) were unspecified | specification added | | [CWG 879](https://cplusplus.github.io/CWG/issues/879.html) | C++98 | pointers to function types and pointersto void did not have built-in comparisons | added comparison specificationfor these pointers | | [CWG 1512](https://cplusplus.github.io/CWG/issues/1512.html) | C++98 | the rule of composite pointer type was incomplete, and thusdid not allow comparison between `int**` and `const int**` | made complete | | [CWG 1596](https://cplusplus.github.io/CWG/issues/1596.html) | C++98 | non-array objects were considered to belong to arrays withone element only for the purpose of pointer arithmetic | the rule is alsoapplied to comparison | | [CWG 1598](https://cplusplus.github.io/CWG/issues/1598.html) | C++98 | two pointers to members of classes that are different andneither is the base class of the other did not compare equaleven if the offsets of the pointed members can be the same | the result isunspecifiedin this case | | [CWG 1858](https://cplusplus.github.io/CWG/issues/1858.html) | C++98 | it was not clear whether two pointers to membersthat refer to different members of the same unioncompare equal as if they refer to the same member | they compareequal in this case | | [CWG 2419](https://cplusplus.github.io/CWG/issues/2419.html) | C++98 | a pointer to non-array object was only treated as apointer to the first element of an array with size 1in pointer comparison if the pointer is obtained by `&` | applies to all pointersto non-array objects | ### See also * [Operator precedence](operator_precedence "cpp/language/operator precedence") * [Operator overloading](operators "cpp/language/operators") * [Compare](../named_req/compare "cpp/named req/Compare") (named requirements) | Common operators | | --- | | [assignment](operator_assignment "cpp/language/operator assignment") | [incrementdecrement](operator_incdec "cpp/language/operator incdec") | [arithmetic](operator_arithmetic "cpp/language/operator arithmetic") | [logical](operator_logical "cpp/language/operator logical") | **comparison** | [memberaccess](operator_member_access "cpp/language/operator member access") | [other](operator_other "cpp/language/operator other") | | `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b a <=> b`. | `a[b] *a &a a->b a.b a->*b a.*b`. | `a(...) a, b a ? b : c`. | | Special operators | | [`static_cast`](static_cast "cpp/language/static cast") converts one type to another related type [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") converts within inheritance hierarchies [`const_cast`](const_cast "cpp/language/const cast") adds or removes [cv](cv "cpp/language/cv") qualifiers [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") converts type to unrelated type [C-style cast](explicit_cast "cpp/language/explicit cast") converts one type to another by a mix of `static_cast`, `const_cast`, and `reinterpret_cast` [`new`](new "cpp/language/new") creates objects with dynamic storage duration [`delete`](delete "cpp/language/delete") destructs objects previously created by the new expression and releases obtained memory area [`sizeof`](sizeof "cpp/language/sizeof") queries the size of a type [`sizeof...`](sizeof... "cpp/language/sizeof...") queries the size of a [parameter pack](parameter_pack "cpp/language/parameter pack") (since C++11) [`typeid`](typeid "cpp/language/typeid") queries the type information of a type [`noexcept`](noexcept "cpp/language/noexcept") checks if an expression can throw an exception (since C++11) [`alignof`](alignof "cpp/language/alignof") queries alignment requirements of a type (since C++11). | | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/operator_comparison "c/language/operator comparison") for Comparison operators |
programming_docs
cpp Pointer declaration Pointer declaration =================== Declares a variable of a pointer or pointer-to-member type. ### Syntax A pointer declaration is any simple declaration whose [declarator](declarations "cpp/language/declarations") has the form. | | | | | --- | --- | --- | | `*` attr(optional) cv(optional) declarator | (1) | | | nested-name-specifier `*` attr(optional) cv(optional) declarator | (2) | | 1) **Pointer declarator**: the declaration `S* D;` declares `D` as a pointer to the type determined by decl-specifier-seq `S`. 2) **Pointer to member declarator**: the declaration `S C::* D;` declares `D` as a pointer to non-static member of `C` of type determined by decl-specifier-seq `S`. | | | | | --- | --- | --- | | nested-name-specifier | - | a [sequence of names and scope resolution operators `::`](identifiers#Qualified_identifiers "cpp/language/identifiers") | | attr | - | (since C++11) a list of [attributes](attributes "cpp/language/attributes") | | cv | - | const/volatile qualification which apply to the pointer that is being declared (not to the pointed-to type, whose qualifications are part of decl-specifier-seq) | | declarator | - | any [declarator](declarations "cpp/language/declarations") other than a reference declarator (there are no pointers to references). It can be another pointer declarator (pointer to pointers are allowed) | There are no pointers to [references](reference "cpp/language/reference") and there are no pointers to [bit fields](bit_field "cpp/language/bit field"). Typically, mentions of "pointers" without elaboration do not include pointers to (non-static) members. ### Pointers Every value of pointer type is one of the following: * a *pointer to an object or function* (in which case the pointer is said to *point to* the object or function), or * a *pointer past the end of an object*, or * the *[null pointer value](#Null_pointers)* for that type, or * an *invalid pointer value*. A pointer that points to an object *represents the address* of the first byte in memory occupied by the object. A pointer past the end of an object *represents the address* of the first byte in memory after the end of the storage occupied by the object. Note that two pointers that represent the same address may nonetheless have different values. ``` struct C { int x, y; } c; int* px = &c.x; // value of px is "pointer to c.x" int* pxe= px + 1; // value of pxe is "pointer past the end of c.x" int* py = &c.y; // value of py is "pointer to c.y" assert(pxe == py); // == tests if two pointers represent the same address // may or may not fire *pxe = 1; // undefined behavior even if the assertion does not fire ``` Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior. Some implementations might define that copying an invalid pointer value causes a system-generated runtime fault. #### Pointers to objects A pointer to object can be initialized with the return value of the [address-of operator](operator_member_access "cpp/language/operator member access") applied to any expression of object type, including another pointer type: ``` int n; int* np = &n; // pointer to int int* const* npp = &np; // non-const pointer to const pointer to non-const int int a[2]; int (*ap)[2] = &a; // pointer to array of int struct S { int n; }; S s = {1}; int* sp = &s.n; // pointer to the int that is a member of s ``` Pointers may appear as operands to the built-in indirection operator (unary `operator*`), which returns the [lvalue expression](value_category#lvalue "cpp/language/value category") identifying the pointed-to object: ``` int n; int* p = &n; // pointer to n int& r = *p; // reference is bound to the lvalue expression that identifies n r = 7; // stores the int 7 in n std::cout << *p; // lvalue-to-rvalue implicit conversion reads the value from n ``` Pointers to class objects may also appear as the left-hand operands of the member access operators [`operator->`](operator_member_access#Built-in_member_access_operators "cpp/language/operator member access") and [`operator->*`](operator_member_access#Built-in_pointer-to-member_access_operators "cpp/language/operator member access"). Because of the [array-to-pointer](implicit_cast "cpp/language/implicit cast") implicit conversion, pointer to the first element of an array can be initialized with an expression of array type: ``` int a[2]; int* p1 = a; // pointer to the first element a[0] (an int) of the array a int b[6][3][8]; int (*p2)[3][8] = b; // pointer to the first element b[0] of the array b, // which is an array of 3 arrays of 8 ints ``` Because of the [derived-to-base](implicit_cast "cpp/language/implicit cast") implicit conversion for pointers, pointer to a base class can be initialized with the address of a derived class: ``` struct Base {}; struct Derived : Base {}; Derived d; Base* p = &d; ``` If `Derived` is [polymorphic](object#Polymorphic_objects "cpp/language/object"), such pointer may be used to make [virtual function calls](virtual "cpp/language/virtual"). Certain [addition, subtraction](operator_arithmetic#Additive_operators "cpp/language/operator arithmetic"), [increment, and decrement](operator_incdec "cpp/language/operator incdec") operators are defined for pointers to elements of arrays: such pointers satisfy the [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") requirements and allow the C++ library [algorithms](../algorithm "cpp/algorithm") to work with raw arrays. [Comparison operators](operator_comparison#Pointer_comparison_operators "cpp/language/operator comparison") are defined for pointers to objects in some situations: two pointers that represent the same address compare equal, two null pointer values compare equal, pointers to elements of the same array compare the same as the array indexes of those elements, and pointers to non-static data members with the same [member access](access "cpp/language/access") compare in order of declaration of those members. Many implementations also provide [strict total ordering](https://en.wikipedia.org/wiki/Total_order#Strict_total_order "enwiki:Total order") of pointers of random origin, e.g. if they are implemented as addresses within continuous virtual address space. Those implementations that do not (e.g. where not all bits of the pointer are part of a memory address and have to be ignored for comparison, or an additional calculation is required or otherwise pointer and integer is not a 1 to 1 relationship), provide a specialization of `[std::less](../utility/functional/less "cpp/utility/functional/less")` for pointers that has that guarantee. This makes it possible to use all pointers of random origin as keys in standard associative containers such as `[std::set](../container/set "cpp/container/set")` or `[std::map](../container/map "cpp/container/map")`. #### Pointers to void Pointer to object of any type can be [implicitly converted](implicit_cast "cpp/language/implicit cast") to pointer to `void` (optionally [cv-qualified](cv "cpp/language/cv")); the pointer value is unchanged. The reverse conversion, which requires [`static_cast`](static_cast "cpp/language/static cast") or [explicit cast](explicit_cast "cpp/language/explicit cast"), yields the original pointer value: ``` int n = 1; int* p1 = &n; void* pv = p1; int* p2 = static_cast<int*>(pv); std::cout << *p2 << '\n'; // prints 1 ``` If the original pointer is pointing to a base class subobject within an object of some polymorphic type, [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") may be used to obtain a `void*` that is pointing at the complete object of the most derived type. Pointers to void have the same size, representation and alignment as pointers to `char`. Pointers to void are used to pass objects of unknown type, which is common in C interfaces: `[std::malloc](../memory/c/malloc "cpp/memory/c/malloc")` returns `void*`, `[std::qsort](../algorithm/qsort "cpp/algorithm/qsort")` expects a user-provided callback that accepts two `const void*` arguments. [`pthread_create`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_create.html) expects a user-provided callback that accepts and returns `void*`. In all cases, it is the caller's responsibility to cast the pointer to the correct type before use. #### Pointers to functions A pointer to function can be initialized with an address of a non-member function or a static member function. Because of the [function-to-pointer](implicit_cast "cpp/language/implicit cast") implicit conversion, the address-of operator is optional: ``` void f(int); void (*p1)(int) = &f; void (*p2)(int) = f; // same as &f ``` Unlike functions or references to functions, pointers to functions are objects and thus can be stored in arrays, copied, assigned, etc. ``` void (a[10])(int); // Error: array of functions void (&a[10])(int); // Error: array of references void (*a[10])(int); // OK: array of pointers to functions ``` Note: declarations involving pointers to functions can often be simplified with type aliases: ``` using F = void(int); // named type alias to simplify declarations F a[10]; // Error: array of functions F& a[10]; // Error: array of references F* a[10]; // OK: array of pointers to functions ``` A pointer to function can be used as the left-hand operand of the [function call operator](operator_other "cpp/language/operator other"), this invokes the pointed-to function: ``` int f(int n) { std::cout << n << '\n'; return n * n; } int main() { int (*p)(int) = f; int x = p(7); } ``` Dereferencing a function pointer yields the lvalue identifying the pointed-to function: ``` int f(); int (*p)() = f; // pointer p is pointing to f int (&r)() = *p; // the lvalue that identifies f is bound to a reference r(); // function f invoked through lvalue reference (*p)(); // function f invoked through the function lvalue p(); // function f invoked directly through the pointer ``` A pointer to function may be initialized from an overload set which may include functions, function template specializations, and function templates, if only one overload matches the type of the pointer (see [address of an overloaded function](overloaded_address "cpp/language/overloaded address") for more detail): ``` template<typename T> T f(T n) { return n; } double f(double n) { return n; } int main() { int (*p)(int) = f; // instantiates and selects f<int> } ``` [Equality comparison operators](operator_comparison#Pointer_comparison_operators "cpp/language/operator comparison") are defined for pointers to functions (they compare equal if pointing to the same function). ### Pointers to members #### Pointers to data members A pointer to non-static member object `m` which is a member of class `C` can be initialized with the expression `&C::m` exactly. Expressions such as `&(C::m)` or `&m` inside `C`'s member function do not form pointers to members. Such pointer may be used as the right-hand operand of the [pointer-to-member access operators](operator_member_access "cpp/language/operator member access") `operator.*` and `operator->*`: ``` struct C { int m; }; int main() { int C::* p = &C::m; // pointer to data member m of class C C c = {7}; std::cout << c.*p << '\n'; // prints 7 C* cp = &c; cp->m = 10; std::cout << cp->*p << '\n'; // prints 10 } ``` Pointer to data member of an accessible unambiguous non-virtual base class can be [implicitly converted](implicit_cast "cpp/language/implicit cast") to pointer to the same data member of a derived class: ``` struct Base { int m; }; struct Derived : Base {}; int main() { int Base::* bp = &Base::m; int Derived::* dp = bp; Derived d; d.m = 1; std::cout << d.*dp << ' ' << d.*bp << '\n'; // prints 1 1 } ``` Conversion in the opposite direction, from a pointer to data member of a derived class to a pointer to data member of an unambiguous non-virtual base class, is allowed with [`static_cast`](static_cast "cpp/language/static cast") and [explicit cast](explicit_cast "cpp/language/explicit cast"), even if the base class does not have that member (but the most-derived class does, when the pointer is used for access): ``` struct Base {}; struct Derived : Base { int m; }; int main() { int Derived::* dp = &Derived::m; int Base::* bp = static_cast<int Base::*>(dp); Derived d; d.m = 7; std::cout << d.*bp << '\n'; // okay: prints 7 Base b; std::cout << b.*bp << '\n'; // undefined behavior } ``` The pointed-to type of a pointer-to-member may be a pointer-to-member itself: pointers to members can be multilevel, and can be cv-qualifed differently at every level. Mixed multi-level combinations of pointers and pointers-to-members are also allowed: ``` struct A { int m; // const pointer to non-const member int A::* const p; }; int main() { // non-const pointer to data member which is a const pointer to non-const member int A::* const A::* p1 = &A::p; const A a = {1, &A::m}; std::cout << a.*(a.*p1) << '\n'; // prints 1 // regular non-const pointer to a const pointer-to-member int A::* const* p2 = &a.p; std::cout << a.**p2 << '\n'; // prints 1 } ``` #### Pointers to member functions A pointer to non-static member function `f` which is a member of class `C` can be initialized with the expression `&C::f` exactly. Expressions such as `&(C::f)` or `&f` inside `C`'s member function do not form pointers to member functions. Such pointer may be used as the right-hand operand of the [pointer-to-member access operators](operator_member_access "cpp/language/operator member access") `operator.*` and `operator->*`. The [resulting expression](value_category#Pending_member_function_call "cpp/language/value category") can be used only as the left-hand operand of a function-call operator: ``` struct C { void f(int n) { std::cout << n << '\n'; } }; int main() { void (C::* p)(int) = &C::f; // pointer to member function f of class C C c; (c.*p)(1); // prints 1 C* cp = &c; (cp->*p)(2); // prints 2 } ``` Pointer to member function of a base class can be [implicitly converted](implicit_cast "cpp/language/implicit cast") to pointer to the same member function of a derived class: ``` struct Base { void f(int n) { std::cout << n << '\n'; } }; struct Derived : Base {}; int main() { void (Base::* bp)(int) = &Base::f; void (Derived::* dp)(int) = bp; Derived d; (d.*dp)(1); (d.*bp)(2); } ``` Conversion in the opposite direction, from a pointer to member function of a derived class to a pointer to member function of an unambiguous non-virtual base class, is allowed with [`static_cast`](static_cast "cpp/language/static cast") and [explicit cast](explicit_cast "cpp/language/explicit cast"), even if the base class does not have that member function (but the most-derived class does, when the pointer is used for access): ``` struct Base {}; struct Derived : Base { void f(int n) { std::cout << n << '\n'; } }; int main() { void (Derived::* dp)(int) = &Derived::f; void (Base::* bp)(int) = static_cast<void (Base::*)(int)>(dp); Derived d; (d.*bp)(1); // okay: prints 1 Base b; (b.*bp)(2); // undefined behavior } ``` Pointers to member functions may be used as callbacks or as function objects, often after applying `[std::mem\_fn](../utility/functional/mem_fn "cpp/utility/functional/mem fn")` or `[std::bind](../utility/functional/bind "cpp/utility/functional/bind")`: ``` #include <iostream> #include <string> #include <algorithm> #include <functional> int main() { std::vector<std::string> v = {"a", "ab", "abc"}; std::vector<std::size_t> l; transform(v.begin(), v.end(), std::back_inserter(l), std::mem_fn(&std::string::size)); for(std::size_t n : l) std::cout << n << ' '; } ``` Output: ``` 1 2 3 ``` ### Null pointers Pointers of every type have a special value known as *null pointer value* of that type. A pointer whose value is null does not point to an object or a function (the behavior of dereferencing a null pointer is undefined), and compares equal to all pointers of the same type whose value is also *null*. To initialize a pointer to null or to assign the null value to an existing pointer, the null pointer literal `nullptr`, the null pointer constant `[NULL](../types/null "cpp/types/NULL")`, or the [implicit conversion](implicit_cast "cpp/language/implicit cast") from the integer literal with value `​0​` may be used. [Zero-](zero_initialization "cpp/language/zero initialization") and [value-initialization](value_initialization "cpp/language/value initialization") also initialize pointers to their null values. Null pointers can be used to indicate the absence of an object (e.g. [`function::target()`](../utility/functional/function/target "cpp/utility/functional/function/target")), or as other error condition indicators (e.g. [dynamic\_cast](dynamic_cast "cpp/language/dynamic cast")). In general, a function that receives a pointer argument almost always needs to check if the value is null and handle that case differently (for example, the [delete expression](delete "cpp/language/delete") does nothing when a null pointer is passed). ### Constness * If cv appears before `*` in the pointer declaration, it is part of decl-specifier-seq and applies to the pointed-to object. * If cv appears after `*` in the pointer declaration, it is part of declarator and applies to the pointer that's being declared. | Syntax | meaning | | --- | --- | | `const T*` | pointer to constant object | | `T const*` | pointer to constant object | | `T* const` | constant pointer to object | | `const T* const` | constant pointer to constant object | | `T const* const` | constant pointer to constant object | ``` // pc is a non-const pointer to const int // cpc is a const pointer to const int // ppc is a non-const pointer to non-const pointer to const int const int ci = 10, *pc = &ci, *const cpc = pc, **ppc; // p is a non-const pointer to non-const int // cp is a const pointer to non-const int int i, *p, *const cp = &i; i = ci; // okay: value of const int copied into non-const int *cp = ci; // okay: non-const int (pointed-to by const pointer) can be changed pc++; // okay: non-const pointer (to const int) can be changed pc = cpc; // okay: non-const pointer (to const int) can be changed pc = p; // okay: non-const pointer (to const int) can be changed ppc = &pc; // okay: address of pointer to const int is pointer to pointer to const int ci = 1; // error: const int cannot be changed ci++; // error: const int cannot be changed *pc = 2; // error: pointed-to const int cannot be changed cp = &ci; // error: const pointer (to non-const int) cannot be changed cpc++; // error: const pointer (to const int) cannot be changed p = pc; // error: pointer to non-const int cannot point to const int ppc = &p; // error: pointer to pointer to const int cannot point to // pointer to non-const int ``` In general, implicit conversion from one multi-level pointer to another follows the rules described in [qualification conversions](implicit_cast#Qualification_conversions "cpp/language/implicit cast") and in [pointer comparison operators](operator_comparison#Pointer_comparison_operators "cpp/language/operator comparison"). ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 73](https://cplusplus.github.io/CWG/issues/73.html) | C++98 | a pointer to an object never compares equalto a pointer to one past the end of an array | for non-null and non-function pointers,compare the addresses they represent | | [CWG 903](https://cplusplus.github.io/CWG/issues/903.html) | C++98 | any integral constant expression thatevaluates to 0 was a null pointer constant | limited to integerliterals with value 0 | | [CWG 1438](https://cplusplus.github.io/CWG/issues/1438.html) | C++98 | the behavior of using an invalid pointervalue in any way was undefined | behaviors other than indirection andpassing to deallocation functionsare implementation-defined | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/pointer "c/language/pointer") for Pointer declaration |
programming_docs
cpp Converting constructor Converting constructor ====================== A constructor that is not declared with the specifier [explicit](explicit "cpp/language/explicit") and which can be called with a single parameter (until C++11) is called a *converting constructor*. Unlike explicit constructors, which are only considered during [direct initialization](direct_initialization "cpp/language/direct initialization") (which includes [explicit conversions](explicit_cast "cpp/language/explicit cast") such as [static\_cast](static_cast "cpp/language/static cast")), converting constructors are also considered during [copy initialization](copy_initialization "cpp/language/copy initialization"), as part of [user-defined conversion sequence](implicit_cast "cpp/language/implicit cast"). It is said that a converting constructor specifies an implicit conversion from the types of its arguments (if any) to the type of its class. Note that non-explicit [user-defined conversion function](cast_operator "cpp/language/cast operator") also specifies an implicit conversion. Implicitly-declared and user-defined non-explicit [copy constructors](copy_constructor "cpp/language/copy constructor") and [move constructors](move_constructor "cpp/language/move constructor") are converting constructors. ### Example ``` struct A { A() { } // converting constructor (since C++11) A(int) { } // converting constructor A(int, int) { } // converting constructor (since C++11) }; struct B { explicit B() { } explicit B(int) { } explicit B(int, int) { } }; int main() { A a1 = 1; // OK: copy-initialization selects A::A(int) A a2(2); // OK: direct-initialization selects A::A(int) A a3{4, 5}; // OK: direct-list-initialization selects A::A(int, int) A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int) A a5 = (A)1; // OK: explicit cast performs static_cast, direct-initialization // B b1 = 1; // error: copy-initialization does not consider B::B(int) B b2(2); // OK: direct-initialization selects B::B(int) B b3{4, 5}; // OK: direct-list-initialization selects B::B(int, int) // B b4 = {4, 5}; // error: copy-list-initialization selected an explicit constructor // B::B(int, int) B b5 = (B)1; // OK: explicit cast performs static_cast, direct-initialization B b6; // OK, default-initialization B b7{}; // OK, direct-list-initialization // B b8 = {}; // error: copy-list-initialization selected an explicit constructor // B::B() } ``` ### See also * [copy assignment](copy_assignment "cpp/language/copy assignment") * [copy constructor](copy_constructor "cpp/language/copy constructor") * [copy elision](copy_elision "cpp/language/copy elision") * [default constructor](default_constructor "cpp/language/default constructor") * [destructor](destructor "cpp/language/destructor") * [explicit](explicit "cpp/language/explicit") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [copy initialization](copy_initialization "cpp/language/copy initialization") + [default initialization](default_initialization "cpp/language/default initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [initializer list](initializer_list "cpp/language/initializer list") + [list initialization](list_initialization "cpp/language/list initialization") + [reference initialization](reference_initialization "cpp/language/reference initialization") + [value initialization](value_initialization "cpp/language/value initialization") + [zero initialization](zero_initialization "cpp/language/zero initialization") * [move assignment](move_assignment "cpp/language/move assignment") * [move constructor](move_constructor "cpp/language/move constructor") * [new](new "cpp/language/new") cpp Abstract class Abstract class ============== Defines an abstract type which cannot be instantiated, but can be used as a base class. ### Syntax A *pure virtual* function is a [virtual function](virtual "cpp/language/virtual") whose [declarator](function "cpp/language/function") has the following syntax: | | | | | --- | --- | --- | | declarator virt-specifier(optional) `=` `0` | | | Here the sequence `= 0` is known as pure-specifier, and appears either immediately after the declarator or after the optional virt-specifier ([`override`](override "cpp/language/override") or [`final`](final "cpp/language/final")). pure-specifier cannot appear in a member function definition or [friend](friend "cpp/language/friend") declaration. ``` struct Base { virtual int g(); virtual ~Base() {} }; struct A : Base { // OK: declares three member virtual functions, two of them pure virtual int f() = 0, g() override = 0, h(); // OK: destructor can be pure too ~A() = 0; // Error: pure-specifier on a function definition virtual int b() = 0 {} }; ``` An *abstract class* is a class that either defines or inherits at least one function for which [the final overrider](virtual "cpp/language/virtual") is *pure virtual*. ### Explanation Abstract classes are used to represent general concepts (for example, Shape, Animal), which can be used as base classes for concrete classes (for example, Circle, Dog). No objects of an abstract class can be created (except for base subobjects of a class derived from it) and no non-static data members whose type is an abstract class can be declared. Abstract types cannot be used as parameter types, as function return types, or as the type of an explicit conversion (note this is checked at the point of definition and function call, since at the point of function declaration parameter and return type may be incomplete). Pointers and references to an abstract class can be declared. ``` struct Abstract { virtual void f() = 0; // pure virtual }; // "Abstract" is abstract struct Concrete : Abstract { void f() override {} // non-pure virtual virtual void g(); // non-pure virtual }; // "Concrete" is non-abstract struct Abstract2 : Concrete { void g() override = 0; // pure virtual overrider }; // "Abstract2" is abstract int main() { // Abstract a; // Error: abstract class Concrete b; // OK Abstract& a = b; // OK to reference abstract base a.f(); // virtual dispatch to Concrete::f() // Abstract2 a2; // Error: abstract class (final overrider of g() is pure) } ``` The definition of a pure virtual function may be provided (and must be provided if the pure virtual is the [destructor](destructor "cpp/language/destructor")): the member functions of the derived class are free to call the abstract base's pure virtual function using qualified function id. This definition must be provided outside of the class body (the syntax of a function declaration doesn't allow both the pure specifier `= 0` and a function body). Making a virtual call to a pure virtual function from a constructor or the destructor of the abstract class is undefined behavior (regardless of whether it has a definition or not). ``` struct Abstract { virtual void f() = 0; // pure virtual virtual void g() {} // non-pure virtual ~Abstract() { g(); // OK: calls Abstract::g() // f(); // undefined behavior Abstract::f(); // OK: non-virtual call } }; // definition of the pure virtual function void Abstract::f() { std::cout << "A::f()\n"; } struct Concrete : Abstract { void f() override { Abstract::f(); // OK: calls pure virtual function } void g() override {} ~Concrete() { g(); // OK: calls Concrete::g() f(); // OK: calls Concrete::f() } }; ``` ### Defect Reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 390](https://cplusplus.github.io/CWG/issues/390.html) | C++98 | an undefined pure virtual destructor might be called | a definition is required in this case | | [CWG 2153](https://cplusplus.github.io/CWG/issues/2153.html) | C++98 | pure-specifier could appear in friend declarations | prohibited | ### See also * [`virtual`](virtual "cpp/language/virtual") cpp Transactional memory Transactional memory ==================== Work in progress This page is under construction Experimental Feature The functionality described on this page is part of the Transactional Memory Technical Specification ISO/IEC TS 19841:2015 (TM TS) Transactional memory is a concurrency synchronization mechanism that combines groups of statements in transactions, that are. * atomic (either all statements occur, or nothing occurs) * isolated (statements in a transaction may not observe half-written writes made by another transaction, even if they execute in parallel) Typical implementations use hardware transactional memory where supported and to the limits that it is available (e.g. until the changeset is saturated) and fall back to software transactional memory, usually implemented with optimistic concurrency: if another transaction updated some of the variables used by a transaction, it is silently retried. For that reason, retriable transactions ("atomic blocks") can only call transaction-safe functions. Note that accessing a variable in a transaction and out of a transaction without other external synchronization is a data race. If feature testing is supported, the features described here are indicated by the macro constant `__cpp_transactional_memory` with a value equal or greater `201505`. ### Synchronized blocks `synchronized` compound-statement. Executes the [compound statement](statements#Compound_statements "cpp/language/statements") as if under a global lock: all outermost synchronized blocks in the program execute in a single total order. The end of each synchronized block synchronizes with the beginning of the next synchronized block in that order. Synchronized blocks that are nested within other synchronized blocks have no special semantics. Synchronized blocks are not transactions (unlike the atomic blocks below) and may call transaction-unsafe functions. ``` #include <iostream> #include <vector> #include <thread> int f() { static int i = 0; synchronized { // begin synchronized block std::cout << i << " -> "; ++i; // each call to f() obtains a unique value of i std::cout << i << '\n'; return i; // end synchronized block } } int main() { std::vector<std::thread> v(10); for(auto& t: v) t = std::thread([]{ for(int n = 0; n < 10; ++n) f(); }); for(auto& t: v) t.join(); } ``` Output: ``` 0 -> 1 1 -> 2 2 -> 3 ... 99 -> 100 ``` Leaving a synchronized block by any means (reaching the end, executing goto, break, continue, or return, or throwing an exception) exits the block and synchronizes-with the next block in the single total order if the exited block was an outer block. The behavior is undefined if `[std::longjmp](../utility/program/longjmp "cpp/utility/program/longjmp")` is used to exit a synchronized block. Entering a synchronized block by goto or switch is not allowed. Although synchronized blocks execute as-if under a global lock, the implementations are expected to examine the code within each block and use optimistic concurrency (backed up by hardware transactional memory where available) for transaction-safe code and minimal locking for non-transaction safe code. When a synchronized block makes a call to a non-inlined function, the compiler may have to drop out of speculative execution and hold a lock around the entire call unless the function is declared `transaction_safe` (see below) or the attribute `[[optimize_for_synchronized]]` (see below) is used. ### Atomic blocks `atomic_noexcept` compound-statement. `atomic_cancel` compound-statement. `atomic_commit` compound-statement. 1) If an exception is thrown, `[std::abort](http://en.cppreference.com/w/cpp/utility/program/abort)` is called 2) If an exception is thrown, `[std::abort](http://en.cppreference.com/w/cpp/utility/program/abort)` is called, unless the exception is one of the exceptions used for transaction cancellation (see below) in which case the transaction is *cancelled*: the values of all memory locations in the program that were modified by side effects of the operations of the atomic block are restored to the values they had at the time the start of the atomic block was executed, and the exception continues stack unwinding as usual. 3) If an exception is thrown, the transaction is committed normally. The exceptions used for transaction cancellation in `atomic_cancel` blocks are `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")`, `[std::bad\_array\_new\_length](../memory/new/bad_array_new_length "cpp/memory/new/bad array new length")`, `[std::bad\_cast](../types/bad_cast "cpp/types/bad cast")`, `[std::bad\_typeid](../types/bad_typeid "cpp/types/bad typeid")`, `[std::bad\_exception](../error/bad_exception "cpp/error/bad exception")`, `[std::exception](../error/exception "cpp/error/exception")` and all standard library exceptions derived from it, and the special exception type [`std::tx_exception<T>`](../error/tx_exception "cpp/error/tx exception") The compound-statement in an atomic block is not allowed to execute any expression or statement or call any function that isn't `transaction_safe` (this is a compile time error). ``` // each call to f() retrieves a unique value of i, even when done in parallel int f() { static int i = 0; atomic_noexcept { // begin transaction // printf("before %d\n", i); // error: cannot call a non transaction-safe function ++i; return i; // commit transaction } } ``` Leaving an atomic block by any means other than exception (reaching the end, goto, break, continue, return) commits the transaction. The behavior is undefined if `[std::longjmp](../utility/program/longjmp "cpp/utility/program/longjmp")` is used to exit an atomic block. ### Transaction-safe functions A function can be explicitly declared to be transaction-safe by using the keyword `transaction_safe` in its declaration. In a [lambda](lambda "cpp/language/lambda") declaration, it appears either immediately after the capture list, or immediately after the (keyword `mutable` (if one is used). ``` extern volatile int * p = 0; struct S { virtual ~S(); }; int f() transaction_safe { int x = 0; // ok: not volatile p = &x; // ok: the pointer is not volatile int i = *p; // error: read through volatile glvalue S s; // error: invocation of unsafe destructor } ``` ``` int f(int x) { // implicitly transaction-safe if (x <= 0) return 0; return x + f(x-1); } ``` If a function that is not transaction-safe is called through a reference or pointer to a transaction-safe function, the behavior is undefined. Pointers to transaction-safe functions and pointers to transaction-safe member functions are implicitly convertible to pointers to functions and pointers to member functions respectively. It is unspecified if the resulting pointer compares equal to the original. #### Transaction-safe virtual functions If the final overrider of a `transaction_safe_dynamic` function is not declared `transaction_safe`, calling it in an atomic block is undefined behavior. ### Standard library Besides introducing the new exception template [`std::tx_exception`](../error/tx_exception "cpp/error/tx exception"), the transactional memory technical specification makes the following changes to the standard library: * makes the following functions explicitly `transaction_safe`: + `[std::forward](../utility/forward "cpp/utility/forward")`, `std::move`, `[std::move\_if\_noexcept](../utility/move_if_noexcept "cpp/utility/move if noexcept")`, `[std::align](../memory/align "cpp/memory/align")`, `[std::abort](../utility/program/abort "cpp/utility/program/abort")`, global default `[operator new](../memory/new/operator_new "cpp/memory/new/operator new")`, global default `[operator delete](../memory/new/operator_delete "cpp/memory/new/operator delete")`, `[std::allocator::construct](../memory/allocator/construct "cpp/memory/allocator/construct")` if the invoked constructor is transaction-safe, `[std::allocator::destroy](../memory/allocator/destroy "cpp/memory/allocator/destroy")` if the invoked destructor is transaction-safe, `[std::get\_temporary\_buffer](../memory/get_temporary_buffer "cpp/memory/get temporary buffer")`, `[std::return\_temporary\_buffer](../memory/return_temporary_buffer "cpp/memory/return temporary buffer")`, `[std::addressof](../memory/addressof "cpp/memory/addressof")`, `[std::pointer\_traits::pointer\_to](../memory/pointer_traits/pointer_to "cpp/memory/pointer traits/pointer to")`, each non-virtual member function of all exception types that support transaction cancellation (see `atomic_cancel` above) * makes the following functions explicitly `transaction_safe_dynamic` + each virtual member function of all exception types that support transaction cancellation (see `atomic_cancel` above) * requires that all operations that are transaction-safe on an [Allocator](../named_req/allocator "cpp/named req/Allocator") X are transaction-safe on `X::rebind<>::other` ### Attributes The attribute `[[[optimize\_for\_synchronized](attributes/optimize_for_synchronized "cpp/language/attributes/optimize for synchronized")]]` may be applied to a declarator in a function declaration and must appear on the first declaration of the function. If a function is declared `[[optimize_for_synchronized]]` in one translation unit and the same function is declared without `[[optimize_for_synchronized]]` in another translation unit, the program is ill-formed; no diagnostic required. It indicates that a the function definition should be optimized for invocation from a `synchronized` statement. In particular, it avoids serializing synchronized blocks that make a call to a function that is transaction-safe for the majority of calls, but not for all calls (e.g. hash table insertion that may have to rehash, allocator that may have to request a new block, a simple function that may rarely log). ``` std::atomic<bool> rehash{false}; // maintenance thread runs this loop void maintenance_thread(void*) { while (!shutdown) { synchronized { if (rehash) { hash.rehash(); rehash = false; } } } } // worker threads execute hundreds of thousands of calls to this function // every second. Calls to insert_key() from synchronized blocks in other // translation units will cause those blocks to serialize, unless insert_key() // is marked [[optimize_for_synchronized]] [[optimize_for_synchronized]] void insert_key(char* key, char* value) { bool concern = hash.insert(key, value); if (concern) rehash = true; } ``` GCC assembly without the attribute: the entire function is serialized. ``` insert_key(char*, char*): subq $8, %rsp movq %rsi, %rdx movq %rdi, %rsi movl $hash, %edi call Hash::insert(char*, char*) testb %al, %al je .L20 movb $1, rehash(%rip) mfence .L20: addq $8, %rsp ret ``` GCC assembly with the attribute: ``` transaction clone for insert_key(char*, char*): subq $8, %rsp movq %rsi, %rdx movq %rdi, %rsi movl $hash, %edi call transaction clone for Hash::insert(char*, char*) testb %al, %al je .L27 xorl %edi, %edi call _ITM_changeTransactionMode # Note: this is the serialization point movb $1, rehash(%rip) mfence .L27: addq $8, %rsp ret ``` ### Notes ### Compiler support This technical specification is supported by GCC as of version 6.1 (requires `-fgnu-tm` to enable). An older variant of this specification was [supported in GCC](http://www-users.cs.umn.edu/~boutcher/stm/) as of 4.7.
programming_docs
cpp No Diagnostic Required No Diagnostic Required ====================== "No diagnostic required" indicates that some phraseology is ill-formed according to the language rules, but a compiler need not issue any diagnostic or error message. Usually, the reason is that trying to detect these situations would result in prohibitively long compile times. If such a program is executed, [the behavior is undefined](ub "cpp/language/ub"). ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/ndr "c/language/ndr") for No Diagnostic Required | cpp Statements Statements ========== Statements are fragments of the C++ program that are executed in sequence. The body of any function is a sequence of statements. For example: ``` int main() { int n = 1; // declaration statement n = n + 1; // expression statement std::cout << "n = " << n << '\n'; // expression statement return 0; // return statement } ``` C++ includes the following types of statements: 1) labeled statements; 2) expression statements; 3) compound statements; 4) selection statements; 5) iteration statements; 6) jump statements; 7) declaration statements; 8) try blocks; 9) atomic and synchronized blocks (TM TS). ### Labeled statements A labeled statement labels a statement for control flow purposes. | | | | | --- | --- | --- | | attr(optional) identifier `:` statement | (1) | | | attr(optional) `case` constexpr `:` statement | (2) | | | attr(optional) `default` `:` statement | (3) | | 1) target for [goto](goto "cpp/language/goto"); 2) case label in a [switch](switch "cpp/language/switch") statement; 3) default label in a [switch](switch "cpp/language/switch") statement. A statement may carry multiple labels. | | | | --- | --- | | An [attribute](attributes "cpp/language/attributes") sequence attr may appear just before the label (in which case it applies to the label), or just before any statement itself, in which case it applies to the entire statement. | (since C++11) | A label with an identifier declared inside a function matches all goto statements with the same identifier in that function, in all nested blocks, before and after its own declaration. Two labels in a function must not have the same identifier. Labels are not found by [unqualified lookup](unqualified_lookup "cpp/language/unqualified lookup"): a label can have the same name as any other entity in the program. ``` void f() { { goto label; // label in scope even though declared later label:; } goto label; // label ignores block scope } void g() { goto label; // error: label not in scope in g() } ``` ### Expression statements An expression statement is an expression followed by a semicolon. | | | | | --- | --- | --- | | attr(optional) expression(optional) `;` | (1) | | | | | | | --- | --- | --- | | attr | - | (since C++11) optional sequence of any number of [attributes](attributes "cpp/language/attributes") | | expression | - | an [expression](expressions "cpp/language/expressions") | Most statements in a typical C++ program are expression statements, such as assignments or function calls. An expression statement without an expression is called a *null statement*. It is often used to provide an empty body to a [for](for "cpp/language/for") or [while](while "cpp/language/while") loop. It can also be used to carry a label in the end of a compound statement. ### Compound statements A compound statement or *block* groups a sequence of statements into a single statement. | | | | | --- | --- | --- | | attr(optional) `{` statement...(optional) `}` | (1) | | When one statement is expected, but multiple statements need to be executed in sequence (for example, in an [if](if "cpp/language/if") statement or a loop), a compound statement may be used: ``` if (x > 5) // start of if statement { // start of block int n = 1; // declaration statement std::cout << n; // expression statement } // end of block, end of if statement ``` Each compound statement introduces its own block [scope](scope "cpp/language/scope"); variables declared inside a block are destroyed at the closing brace in reverse order: ``` int main() { // start of outer block { // start of inner block std::ofstream f("test.txt"); // declaration statement f << "abc\n"; // expression statement } // end of inner block, f is flushed and closed std::ifstream f("test.txt"); // declaration statement std::string str; // declaration statement f >> str; // expression statement } // end of outer block, str is destroyed, f is closed ``` ### Selection statements A selection statement chooses between one of several control flows. | | | | | --- | --- | --- | | attr(optional) `if` `constexpr`(optional) `(` init-statement(optional) condition `)` statement | (1) | | | attr(optional) `if` `constexpr`(optional) `(` init-statement(optional) condition `)` statement `else` statement | (2) | | | attr(optional) `switch` `(` init-statement(optional) condition `)` statement | (3) | | | attr(optional) `if` `!`(optional) `consteval` compound-statement | (4) | (since C++23) | | attr(optional) `if` `!`(optional) `consteval` compound-statement `else` statement | (5) | (since C++23) | 1) [if](if "cpp/language/if") statement; 2) [if](if "cpp/language/if") statement with an else clause; 3) [switch](switch "cpp/language/switch") statement; 4) [consteval if](if#Consteval_if "cpp/language/if") statement; 5) [consteval if](if#Consteval_if "cpp/language/if") statement with an else clause. ### Iteration statements An iteration statement repeatedly executes some code. | | | | | --- | --- | --- | | attr(optional) `while` `(` condition `)` statement | (1) | | | attr(optional) `do` statement `while` `(` expression `)` `;` | (2) | | | attr(optional) `for` `(` init-statement condition(optional) `;` expression(optional) `)` statement | (3) | | | attr(optional) `for` `(` init-statement(optional)(since C++20) for-range-decl `:` for-range-init `)` statement | (4) | (since C++11) | 1) [while](while "cpp/language/while") loop; 2) [do-while](do "cpp/language/do") loop; 3) [for](for "cpp/language/for") loop; 4) [range for](range-for "cpp/language/range-for") loop. ### Jump statements A jump statement unconditionally transfers control flow. | | | | | --- | --- | --- | | attr(optional) `break` `;` | (1) | | | attr(optional) `continue` `;` | (2) | | | attr(optional) `return` expression(optional) `;` | (3) | | | attr(optional) `return` braced-init-list `;` | (4) | (since C++11) | | attr(optional) `goto` identifier `;` | (5) | | 1) [break](break "cpp/language/break") statement; 2) [continue](continue "cpp/language/continue") statement; 3) [return](return "cpp/language/return") statement with an optional expression; 4) [return](return "cpp/language/return") statement using [list initialization](list_initialization "cpp/language/list initialization"); 5) [goto](goto "cpp/language/goto") statement. Note: for all jump statements, transfer out of a loop, out of a block, or back past an initialized variable with automatic storage duration involves the destruction of objects with automatic storage duration that are in scope at the point transferred from but not at the point transferred to. If multiple objects were initialized, the order of destruction is the opposite of the order of initialization. ### Declaration statements A declaration statement introduces one or more identifiers into a block. | | | | | --- | --- | --- | | block-declaration | (1) | | 1) see [Declarations](declarations "cpp/language/declarations") and [Initialization](initialization "cpp/language/initialization") for details. ### Try blocks A try block catches exceptions thrown when executing other statements. | | | | | --- | --- | --- | | attr(optional) `try` compound-statement handler-sequence | (1) | | 1) see [try/catch](try_catch "cpp/language/try catch") for details. | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | Atomic and synchronized blocks An atomic and synchronized block provides [transactional memory](transactional_memory "cpp/language/transactional memory"). | | | | | --- | --- | --- | | `synchronized` compound-statement | (1) | (TM TS) | | `atomic_noexcept` compound-statement | (2) | (TM TS) | | `atomic_cancel` compound-statement | (3) | (TM TS) | | `atomic_commit` compound-statement | (4) | (TM TS) | 1) [synchronized block](transactional_memory#Synchronized_blocks "cpp/language/transactional memory"), executed in single total order with all synchronized blocks; 2) [atomic block](transactional_memory#Atomic_blocks "cpp/language/transactional memory") that aborts on exceptions; 3) [atomic block](transactional_memory#Atomic_blocks "cpp/language/transactional memory") that rolls back on exceptions; 4) [atomic block](transactional_memory#Atomic_blocks "cpp/language/transactional memory") that commits on exceptions. | (TM TS) | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/statements "c/language/statements") for Statements | cpp Direct initialization Direct initialization ===================== Initializes an object from explicit set of constructor arguments. ### Syntax | | | | | --- | --- | --- | | T object `(` arg `);` T object `(` arg1, arg2, ... `);` | (1) | | | T object `{` arg `};` | (2) | (since C++11) | | T `(` other `)` T `(` arg1, arg2, ... `)`. | (3) | | | `static_cast<` T `>(` other `)` | (4) | | | `new` T`(`args, ...`)` | (5) | | | Class`::`Class`()` `:` member`(`args, ...`)` `{` ... `}` | (6) | | | `[`arg`](){` ... `}` | (7) | (since C++11) | ### Explanation Direct initialization is performed in the following situations: 1) initialization with a nonempty parenthesized list of expressions or braced-init-lists (since C++11) 2) initialization of an object of non-class type with a single brace-enclosed initializer (note: for class types and other uses of braced-init-list, see [list-initialization](list_initialization "cpp/language/list initialization")) (since C++11) 3) initialization of a prvalue temporary (until C++17)the result object of a prvalue (since C++17) by [function-style cast](explicit_cast "cpp/language/explicit cast") or with a parenthesized expression list 4) initialization of a prvalue temporary (until C++17)the result object of a prvalue (since C++17) by a [static\_cast](static_cast "cpp/language/static cast") expression 5) initialization of an object with dynamic storage duration by a new-expression with a non-empty initializer 6) initialization of a base or a non-static member by constructor [initializer list](initializer_list "cpp/language/initializer list") 7) initialization of closure object members from the variables caught by copy in a lambda-expression The effects of direct initialization are: * If `T` is an array type, | | | | --- | --- | | * the program is ill-formed. | (until C++20) | | * the array is initialized as in [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization"), except that narrowing conversions are allowed and any elements without an initializer are [value-initialized](value_initialization "cpp/language/value initialization"). ``` struct A { explicit A(int i = 0) {} }; A a[2](A(1)); // OK: initializes a[0] with A(1) and a[1] with A() A b[2]{A(1)}; // error: implicit copy-list-initialization of b[1] // from {} selected explicit constructor ``` | (since C++20) | * If `T` is a class type, | | | | --- | --- | | * if the initializer is a [prvalue](value_category "cpp/language/value category") expression whose type is the same class as `T` (ignoring cv-qualification), the initializer expression itself, rather than a temporary materialized from it, is used to initialize the destination object.(Before C++17, the compiler may elide the construction from the prvalue temporary in this case, but the appropriate constructor must still be accessible: see [copy elision](copy_elision "cpp/language/copy elision")) | (since C++17) | * the constructors of `T` are examined and the best match is selected by overload resolution. The constructor is then called to initialize the object. | | | | --- | --- | | * otherwise, if the destination type is a (possibly cv-qualified) aggregate class, it is initialized as described in [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") except that narrowing conversions are permitted, designated initializers are not allowed, a temporary bound to a reference does not have its lifetime extended, there is no brace elision, and any elements without an initializer are [value-initialized](value_initialization "cpp/language/value initialization"). ``` struct B { int a; int&& r; }; int f(); int n = 10; B b1{1, f()}; // OK, lifetime is extended B b2(1, f()); // well-formed, but dangling reference B b3{1.0, 1}; // error: narrowing conversion B b4(1.0, 1); // well-formed, but dangling reference B b5(1.0, std::move(n)); // OK ``` | (since C++20) | * Otherwise, if `T` is a non-class type but the source type is a class type, the conversion functions of the source type and its base classes, if any, are examined and the best match is selected by overload resolution. The selected user-defined conversion is then used to convert the initializer expression into the object being initialized. * Otherwise, if `T` is `bool` and the source type is `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")`, the value of the initialized object is `false`. * Otherwise, [standard conversions](implicit_cast "cpp/language/implicit cast") are used, if necessary, to convert the value of other to the cv-unqualified version of `T`, and the initial value of the object being initialized is the (possibly converted) value. ### Notes Direct-initialization is more permissive than copy-initialization: copy-initialization only considers non-[explicit](explicit "cpp/language/explicit") constructors and non-explicit user-defined [conversion functions](cast_operator "cpp/language/cast operator"), while direct-initialization considers all constructors and all user-defined conversion functions. In case of ambiguity between a variable declaration using the direct-initialization syntax (1) (with round parentheses) and a [function declaration](function "cpp/language/function"), the compiler always chooses function declaration. This disambiguation rule is sometimes counter-intuitive and has been called the [most vexing parse](https://en.wikipedia.org/wiki/Most_vexing_parse "enwiki:Most vexing parse"). ``` #include <iterator> #include <string> #include <fstream> int main() { std::ifstream file("data.txt"); // the following is a function declaration: std::string str(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()); // it declares a function called str, whose return type is std::string, // first parameter has type std::istreambuf_iterator<char> and the name "file" // second parameter has no name and has type std::istreambuf_iterator<char>(), // which is rewritten to function pointer type std::istreambuf_iterator<char>(*)() // pre-C++11 fix: extra parentheses around one of the arguments std::string str( (std::istreambuf_iterator<char>(file) ), std::istreambuf_iterator<char>()); // post-C++11 fix: list-initialization for any of the arguments std::string str(std::istreambuf_iterator<char>{file}, {}); } ``` ### Example ``` #include <string> #include <iostream> #include <memory> struct Foo { int mem; explicit Foo(int n) : mem(n) {} }; int main() { std::string s1("test"); // constructor from const char* std::string s2(10, 'a'); std::unique_ptr<int> p(new int(1)); // OK: explicit constructors allowed // std::unique_ptr<int> p = new int(1); // error: constructor is explicit Foo f(2); // f is direct-initialized: // constructor parameter n is copy-initialized from the rvalue 2 // f.mem is direct-initialized from the parameter n // Foo f2 = 2; // error: constructor is explicit std::cout << s1 << ' ' << s2 << ' ' << *p << ' ' << f.mem << '\n'; } ``` Output: ``` test aaaaaaaaaa 1 2 ``` ### See also * [copy elision](copy_elision "cpp/language/copy elision") * [converting constructor](converting_constructor "cpp/language/converting constructor") * [copy assignment](copy_assignment "cpp/language/copy assignment") * [copy constructor](copy_constructor "cpp/language/copy constructor") * [default constructor](default_constructor "cpp/language/default constructor") * [destructor](destructor "cpp/language/destructor") * [`explicit`](explicit "cpp/language/explicit") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [copy initialization](copy_initialization "cpp/language/copy initialization") + [default initialization](default_initialization "cpp/language/default initialization") + [initializer list](initializer_list "cpp/language/initializer list") + [list initialization](list_initialization "cpp/language/list initialization") + [reference initialization](reference_initialization "cpp/language/reference initialization") + [value initialization](value_initialization "cpp/language/value initialization") + [zero initialization](zero_initialization "cpp/language/zero initialization") * [move assignment](move_assignment "cpp/language/move assignment") * [move constructor](move_constructor "cpp/language/move constructor") * [`new`](new "cpp/language/new") cpp Aggregate initialization Aggregate initialization ======================== Initializes an aggregate from an initializer list. It is a form of [list-initialization](list_initialization "cpp/language/list initialization"). (since C++11). ### Syntax | | | | | --- | --- | --- | | T object `=` `{` arg1, arg2, ... `};` | (1) | | | T object `{` arg1, arg2, ... `};` | (2) | (since C++11) | | T object `=` `{` `.`des1 `=` arg1 `,` `.`des2 `{` arg2 `}` ... `};` | (3) | (since C++20) | | T object `{` `.`des1 `=` arg1 `,` `.`des2 `{` arg2 `}` ... `};` | (4) | (since C++20) | 1,2) Initializing an aggregate with an ordinary initializer list. 3,4) Initializing an aggregate with [designated initializers](#Designated_initializers) (aggregate class only). ### Explanation #### Definitions An *aggregate* is one of the following types: * array type * class type (typically, `struct` or `union`), that has + no private or protected direct (since C++17)non-static data members | | | | --- | --- | | * no user-declared constructors | (until C++11) | | * no [user-provided](function#User-provided_functions "cpp/language/function"), [inherited](using_declaration#Inheriting_constructors "cpp/language/using declaration"), or [explicit](explicit "cpp/language/explicit") constructors | (since C++11)(until C++20) | | * no user-declared or inherited constructors | (since C++20) | * no virtual, private, or protected (since C++17) base classes * no virtual member functions | | | | --- | --- | | * no [default member initializers](data_members#Member_initialization "cpp/language/data members") | (since C++11)(until C++14) | The *elements* of an aggregate are: * for an array, the array elements in increasing subscript order, or | | | | --- | --- | | * for a class, the non-static data members that are not anonymous [bit-fields](bit_field "cpp/language/bit field"), in declaration order. | (until C++17) | | * for a class, the direct base classes in declaration order, followed by the direct non-static data members that are neither anonymous [bit-fields](bit_field "cpp/language/bit field") nor members of an [anonymous union](union#Anonymous_unions "cpp/language/union"), in declaration order. | (since C++17) | #### Process The effects of aggregate initialization are: 1) Reject the following ill-formed cases: * the number of initializer clauses in the initializer list exceeds the number of elements of the aggregate, or * initialize an array of unknown bound with an empty initializer list (`{}`). ``` char cv[4] = {'a', 's', 'd', 'f', 0}; // error int x[] = {} // error ``` 2) Determine the *explicitly initialized elements* of the aggregate as follows: | | | | --- | --- | | * If the initializer list is a [designated initializer list](#Designated_initializers) (the aggregate can only be of class type), the identifier in each designator shall name a direct non-static data member of the class, and the explicitly initialized elements of the aggregate are the elements that are, or contain, those members. | (since C++20) | * Otherwise, if the initializer list is non-empty, the explicitly initialized elements of the aggregate are the first *n* elements of the aggregate, where *n* is the number of elements in the initializer list. * Otherwise, the initializer list must be empty (`{}`), and there are no explicitly initialized elements. The program is ill-formed if the aggregate is an union and there are two or more explicitly initialized elements: ``` union u { int a; const char* b; }; u a = {1}; // OK: explicitly initializes member `a` u b = {0, "asdf"}; // error: explicitly initializes two members u c = {"asdf"}; // error: int cannot be initialized by "asdf" // C++20 designated initializer lists u d = {.b = "asdf"}; // OK: can explicitly initialize a non-initial member u e = {.a = 1, .b = "asdf"}; // error: explicitly initializes two members ``` 3) Initialize each element of the aggregate in the element order. That is, all value computations and side effects associated with a given element are [sequenced before](eval_order "cpp/language/eval order") those of any element that follows it in order (since C++11). #### Initializing Elements For each explicitly initialized element: | | | | --- | --- | | * If the element is an anonymous union member and the initializer list is a [designated initializer list](#Designated_initializers), the element is initialized by the designated initializer list `{D}`, where `D` is the designated initializer clause naming a member of the anonymous union member. There shall be only one such designated initializer clause. ``` struct C { union { int a; const char* p; }; int x; } c = {.a = 1, .x = 3}; // initializes c.a with 1 and c.x with 3 ``` | (since C++20) | * Otherwise, the element is [copy-initialized](copy_initialization "cpp/language/copy initialization") from the corresponding initializer clause of the initializer list: + If the initializer clause is an expression, [implicit conversions](implicit_cast "cpp/language/implicit cast") are allowed as per copy-initialization, except that narrowing conversions are prohibited (since C++11). + If the initializer clause is a nested braced-init-list (which is not an expression), [list-initialize](list_initialization "cpp/language/list initialization") the corresponding element from that clause, which will (since C++11) recursively apply the rule if the corresponding element is a subaggregate. ``` struct A { int x; struct B { int i; int j; } b; } a = {1, {2, 3}}; // initializes a.x with 1, a.b.i with 2, a.b.j with 3 struct base1 { int b1, b2 = 42; }; struct base2 { base2() { b3 = 42; } int b3; }; struct derived : base1, base2 { int d; }; derived d1{{1, 2}, {}, 4}; // initializes d1.b1 with 1, d1.b2 with 2, // d1.b3 with 42, d1.d with 4 derived d2{{}, {}, 4}; // initializes d2.b1 with 0, d2.b2 with 42, // d2.b3 with 42, d2.d with 4 ``` For a non-union aggregate, each element that is not an explicitly initialized element is initialized as follows: | | | | --- | --- | | * If the element has a [default member initializer](data_members#Member_initialization "cpp/language/data members"), the element is initialized from that initializer. | (since C++11) | * Otherwise, if the element is not a reference, the element is copy-initialized from an empty initializer list. * Otherwise, the program is ill-formed. ``` struct S { int a; const char* b; int c; int d = b[a]; }; // initializes ss.a with 1, // ss.b with "asdf", // ss.c with the value of an expression of the form int{} (that is, 0), // and ss.d with the value of ss.b[ss.a] (that is, 's') S ss = {1, "asdf"}; ``` If the aggregate is a union and the initializer list is empty, then. | | | | --- | --- | | * If any variant member has a default member initializer, that member is initialized from its default member initializer. | (since C++11) | * Otherwise, the first member of the union (if any) is copy-initialized from an empty initializer list. #### Brace elision The braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object. However, if the object has a sub-aggregate without any members (an empty struct, or a struct holding only static members), brace elision is not allowed, and an empty nested list `{}` must be used. | | | | --- | --- | | Designated initializers The syntax forms (3,4) are known as designated initializers: each designator must name a direct non-static data member of T, and all designators used in the expression must appear in the same order as the data members of T. ``` struct A { int x; int y; int z; }; A a{.y = 2, .x = 1}; // error; designator order does not match declaration order A b{.x = 1, .z = 2}; // ok, b.y initialized to 0 ``` Each direct non-static data member named by the designated initializer is initialized from the corresponding brace-or-equals initializer that follows the designator. Narrowing conversions are prohibited. Designated initializer can be used to initialize a [union](union "cpp/language/union") into the state other than the first. Only one initializer may be provided for a union. ``` union u { int a; const char* b; }; u f = {.b = "asdf"}; // OK, active member of the union is b u g = {.a = 1, .b = "asdf"}; // Error, only one initializer may be provided ``` For a non-union aggregate, elements for which a designated initializer is not provided are initialized the same as described above for when the number of initializer clauses is less than the number of members (default member initializers where provided, empty list-initialization otherwise): ``` struct A { string str; int n = 42; int m = -1; }; A{.m = 21} // Initializes str with {}, which calls the default constructor // then initializes n with = 42 // then initializes m with = 21 ``` If the aggregate that is initialized with a designated initializer clause has an anonymous union member, the corresponding designated initializer must name one of the members of that anonymous union. Note: out-of-order designated initialization, nested designated initialization, mixing of designated initializers and regular initializers, and designated initialization of arrays are all supported in the [C programming language](https://en.cppreference.com/w/c/language/struct_initialization "c/language/struct initialization"), but are not allowed in C++. ``` struct A { int x, y; }; struct B { struct A a; }; struct A a = {.y = 1, .x = 2}; // valid C, invalid C++ (out of order) int arr[3] = {[1] = 5}; // valid C, invalid C++ (array) struct B b = {.a.x = 0}; // valid C, invalid C++ (nested) struct A a = {.x = 1, 2}; // valid C, invalid C++ (mixed) ``` | (since C++20) | ### Character arrays Arrays of ordinary character types (`char`, `signed char`, `unsigned char`), `char8_t` (since C++20), `char16_t`, `char32_t` (since C++11), or `wchar_t` can be initialized from ordinary [string literals](string_literal "cpp/language/string literal"), UTF-8 string literals (since C++20), UTF-16 string literals, UTF-32 string literals (since C++11), or wide string literals, respectively, optionally enclosed in braces. Additionally, an array of `char` or `unsigned char` may be initialized by a UTF-8 string literal, optionally enclosed in braces. (since C++20) Successive characters of the string literal (which includes the implicit terminating null character) initialize the elements of the array. If the size of the array is specified and it is larger than the number of characters in the string literal, the remaining characters are zero-initialized. ``` char a[] = "abc"; // equivalent to char a[4] = {'a', 'b', 'c', '\0'}; // unsigned char b[3] = "abc"; // Error: initializer string too long unsigned char b[5]{"abc"}; // equivalent to unsigned char b[5] = {'a', 'b', 'c', '\0', '\0'}; wchar_t c[] = {L"кошка"}; // optional braces // equivalent to wchar_t c[6] = {L'к', L'о', L'ш', L'к', L'а', L'\0'}; ``` ### Notes An aggregate class or array may include non-aggregate public bases (since C++17), members, or elements, which are initialized as described above (e.g. copy-initialization from the corresponding initializer clause). Until C++11, narrowing conversions were permitted in aggregate initialization, but they are no longer allowed. Until C++11, aggregate initialization could only be used in variable definition, and could not be used in a [constructor initializer list](constructor "cpp/language/constructor"), a [new-expression](new "cpp/language/new"), or temporary object creation due to syntax restrictions. In C, character array of size one less than the size of the string literal may be initialized from a string literal; the resulting array is not null-terminated. This is not allowed in C++. ### Example ``` #include <string> #include <array> #include <cstdio> struct S { int x; struct Foo { int i; int j; int a[3]; } b; }; int main() { S s1 = {1, {2, 3, {4, 5, 6}}}; S s2 = {1, 2, 3, 4, 5, 6}; // same, but with brace elision S s3{1, {2, 3, {4, 5, 6}}}; // same, using direct-list-initialization syntax S s4{1, 2, 3, 4, 5, 6}; // error until CWG 1270: // brace elision only allowed with equals sign int ar[] = {1, 2, 3}; // ar is int[3] // char cr[3] = {'a', 'b', 'c', 'd'}; // too many initializer clauses char cr[3] = {'a'}; // array initialized as {'a', '\0', '\0'} int ar2d1[2][2] = {{1, 2}, {3, 4}}; // fully-braced 2D array: {1, 2} // {3, 4} int ar2d2[2][2] = {1, 2, 3, 4}; // brace elision: {1, 2} // {3, 4} int ar2d3[2][2] = {{1}, {2}}; // only first column: {1, 0} // {2, 0} std::array<int, 3> std_ar2{{1, 2, 3}}; // std::array is an aggregate std::array<int, 3> std_ar1 = {1, 2, 3}; // brace-elision okay // int ai[] = {1, 2.0}; // narrowing conversion from double to int: // error in C++11, okay in C++03 std::string ars[] = {std::string("one"), // copy-initialization "two", // conversion, then copy-initialization {'t', 'h', 'r', 'e', 'e'}}; // list-initialization union U { int a; const char* b; }; U u1 = {1}; // OK, first member of the union // U u2 = {0, "asdf"}; // error: too many initializers for union // U u3 = {"asdf"}; // error: invalid conversion to int [](...) { std::puts("Garbage unused variables... Done."); } ( s1, s2, s3, s4, ar, cr, ar2d1, ar2d2, ar2d3, std_ar2, std_ar1, u1 ); } // aggregate struct base1 { int b1, b2 = 42; }; // non-aggregate struct base2 { base2() : b3(42) {} int b3; }; // aggregate in C++17 struct derived : base1, base2 { int d; }; derived d1{{1, 2}, {}, 4}; // d1.b1 = 1, d1.b2 = 2, d1.b3 = 42, d1.d = 4 derived d2{{}, {}, 4}; // d2.b1 = 0, d2.b2 = 42, d2.b3 = 42, d2.d = 4 ``` Output: ``` Garbage unused variables... Done. ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 413](https://cplusplus.github.io/CWG/issues/413.html) | C++98 | anonymous bit-fields were initialized in aggregate initialization | they are ignored | | [CWG 737](https://cplusplus.github.io/CWG/issues/737.html) | C++98 | when a character array is initialized with a string literalhaving fewer characters than the array size, the characterelements after the trailing `'\0'` was uninitialized | they are zero-initialized | | [CWG 1270](https://cplusplus.github.io/CWG/issues/1270.html) | C++11 | brace elision was only allowed to be used in copy-list-initialization | allowed elsewhere | | [CWG 1518](https://cplusplus.github.io/CWG/issues/1518.html) | C++11 | a class that declares an explicit default constructor orhas inherited constructors should could be an aggregate | it is not an aggregate | | [CWG 1622](https://cplusplus.github.io/CWG/issues/1622.html) | C++98 | a union could not be initialized with `{}` | allowed | | [CWG 2272](https://cplusplus.github.io/CWG/issues/2272.html) | C++98 | a non-static reference member that is not explicitlyinitialized was copy-initialized from an empty initializer list | the program is ill-formed in this case | | [P2513R3](https://wg21.link/P2513R3) | C++20 | a UTF-8 string literal could not initialize an array of `char`or `unsigned char`, which was incompatible with C or C++17 | such initialization is valid | ### See also * [copy elision](copy_elision "cpp/language/copy elision") * [initialization](initialization "cpp/language/initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [list initialization](list_initialization "cpp/language/list initialization") + [reference initialization](reference_initialization "cpp/language/reference initialization") + [value initialization](value_initialization "cpp/language/value initialization") + [zero initialization](zero_initialization "cpp/language/zero initialization") | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/struct_initialization "c/language/struct initialization") for Struct and union initialization |
programming_docs
cpp Default initialization Default initialization ====================== This is the initialization performed when an object is constructed with no initializer. ### Syntax | | | | | --- | --- | --- | | T object `;` | (1) | | | `new` T | (2) | | ### Explanation Default initialization is performed in three situations: 1) when a variable with automatic, static, or thread-local [storage duration](storage_duration "cpp/language/storage duration") is declared with no initializer; 2) when an object with dynamic storage duration is created by a [new-expression](new "cpp/language/new") with no initializer; 3) when a base class or a non-static data member is not mentioned in a [constructor initializer list](constructor "cpp/language/constructor") and that constructor is called. The effects of default initialization are: * if `T` is a (possibly cv-qualified) non-POD (until C++11) class type, the constructors are considered and subjected to [overload resolution](overload_resolution "cpp/language/overload resolution") against the empty argument list. The constructor selected (which is one of the [default constructors](default_constructor "cpp/language/default constructor")) is called to provide the initial value for the new object; * if `T` is an array type, every element of the array is default-initialized; * otherwise, no initialization is performed: the objects with automatic storage duration (and their subobjects) contain indeterminate values. | | | | --- | --- | | Only (possibly cv-qualified) non-POD class types (or arrays thereof) with automatic storage duration were considered to be default-initialized when no initializer is used. Scalars and POD types with dynamic storage duration were considered to be not initialized (since C++11, this situation was reclassified as a form of default initialization). | (until C++11) | #### Default initialization of a const object If a program calls for the default-initialization of an object of a [const](cv "cpp/language/cv")-qualified type `T`, T shall be a *const-default-constructible* class type or array thereof. A class type `T` is const-default-constructible if default initialization of `T` would invoke a user-provided constructor of `T` (not inherited from a base class) (since C++11) or if. | | | | --- | --- | | * each direct non-static data member `M` of `T` is of class type `X` (or array thereof), `X` is const-default-constructible, and * `T` has no direct [variant members](union#Union-like_classes "cpp/language/union"), and | (until C++11) | | * each direct non-variant non-static data member `M` of `T` has a [default member initializer](data_members#Member_initialization "cpp/language/data members") or, if `M` is of class type `X` (or array thereof), `X` is const-default-constructible, * if `T` is a union with at least one non-static data member, exactly one [variant member](union#Union-like_classes "cpp/language/union") has a default member initializer, * if `T` is not a union, for each anonymous union member with at least one non-static data member (if any), exactly one non-static data member has a default member initializer, and | (since C++11) | each potentially constructed base class of `T` is const-default-constructible. #### Read from an indeterminate byte Use of an indeterminate value obtained by default-initializing a non-class variable of any type is [undefined behavior](ub "cpp/language/ub") (in particular, it may be a [trap representation](object#Object_representation_and_value_representation "cpp/language/object")), except in the following cases: * if an indeterminate value of type `unsigned char` or [`std::byte`](../types/byte "cpp/types/byte") (since C++17) is assigned to another variable of type (possibly cv-qualified) `unsigned char` or [`std::byte`](../types/byte "cpp/types/byte") (since C++17) (the value of the variable becomes indeterminate, but the behavior is not undefined); * if an indeterminate value of type `unsigned char` or [`std::byte`](../types/byte "cpp/types/byte") (since C++17) is used to initialize another variable of type (possibly cv-qualified) `unsigned char` or [`std::byte`](../types/byte "cpp/types/byte") (since C++17); * if an indeterminate value of type `unsigned char` or [`std::byte`](../types/byte "cpp/types/byte") (since C++17) results from + the second or third operand of a conditional expression, + the right operand of the comma operator, + the operand of a cast or conversion to (possibly cv-qualified) `unsigned char` or [`std::byte`](../types/byte "cpp/types/byte") (since C++17), + a discarded-value expression. ``` int f(bool b) { int x; // OK: the value of x is indeterminate int y = x; // undefined behavior unsigned char c; // OK: the value of c is indeterminate unsigned char d = c; // OK: the value of d is indeterminate int e = d; // undefined behavior return b ? d : 0; // undefined behavior if b is true } ``` ### Notes Default initialization of non-class variables with automatic and dynamic storage duration produces objects with indeterminate values (static and thread-local objects get [zero initialized](zero_initialization "cpp/language/zero initialization")). References and const scalar objects cannot be default-initialized. ### Example ``` #include <string> struct T1 { int mem; }; struct T2 { int mem; T2() { } // "mem" is not in the initializer list }; int n; // static non-class, a two-phase initialization is done: // 1) zero initialization initializes n to zero // 2) default initialization does nothing, leaving n being zero int main() { int n; // non-class, the value is indeterminate std::string s; // class, calls default ctor, the value is "" (empty string) std::string a[2]; // array, default-initializes the elements, the value is {"", ""} // int& r; // error: a reference // const int n; // error: a const non-class // const T1 t1; // error: const class with implicit default ctor T1 t1; // class, calls implicit default ctor const T2 t2; // const class, calls the user-provided default ctor // t2.mem is default-initialized (to indeterminate value) } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 178](https://cplusplus.github.io/CWG/issues/178.html) | C++98 | there's no value-initialization; empty initializer invoke default-init(though `new T()` also performs zero-init) | empty initializer invoke value-init | | [CWG 253](https://cplusplus.github.io/CWG/issues/253.html) | C++98 | default initialization of a const object could notcall an implicitly declared default constructor | allowed if all subobjects are initialized | | [CWG 616](https://cplusplus.github.io/CWG/issues/616.html) | C++98 | lvalue to rvalue conversion of any uninitialized object was always UB | indeterminate `unsigned char` is allowed | | [CWG 1787](https://cplusplus.github.io/CWG/issues/1787.html) | C++98 | read from an indeterminate `unsigned char` cached in a register was UB | made well-defined | ### See also * [converting constructor](converting_constructor "cpp/language/converting constructor") * [default constructor](default_constructor "cpp/language/default constructor") * [`explicit`](explicit "cpp/language/explicit") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [copy initialization](copy_initialization "cpp/language/copy initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [list initialization](list_initialization "cpp/language/list initialization") + [reference initialization](reference_initialization "cpp/language/reference initialization") + [value initialization](value_initialization "cpp/language/value initialization") + [zero initialization](zero_initialization "cpp/language/zero initialization") * [`new`](new "cpp/language/new") cpp Order of evaluation Order of evaluation =================== Order of evaluation of any part of any expression, including order of evaluation of function arguments is *unspecified* (with some exceptions listed below). The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again. There is no concept of left-to-right or right-to-left evaluation in C++. This is not to be confused with left-to-right and right-to-left associativity of operators: the expression `a() + b() + c()` is parsed as `(a() + b()) + c()` due to left-to-right associativity of operator+, but `c()` may be evaluated first, last, or between `a()` or `b()` at run time: ``` #include <cstdio> int a() { return std::puts("a"); } int b() { return std::puts("b"); } int c() { return std::puts("c"); } void z(int, int, int) {} int main() { z(a(), b(), c()); // all 6 permutations of output are allowed return a() + b() + c(); // all 6 permutations of output are allowed } ``` Possible output: ``` b c a c a b ``` ### "Sequenced before" rules (since C++11) #### Evaluation of Expressions Evaluation of each expression includes: * *value computations*: calculation of the value that is returned by the expression. This may involve determination of the identity of the object (glvalue evaluation, e.g. if the expression returns a reference to some object) or reading the value previously assigned to an object (prvalue evaluation, e.g. if the expression returns a number, or some other value) * Initiation of *side effects*: access (read or write) to an object designated by a volatile glvalue, modification (writing) to an object, calling a library I/O function, or calling a function that does any of those operations. #### Ordering *sequenced before* is an asymmetric, transitive, pair-wise relationship between evaluations within the same thread. * If A is sequenced before B (or, equivalently, B is *sequenced after* A), then evaluation of A will be complete before evaluation of B begins. * If A is not sequenced before B and B is sequenced before A, then evaluation of B will be complete before evaluation of A begins. * If A is not sequenced before B and B is not sequenced before A, then two possibilities exist: + evaluations of A and B are *unsequenced*: they may be performed in any order and may overlap (within a single thread of execution, the compiler may interleave the CPU instructions that comprise A and B) + evaluations of A and B are *indeterminately sequenced*: they may be performed in any order but may not overlap: either A will be complete before B, or B will be complete before A. The order may be the opposite the next time the same expression is evaluated. #### Rules 1) Each value computation and side effect of a [full-expression](expressions#Full-expressions "cpp/language/expressions") is sequenced before each value computation and side effect of the next full-expression. 2) The value computations (but not the side effects) of the operands to any [operator](expressions#Operators "cpp/language/expressions") are sequenced before the value computation of the result of the operator (but not its side effects). 3) When calling a function (whether or not the function is inline, and whether or not explicit function call syntax is used), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function. 4) The value computation of the built-in [post-increment and post-decrement](operator_incdec#Built-in_postfix_operators "cpp/language/operator incdec") operators is sequenced before its side effect. 5) The side effect of the built-in [pre-increment and pre-decrement](operator_incdec#Built-in_prefix_operators "cpp/language/operator incdec") operators is sequenced before its value computation (implicit rule due to definition as compound assignment) 6) Every value computation and side effect of the first (left) argument of the built-in [logical](operator_logical "cpp/language/operator logical") AND operator `&&` and the built-in logical OR operator `||` is sequenced before every value computation and side effect of the second (right) argument. 7) Every value computation and side effect associated with the first expression in the [conditional operator](operator_other#Conditional_operator "cpp/language/operator other") `?:` is sequenced before every value computation and side effect associated with the second or third expression. 8) The side effect (modification of the left argument) of the built-in [assignment](operator_assignment#Builtin_direct_assignment "cpp/language/operator assignment") operator and of all built-in [compound](operator_assignment#Builtin_compound_assignment "cpp/language/operator assignment") assignment operators is sequenced after the value computation (but not the side effects) of both left and right arguments, and is sequenced before the value computation of the assignment expression (that is, before returning the reference to the modified object) 9) Every value computation and side effect of the first (left) argument of the built-in [comma operator](operator_other#Built-in_comma_operator "cpp/language/operator other") `,` is sequenced before every value computation and side effect of the second (right) argument. 10) In [list-initialization](list_initialization "cpp/language/list initialization"), every value computation and side effect of a given initializer clause is sequenced before every value computation and side effect associated with any initializer clause that follows it in the brace-enclosed comma-separated list of initializers. 11) A function call that is not sequenced before or sequenced after another expression evaluation outside of the function (possibly another function call) is indeterminately sequenced with respect to that evaluation (the program must behave [as if](as_if "cpp/language/as if") the CPU instructions that constitute a function call were not interleaved with instructions constituting evaluations of other expressions, including other function calls, even if the function was inlined). | | | | --- | --- | | The rule 11 has one exception: function calls made by a standard library algorithm executing under [`std::execution::par_unseq`](../algorithm/execution_policy_tag_t "cpp/algorithm/execution policy tag t") execution policy are unsequenced and may be arbitrarily interleaved with each other. | (since C++17) | 12) The call to the allocation function ([`operator new`](../memory/new/operator_new "cpp/memory/new/operator new")) is indeterminately sequenced with respect to (until C++17)sequenced before (since C++17) the evaluation of the constructor arguments in a [new-expression](new "cpp/language/new") 13) When returning from a function, copy-initialization of the temporary that is the result of evaluating the function call is sequenced before the destruction of all temporaries at the end of the operand of the [return statement](return "cpp/language/return"), which, in turn, is sequenced before the destruction of local variables of the block enclosing the return statement. | | | | --- | --- | | 14) In a function-call expression, the expression that names the function is sequenced before every argument expression and every default argument. 15) In a function call, value computations and side effects of the initialization of every parameter are indeterminately sequenced with respect to value computations and side effects of any other parameter. 16) Every overloaded operator obeys the sequencing rules of the built-in operator it overloads when called using operator notation. 17) In a subscript expression `E1[E2]`, every value computation and side effect of E1 is sequenced before every value computation and side effect of E2 18) In a pointer-to-member expression `E1.*E2` or `E1->*E2`, every value computation and side effect of E1 is sequenced before every value computation and side effect of E2 (unless the dynamic type of E1 does not contain the member to which E2 refers) 19) In a shift operator expression `E1 << E2` and `E1 >> E2`, every value computation and side effect of E1 is sequenced before every value computation and side effect of E2 20) In every simple assignment expression `E1 = E2` and every compound assignment expression `E1 @= E2`, every value computation and side effect of E2 is sequenced before every value computation and side effect of E1 21) Every expression in a comma-separated list of expressions in a parenthesized initializer is evaluated as if for a function call (indeterminately-sequenced) | (since C++17) | #### Undefined behavior 1) If a side effect on a memory location is unsequenced relative to another side effect on the same memory location, [the behavior is undefined](ub "cpp/language/ub"). ``` i = ++i + 2; // well-defined i = i++ + 2; // undefined behavior until C++17 f(i = -2, i = -2); // undefined behavior until C++17 f(++i, ++i); // undefined behavior until C++17, unspecified after C++17 i = ++i + i++; // undefined behavior ``` 2) If a side effect on a memory location is unsequenced relative to a value computation using the value of any object in the same memory location, [the behavior is undefined](ub "cpp/language/ub"). ``` cout << i << i++; // undefined behavior until C++17 a[i] = i++; // undefined behavior until C++17 n = ++i + i; // undefined behavior ``` ### Sequence point rules (until C++11) #### Pre-C++11 Definitions Evaluation of an expression might produce side effects, which are: accessing an object designated by a volatile lvalue, modifying an object, calling a library I/O function, or calling a function that does any of those operations. A *sequence point* is a point in the execution sequence where all side effects from the previous evaluations in the sequence are complete, and no side effects of the subsequent evaluations started. #### Pre-C++11 Rules 1) There is a sequence point at the end of each [full-expression](expressions#Full-expressions "cpp/language/expressions") (typically, at the semicolon). 2) When calling a function (whether or not the function is inline and whether or not function call syntax was used), there is a sequence point after the evaluation of all function arguments (if any) which takes place before execution of any expressions or statements in the function body. 3) There is a sequence point after the copying of a returned value of a function and before the execution of any expressions outside the function. 4) Once the execution of a function begins, no expressions from the calling function are evaluated until execution of the called function has completed (functions cannot be interleaved). 5) In the evaluation of each of the following four expressions, using the built-in (non-overloaded) operators, there is a sequence point after the evaluation of the expression `a`. ``` a && b a || b a ? b : c a , b ``` #### Pre-C++11 Undefined behavior 1) Between the previous and next sequence point, the value of any object in a memory location must be modified at most once by the evaluation of an expression, otherwise [the behavior is undefined](ub "cpp/language/ub"). ``` i = ++i + i++; // undefined behavior i = i++ + 1; // undefined behavior i = ++i + 1; // undefined behavior ++ ++i; // undefined behavior f(++i, ++i); // undefined behavior f(i = -1, i = -1); // undefined behavior ``` 2) Between the previous and next sequence point, for any object in a memory location, its prior value that is modified by the evaluation of the expression must be accessed only to determine the value to be stored. If it is accessed in any other way, [the behavior is undefined](ub "cpp/language/ub"). ``` cout << i << i++; // undefined behavior a[i] = i++; // undefined behavior ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1885](https://cplusplus.github.io/CWG/issues/1885.html) | C++11 | sequencing of the destruction of automaticvariables on function return was not explicit | sequencing rules added | | [CWG 1949](https://cplusplus.github.io/CWG/issues/1949.html) | C++98 | "sequenced after" was not defined but used in the C++ standard | defined as the inverseof "sequenced before" | | [CWG 2146](https://cplusplus.github.io/CWG/issues/2146.html) | C++98 | the cases involving undefine behaviors did not consider bit-fields | considered | ### References * C++20 standard (ISO/IEC 14882:2020): + 6.9.1 Program execution [intro.execution] + 7.6.1.5 Increment and decrement [expr.post.incr] + 7.6.2.7 New [expr.new] + 7.6.14 Logical AND operator [expr.log.and] + 7.6.15 Logical OR operator [expr.log.or] + 7.6.16 Conditional operator [expr.cond] + 7.6.19 Assignment and compound assignment operators [expr.ass] + 7.6.20 Comma operator [expr.comma] + 9.4.4 List-initialization [dcl.init.list] * C++17 standard (ISO/IEC 14882:2017): + 4.6 Program execution [intro.execution] + 8.2.6 Increment and decrement [expr.post.incr] + 8.3.4 New [expr.new] + 8.14 Logical AND operator [expr.log.and] + 8.15 Logical OR operator [expr.log.or] + 8.16 Conditional operator [expr.cond] + 8.18 Assignment and compound assignment operators [expr.ass] + 8.19 Comma operator [expr.comma] + 11.6.4 List-initialization [dcl.init.list] * C++14 standard (ISO/IEC 14882:2014): + 1.9 Program execution [intro.execution] + 5.2.6 Increment and decrement [expr.post.incr] + 5.3.4 New [expr.new] + 5.14 Logical AND operator [expr.log.and] + 5.15 Logical OR operator [expr.log.or] + 5.16 Conditional operator [expr.cond] + 5.17 Assignment and compound assignment operators [expr.ass] + 5.18 Comma operator [expr.comma] + 8.5.4 List-initialization [dcl.init.list] * C++11 standard (ISO/IEC 14882:2011): + 1.9 Program execution [intro.execution] + 5.2.6 Increment and decrement [expr.post.incr] + 5.3.4 New [expr.new] + 5.14 Logical AND operator [expr.log.and] + 5.15 Logical OR operator [expr.log.or] + 5.16 Conditional operator [expr.cond] + 5.17 Assignment and compound assignment operators [expr.ass] + 5.18 Comma operator [expr.comma] + 8.5.4 List-initialization [dcl.init.list] ### See also * [Operator precedence](operator_precedence "cpp/language/operator precedence") which defines how expressions are built from their source code representation. | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/eval_order "c/language/eval order") for Order of evaluation |
programming_docs
cpp Constraints and concepts (since C++20) Constraints and concepts (since C++20) ====================================== *This page describes the core language feature adopted for C++20. For named type requirements used in the specification of the standard library, see [named requirements](../named_req "cpp/named req"). For the Concepts TS version of this feature, see [here](https://en.cppreference.com/w/cpp/experimental/constraints "cpp/experimental/constraints").* ***Temporary notice**: the `requires` expression section has been moved to [its own page](requires "cpp/language/requires")* [Class templates](class_template "cpp/language/class template"), [function templates](function_template "cpp/language/function template"), and non-template functions (typically members of class templates) may be associated with a *constraint*, which specifies the requirements on template arguments, which can be used to select the most appropriate function overloads and template specializations. Named sets of such [requirements](requires "cpp/language/requires") are called *concepts*. Each concept is a predicate, evaluated at compile time, and becomes a part of the interface of a template where it is used as a constraint: ``` #include <string> #include <cstddef> #include <concepts> // Declaration of the concept "Hashable", which is satisfied by any type 'T' // such that for values 'a' of type 'T', the expression std::hash<T>{}(a) // compiles and its result is convertible to std::size_t template<typename T> concept Hashable = requires(T a) { { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>; }; struct meow {}; // Constrained C++20 function template: template<Hashable T> void f(T) {} // // Alternative ways to apply the same constraint: // template<typename T> // requires Hashable<T> // void f(T) {} // // template<typename T> // void f(T) requires Hashable<T> {} // // void f(Hashable auto /*parameterName*/) {} int main() { using std::operator""s; f("abc"s); // OK, std::string satisfies Hashable // f(meow{}); // Error: meow does not satisfy Hashable } ``` Violations of constraints are detected at compile time, early in the template instantiation process, which leads to easy to follow error messages: ``` std::list<int> l = {3, -1, 10}; std::sort(l.begin(), l.end()); // Typical compiler diagnostic without concepts: // invalid operands to binary expression ('std::_List_iterator<int>' and // 'std::_List_iterator<int>') // std::__lg(__last - __first) * 2); // ~~~~~~ ^ ~~~~~~~ // ... 50 lines of output ... // // Typical compiler diagnostic with concepts: // error: cannot call std::sort with std::_List_iterator<int> // note: concept RandomAccessIterator<std::_List_iterator<int>> was not satisfied ``` The intent of concepts is to model semantic categories (Number, Range, RegularFunction) rather than syntactic restrictions (HasPlus, Array). According to [ISO C++ core guideline T.20](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t20-avoid-concepts-without-meaningful-semantics), "The ability to specify meaningful semantics is a defining characteristic of a true concept, as opposed to a syntactic constraint." ### Concepts A concept is a named set of [requirements](requires "cpp/language/requires"). The definition of a concept must appear at namespace scope. The definition of a concept has the form. | | | | | --- | --- | --- | | `template` `<` template-parameter-list `>` `concept` concept-name `=` constraint-expression`;` | | | ``` // concept template<class T, class U> concept Derived = std::is_base_of<U, T>::value; ``` Concepts cannot recursively refer to themselves and cannot be constrained: ``` template<typename T> concept V = V<T*>; // error: recursive concept template<class T> concept C1 = true; template<C1 T> concept Error1 = true; // Error: C1 T attempts to constrain a concept definition template<class T> requires C1<T> concept Error2 = true; // Error: the requires-clause attempts to constrain a concept ``` Explicit instantiations, explicit specializations, or partial specializations of concepts are not allowed (the meaning of the original definition of a constraint cannot be changed). Concepts can be named in an id-expression. The value of the id-expression is `true` if the constraint expression is satisfied, and `false` otherwise. Concepts can also be named in a type-constraint, as part of. * [type template parameter declaration](template_parameters#Type_template_parameter "cpp/language/template parameters"), * [placeholder type specifier](auto "cpp/language/auto"), * [compound requirement](#Compound_Requirements). In a type-constraint, a concept takes one less template argument than its parameter list demands, because the contextually deduced type is implicitly used as the first argument of the concept. ``` template<class T, class U> concept Derived = std::is_base_of<U, T>::value; template<Derived<Base> T> void f(T); // T is constrained by Derived<T, Base> ``` ### Constraints A constraint is a sequence of logical operations and operands that specifies requirements on template arguments. They can appear within [requires expressions](requires "cpp/language/requires") or directly as bodies of concepts. There are three types of constraints: 1) conjunctions 2) disjunctions 3) atomic constraints The constraint associated with a declaration are determined by [normalizing](#Constraint_normalization) a logical AND expression whose operands are in the following order: 1. the constraint expression introduced for each constrained [type template parameter](template_parameters#Type_template_parameter "cpp/language/template parameters") or non-type template parameter declared with a constrained [placeholder type](auto "cpp/language/auto"), in order of appearance; 2. the constraint expression in the [requires clause](constraints#Requires_clauses "cpp/language/constraints") after the template parameter list; 3. the constraint expression introduced for each parameter with constrained [placeholder type](auto "cpp/language/auto") in a [abbreviated function template declaration](function_template#Abbreviated_function_template "cpp/language/function template"); 4. the constraint expression in the trailing [requires clause](constraints#Requires_clauses "cpp/language/constraints"). This order determines the order in which constraints are instantiated when checking for satisfaction. A constrained declaration may only be redeclared using the same syntactic form. No diagnostic is required: ``` template<Incrementable T> void f(T) requires Decrementable<T>; template<Incrementable T> void f(T) requires Decrementable<T>; // OK, redeclaration template<typename T> requires Incrementable<T> && Decrementable<T> void f(T); // ill-formed, no diagnostic required // the following two declarations have different constraints: // the first declaration has Incrementable<T> && Decrementable<T> // the second declaration has Decrementable<T> && Incrementable<T> // Even though they are logically equivalent. template<Incrementable T> void g(T) requires Decrementable<T>; template<Decrementable T> void g(T) requires Incrementable<T>; // ill-formed, no diagnostic required ``` #### Conjunctions The conjunction of two constraints is formed by using the `&&` operator in the constraint expression: ``` template<class T> concept Integral = std::is_integral<T>::value; template<class T> concept SignedIntegral = Integral<T> && std::is_signed<T>::value; template<class T> concept UnsignedIntegral = Integral<T> && !SignedIntegral<T>; ``` A conjunction of two constraints is satisfied only if both constraints are satisfied. Conjunctions are evaluated left to right and short-circuited (if the left constraint is not satisfied, template argument substitution into the right constraint is not attempted: this prevents failures due to substitution outside of immediate context). ``` template<typename T> constexpr bool get_value() { return T::value; } template<typename T> requires (sizeof(T) > 1 && get_value<T>()) void f(T); // #1 void f(int); // #2 void g() { f('A'); // OK, calls #2. When checking the constraints of #1, // 'sizeof(char) > 1' is not satisfied, so get_value<T>() is not checked } ``` #### Disjunctions The disjunction of two constraints is formed by using the `||` operator in the constraint expression. A disjunction of two constraints is satisfied if either constraint is satisfied. Disjunctions are evaluated left to right and short-circuited (if the left constraint is satisfied, template argument substitution into the right constraint is not attempted). ``` template<class T = void> requires EqualityComparable<T> || Same<T, void> struct equal_to; ``` #### Atomic constraints An atomic constraint consists of an expression `E` and a mapping from the template parameters that appear within `E` to template arguments involving the template parameters of the constrained entity, called its *parameter mapping*. Atomic constraints are formed during [constraint normalization](#Constraint_normalization). `E` is never a logical AND or logical OR expression (those form conjunctions and disjunctions, respectively). Satisfaction of an atomic constraint is checked by substituting the parameter mapping and template arguments into the expression `E`. If the substitution results in an invalid type or expression, the constraint is not satisfied. Otherwise, `E`, after any lvalue-to-rvalue conversion, shall be a prvalue constant expression of type `bool` , and the constraint is satisfied if and only if it evaluates to `true`. The type of `E` after substitution must be exactly `bool`. No conversion is permitted: ``` template<typename T> struct S { constexpr operator bool() const { return true; } }; template<typename T> requires (S<T>{}) void f(T); // #1 void f(int); // #2 void g() { f(0); // error: S<int>{} does not have type bool when checking #1, // even though #2 is a better match } ``` Two atomic constraints are considered *identical* if they are formed from the same expression at the source level and their parameter mappings are equivalent. ``` template<class T> constexpr bool is_meowable = true; template<class T> constexpr bool is_cat = true; template<class T> concept Meowable = is_meowable<T>; template<class T> concept BadMeowableCat = is_meowable<T> && is_cat<T>; template<class T> concept GoodMeowableCat = Meowable<T> && is_cat<T>; template<Meowable T> void f1(T); // #1 template<BadMeowableCat T> void f1(T); // #2 template<Meowable T> void f2(T); // #3 template<GoodMeowableCat T> void f2(T); // #4 void g() { f1(0); // error, ambiguous: // the is_meowable<T> in Meowable and BadMeowableCat forms distinct atomic // constraints that are not identical (and so do not subsume each other) f2(0); // OK, calls #4, more constrained than #3 // GoodMeowableCat got its is_meowable<T> from Meowable } ``` #### Constraint normalization *Constraint normalization* is the process that transforms a constraint expression into a sequence of conjunctions and disjunctions of atomic constraints. The *normal form* of an expression is defined as follows: * The normal form of an expression `(E)` is the normal form of `E`; * The normal form of an expression `E1 && E2` is the conjunction of the normal forms of `E1` and `E2`. * The normal form of an expression `E1 || E2` is the disjunction of the normal forms of `E1` and `E2`. * The normal form of an expression `C<A1, A2, ... , AN>`, where `C` names a concept, is the normal form of the constraint expression of `C`, after substituting A1, A2, ... , AN for `C`'s respective template parameters in the parameter mappings of each atomic constraint of C. If any such substitution into the parameter mappings results in an invalid type or expression, the program is ill-formed, no diagnostic required. ``` template<typename T> concept A = T::value || true; template<typename U> concept B = A<U*>; // OK: normalized to the disjunction of // - T::value (with mapping T -> U*) and // - true (with an empty mapping). // No invalid type in mapping even though // T::value is ill-formed for all pointer types template<typename V> concept C = B<V&>; // Normalizes to the disjunction of // - T::value (with mapping T-> V&*) and // - true (with an empty mapping). // Invalid type V&* formed in mapping => ill-formed NDR ``` * The normal form of any other expression `E` is the atomic constraint whose expression is `E` and whose parameter mapping is the identity mapping. This includes all [fold expressions](fold "cpp/language/fold"), even those folding over the `&&` or `||` operators. User-defined overloads of `&&` or `||` have no effect on constraint normalization. ### Requires clauses The keyword [`requires`](../keyword/requires "cpp/keyword/requires") is used to introduce a *requires-clause*, which specifies constraints on template arguments or on a function declaration. ``` template<typename T> void f(T&&) requires Eq<T>; // can appear as the last element of a function declarator template<typename T> requires Addable<T> // or right after a template parameter list T add(T a, T b) { return a + b; } ``` In this case, the keyword *requires* must be followed by some constant expression (so it's possible to write `requires true`), but the intent is that a named concept (as in the example above) or a conjunction/disjunction of named concepts or a {{rlp|requires|requires expression} is used. The expression must have one of the following forms: * a [primary expression](expressions#Primary_expressions "cpp/language/expressions"), e.g. `Swappable<T>`, `[std::is\_integral](http://en.cppreference.com/w/cpp/types/is_integral)<T>::value`, `([std::is\_object\_v](http://en.cppreference.com/w/cpp/types/is_object)<Args> && ...)`, or any parenthesized expression * a sequence of primary expressions joined with the operator `&&` * a sequence of aforementioned expressions joined with the operator `||` ``` template<class T> constexpr bool is_meowable = true; template<class T> constexpr bool is_purrable() { return true; } template<class T> void f(T) requires is_meowable<T>; // OK template<class T> void g(T) requires is_purrable<T>(); // error, is_purrable<T>() is not a primary expression template<class T> void h(T) requires (is_purrable<T>()); // OK ``` ### Partial ordering of constraints Before any further analysis, constraints are [normalized](#Constraint_normalization) by substituting the body of every named concept and every {{rlp|requires|requires expression} until what is left is a sequence of conjunctions and disjunctions on atomic constraints. A constraint `P` is said to *subsume* constraint `Q` if it can be proven that `P` [implies](https://en.wikipedia.org/wiki/Logical_consequence "enwiki:Logical consequence") `Q` up to the identity of atomic constraints in P and Q. (Types and expressions are not analyzed for equivalence: `N > 0` does not subsume `N >= 0`). Specifically, first `P` is converted to disjunctive normal form and `Q` is converted to conjunctive normal form. `P` subsumes `Q` if and only if: * every disjunctive clause in the disjunctive normal form of `P` subsumes every conjunctive clause in the conjunctive normal form of `Q`, where * a disjunctive clause subsumes a conjunctive clause if and only if there is an atomic constraint `U` in the disjunctive clause and an atomic constraint `V` in the conjunctive clause such that `U` subsumes `V`; * an atomic constraint `A` subsumes an atomic constraint `B` if and only if they are identical using the rules described [above](#Atomic_constraints). Subsumption relationship defines partial order of constraints, which is used to determine: * the best viable candidate for a non-template function in [overload resolution](overload_resolution "cpp/language/overload resolution") * the [address of a non-template function](overloaded_address "cpp/language/overloaded address") in an overload set * the best match for a template template argument * partial ordering of class template specializations * [partial ordering](function_template#Function_template_overloading "cpp/language/function template") of function templates If declarations `D1` and `D2` are constrained and `D1`'s associated constraints subsume `D2`'s associated constraints (or if `D2` is unconstrained), then `D1` is said to be *at least as constrained* as `D2`. If `D1` is at least as constrained as `D2`, and `D2` is not at least as constrained as `D1`, then `D1` is *more constrained* than `D2`. ``` template<typename T> concept Decrementable = requires(T t) { --t; }; template<typename T> concept RevIterator = Decrementable<T> && requires(T t) { *t; }; // RevIterator subsumes Decrementable, but not the other way around template<Decrementable T> void f(T); // #1 template<RevIterator T> void f(T); // #2, more constrained than #1 f(0); // int only satisfies Decrementable, selects #1 f((int*)0); // int* satisfies both constraints, selects #2 as more constrained template<class T> void g(T); // #3 (unconstrained) template<Decrementable T> void g(T); // #4 g(true); // bool does not satisfy Decrementable, selects #3 g(0); // int satisfies Decrementable, selects #4 because it is more constrained template<typename T> concept RevIterator2 = requires(T t) { --t; *t; }; template<Decrementable T> void h(T); // #5 template<RevIterator2 T> void h(T); // #6 h((int*)0); //ambiguous ``` ### Keywords [`concept`](../keyword/concept "cpp/keyword/concept"), [`requires`](../keyword/requires "cpp/keyword/requires"). ### See also | | | | --- | --- | | [Requires expression](requires "cpp/language/requires")(C++20) | yields a prvalue expression of type `bool` that describes the constraints | cpp Functions Functions ========= Functions are C++ entities that associate a sequence of [statements](statements "cpp/language/statements") (a *function body*) with a *name* and a list of zero or more *function parameters*. ``` // function name: "isodd" // parameter list has one parameter, with name "n" and type int // the return type is bool bool isodd(int n) { // the body of the function begins return n % 2; } // the body of the function ends ``` When a function is invoked, e.g. in a [function-call expression](operator_other#Built-in_function_call_operator "cpp/language/operator other"), the parameters are initialized from the arguments (either provided at the place of call or [defaulted](default_arguments "cpp/language/default arguments")) and the statements in the function body are executed. If the [parameter list](function#Parameter_list "cpp/language/function") ends with `...`, extra arguments can be supplied to the function, such a function is called [variadic function](variadic_arguments "cpp/language/variadic arguments"). ``` int main() { for(int arg : {-3, -2, -1, 0, 1, 2, 3}) std::cout << isodd(arg) << ' '; // isodd called 7 times, each // time n is copy-initialized from arg } ``` [Unqualified](unqualified_lookup "cpp/language/unqualified lookup") function names in function-call expressions are looked up with an extra set of rules called ["argument-dependent lookup" (ADL)](adl "cpp/language/adl"). A function can terminate by [returning](return "cpp/language/return") or by [throwing](throw "cpp/language/throw") an [exception](exceptions "cpp/language/exceptions"). | | | | --- | --- | | A function may be a [coroutine](coroutines "cpp/language/coroutines"), in which case it can suspend execution to be resumed later. | (since C++20) | A [function declaration](function "cpp/language/function") may appear in any scope, but a [function definition](function "cpp/language/function") may only appear in namespace scope or, for [member](member_functions "cpp/language/member functions") and [friend](friend "cpp/language/friend") functions, in class scope. A function that is declared in a class body without a friend specifier is a class member function. Such functions have many additional properties, see [member functions](member_functions "cpp/language/member functions") for details. Functions are not objects: there are no arrays of functions and functions cannot be passed by value or returned from other functions. Pointers and references to functions (except for [the main function](main_function "cpp/language/main function") and [most standard library functions](extending_std#Addressing_restriction "cpp/language/extending std") (since C++20)) are allowed, and may be used where these functions themselves cannot. Therefore we say these functions are "addressable". Each function has a type, which consists of the function's return type, the types of all parameters (after array-to-pointer and function-to-pointer transformations, see [parameter list](function#Parameter_list "cpp/language/function")) , whether the function is [`noexcept`](noexcept_spec "cpp/language/noexcept spec") or not (since C++17), and, for non-static member functions, cv-qualification and ref-qualification (since C++11). Function types also have [language linkage](language_linkage "cpp/language/language linkage"). There are no cv-qualified function types (not to be confused with the types of [cv-qualified functions](member_functions "cpp/language/member functions") such as `int f() const;` or functions returning [cv-qualified types](cv "cpp/language/cv"), such as `[std::string](http://en.cppreference.com/w/cpp/string/basic_string) const f();`). Any cv-qualifier is ignored if it is added to an alias for a function type. | | | | --- | --- | | Unnamed functions can be generated by [lambda-expressions](lambda "cpp/language/lambda"). | (since C++11) | Multiple functions in the same scope may have the same name, as long as their parameter lists and, for non-static member functions, cv/ref (since C++11)-qualifications are different. This is known as [function overloading](overload_resolution "cpp/language/overload resolution"). Function declarations that differ only in the return type and the noexcept specification (since C++17) cannot be overloaded. The [address of an overloaded function](overloaded_address "cpp/language/overloaded address") is determined differently. ### Function objects Besides function lvalues, the function call expression supports pointers to functions, and any value of class type that overloads the function-call operator or is convertible to function pointer (including [lambda-expressions](lambda "cpp/language/lambda")) (since C++11). Together, these types are known as [FunctionObjects](../named_req/functionobject "cpp/named req/FunctionObject"), and they are used ubiquitously through the C++ standard library, see for example, usages of [BinaryPredicate](../named_req/binarypredicate "cpp/named req/BinaryPredicate") and [Compare](../named_req/compare "cpp/named req/Compare"). The standard library also provides a number of pre-defined [function object templates](../utility/functional "cpp/utility/functional") as well as the methods to compose new ones (including `[std::less](../utility/functional/less "cpp/utility/functional/less")`, `[std::mem\_fn](../utility/functional/mem_fn "cpp/utility/functional/mem fn")`, `[std::bind](../utility/functional/bind "cpp/utility/functional/bind")`, `[std::function](../utility/functional/function "cpp/utility/functional/function")` (since C++11), and `[std::bind\_front](../utility/functional/bind_front "cpp/utility/functional/bind front")` (since C++20), and `std::move_only_function` (since C++20)).
programming_docs
cpp final specifier (since C++11) `final` specifier (since C++11) ================================ Specifies that a [virtual function](virtual "cpp/language/virtual") cannot be overridden in a derived class or that a class cannot be [derived from](derived_class "cpp/language/derived class"). ### Syntax When applied to a member function, the identifier `final` appears immediately after the [declarator](function "cpp/language/function") in the syntax of a member function declaration or a member function definition inside a class definition. When applied to a class, the identifier `final` appears at the beginning of the class definition, immediately after the name of the class. | | | | | --- | --- | --- | | declarator virt-specifier-seq(optional) pure-specifier(optional) | (1) | | | declarator virt-specifier-seq(optional) function-body | (2) | | | class-key attr(optional) class-head-name class-virt-specifier(optional) base-clause(optional) | (3) | | 1) In a member function declaration, `final` may appear in virt-specifier-seq immediately after the declarator, and before the [pure-specifier](abstract_class "cpp/language/abstract class"), if used. 2) In a member function definition inside a class definition, `final` may appear in virt-specifier-seq immediately after the declarator and just before function-body. 3) In a class definition, `final` may appear as class-virt-specifier immediately after the name of the class, just before the colon that begins the base-clause, if used. In the cases (1,2), virt-specifier-seq, if used, is either [`override`](override "cpp/language/override") or `final`, or `final override` or `override final`. In the case (3), the only allowed value of class-virt-specifier, if used, is `final`. ### Explanation When used in a virtual function declaration or definition, `final` specifier ensures that the function is virtual and specifies that it may not be overridden by derived classes. The program is ill-formed (a compile-time error is generated) otherwise. When used in a class definition, `final` specifies that this class may not appear in the base-specifier-list of another class definition (in other words, cannot be derived from). The program is ill-formed otherwise (a compile-time error is generated). `final` can also be used with a [union](union "cpp/language/union") definition, in which case it has no effect (other than on the outcome of `[std::is\_final](../types/is_final "cpp/types/is final")`) (since C++14), since unions cannot be derived from. `final` is an identifier with a special meaning when used in a member function declaration or class head. In other contexts, it is not reserved and may be used to name objects and functions. ### Note In a sequence of the following tokens: * one of `class`, `struct` and `union`; * a possibly qualified [identifier](identifiers "cpp/language/identifiers"); * `final`; * one of `:` and `{`, the third token `final` in the sequence is always considered as a specifier instead of an identifier: ``` struct A; struct A final {}; // OK, definition of struct A, // not value-initialization of variable final struct X { struct C { constexpr operator int() { return 5; } }; struct B final : C{}; // OK, definition of nested class B, // not declaration of a bit-field member final }; ``` ### Example ``` struct Base { virtual void foo(); }; struct A : Base { void foo() final; // Base::foo is overridden and A::foo is the final override void bar() final; // Error: bar cannot be final as it is non-virtual }; struct B final : A // struct B is final { void foo() override; // Error: foo cannot be overridden as it is final in A }; struct C : B {}; // Error: B is final ``` Possible output: ``` main.cpp:9:10: error: 'void A::bar()' marked 'final', but is not virtual 9 | void bar() final; // Error: bar cannot be final as it is non-virtual | ^~~ main.cpp:14:10: error: virtual function 'virtual void B::foo()' overriding final function 14 | void foo() override; // Error: foo cannot be overridden as it is final in A | ^~~ main.cpp:8:10: note: overridden function is 'virtual void A::foo()' 8 | void foo() final; // Base::foo is overridden and A::foo is the final override | ^~~ main.cpp:17:8: error: cannot derive from 'final' base 'B' in derived type 'C' 17 | struct C : B // Error: B is final | ``` ### References * C++11 standard (ISO/IEC 14882:2011): + 9 Classes [class] + 10.3 Virtual functions [class.virtual] * C++14 standard (ISO/IEC 14882:2014): + 9 Classes [class] + 10.3 Virtual functions [class.virtual] * C++17 standard (ISO/IEC 14882:2017): + 12 Classes [class] + 13.3 Virtual functions [class.virtual] * C++20 standard (ISO/IEC 14882:2020): + 11 Classes [class] + 11.7.2 Virtual functions [class.virtual] * C++23 standard (ISO/IEC 14882:2023): + 11 Classes [class] + 11.7.3 Virtual functions [class.virtual] ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1318](https://cplusplus.github.io/CWG/issues/1318.html) | C++11 | a class definition which has `final` after the class name and anempty member specification list might make `final` an identifier | `final` is always aspecifier in this case | ### See also | | | | --- | --- | | [`override` specifier](override "cpp/language/override")(C++11) | explicitly declares that a method overrides another method | cpp decltype specifier decltype specifier ================== Inspects the declared type of an entity or the type and value category of an expression. ### Syntax | | | | | --- | --- | --- | | `decltype (` entity `)` | (1) | (since C++11) | | `decltype (` expression `)` | (2) | (since C++11) | ### Explanation 1) If the argument is an unparenthesized [id-expression](identifiers "cpp/language/identifiers") or an unparenthesized [class member access](operator_member_access "cpp/language/operator member access") expression, then decltype yields the type of the entity named by this expression. If there is no such entity, or if the argument names a set of overloaded functions, the program is ill-formed. | | | | --- | --- | | If the argument is an unparenthesized [id-expression](identifiers "cpp/language/identifiers") naming a [structured binding](structured_binding "cpp/language/structured binding"), then decltype yields the *referenced type* (described in the specification of the structured binding declaration). | (since C++17) | | If the argument is an unparenthesized [id-expression](identifiers "cpp/language/identifiers") naming a [non-type template parameter](template_parameters#Non-type_template_parameter "cpp/language/template parameters"), then decltype yields the type of the template parameter (after performing any necessary type deduction if the template parameter is declared with a placeholder type). The type is non-const even if the entity is a template parameter object (which is a const object). | (since C++20) | 2) If the argument is any other expression of type `T`, and a) if the [value category](value_category "cpp/language/value category") of expression is *xvalue*, then decltype yields `T&&`; b) if the value category of expression is *lvalue*, then decltype yields `T&`; c) if the value category of expression is *prvalue*, then decltype yields `T`. | | | | --- | --- | | If expression is a function call which returns a prvalue of class type or is a [comma expression](operator_other "cpp/language/operator other") whose right operand is such a function call, a temporary object is not introduced for that prvalue. | (until C++17) | | If expression is a prvalue other than a (possibly parenthesized) [immediate invocation](consteval "cpp/language/consteval") (since C++20), a temporary object is not [materialized](implicit_cast#Temporary_materialization "cpp/language/implicit cast") from that prvalue: such prvalue has no result object. | (since C++17) | Because no temporary object is created, the type need not be [complete](incomplete_type "cpp/language/incomplete type") or have an available [destructor](destructor "cpp/language/destructor"), and can be [abstract](abstract_class "cpp/language/abstract class"). This rule doesn't apply to sub-expressions: in `decltype(f(g()))`, `g()` must have a complete type, but `f()` need not. Note that if the name of an object is parenthesized, it is treated as an ordinary lvalue expression, thus `decltype(x)` and `decltype((x))` are often different types. `decltype` is useful when declaring types that are difficult or impossible to declare using standard notation, like lambda-related types or types that depend on template parameters. ### Keywords [`decltype`](../keyword/decltype "cpp/keyword/decltype"). ### Example ``` #include <iostream> #include <type_traits> struct A { double x; }; const A* a; decltype(a->x) y; // type of y is double (declared type) decltype((a->x)) z = y; // type of z is const double& (lvalue expression) template<typename T, typename U> auto add(T t, U u) -> decltype(t + u) // return type depends on template parameters // return type can be deduced since C++14 { return t + u; } const int& getRef(const int* p) { return *p; } static_assert(std::is_same_v<decltype(getRef), const int&(const int*)>); auto getRefFwdBad(const int* p) { return getRef(p); } static_assert(std::is_same_v<decltype(getRefFwdBad), int(const int*)>, "Just returning auto isn't perfect forwarding."); decltype(auto) getRefFwdGood(const int* p) { return getRef(p); } static_assert(std::is_same_v<decltype(getRefFwdGood), const int&(const int*)>, "Returning decltype(auto) perfectly forwards the return type."); // Alternatively: auto getRefFwdGood1(const int* p) -> decltype(getRef(p)) { return getRef(p); } static_assert(std::is_same_v<decltype(getRefFwdGood1), const int&(const int*)>, "Returning decltype(return expression) also perfectly forwards the return type."); int main() { int i = 33; decltype(i) j = i * 2; std::cout << "i and j are the same type? " << std::boolalpha << std::is_same_v<decltype(i), decltype(j)> << '\n'; std::cout << "i = " << i << ", " << "j = " << j << '\n'; auto f = [](int a, int b) -> int { return a * b; }; decltype(f) g = f; // the type of a lambda function is unique and unnamed i = f(2, 2); j = g(3, 3); std::cout << "i = " << i << ", " << "j = " << j << '\n'; } ``` Output: ``` i and j are the same type? true i = 33, j = 66 i = 4, j = 9 ``` ### See also | | | | --- | --- | | [`auto` specifier](auto "cpp/language/auto") (C++11) | specifies a type deduced from an expression | | [declval](../utility/declval "cpp/utility/declval") (C++11) | obtains a reference to its argument for use in unevaluated context (function template) | | [is\_same](../types/is_same "cpp/types/is same") (C++11) | checks if two types are the same (class template) | cpp Variable template (since C++14) Variable template (since C++14) =============================== A variable template defines a family of variables or static data members. ### Syntax | | | | | --- | --- | --- | | `template` `<` parameter-list `>` variable-declaration | | | | | | | | --- | --- | --- | | variable-declaration | - | a [declaration](declarations "cpp/language/declarations") of a variable. The declared variable name becomes a template name. | | parameter-list | - | a non-empty comma-separated list of the [template parameters](template_parameters "cpp/language/template parameters"), each of which is either [non-type parameter](template_parameters#Non-type_template_parameter "cpp/language/template parameters"), a [type parameter](template_parameters#Type_template_parameter "cpp/language/template parameters"), a [template parameter](template_parameters#Template_template_parameter "cpp/language/template parameters"), or a [parameter pack](parameter_pack "cpp/language/parameter pack") of any of those. | ### Explanation A variable instantiated from a variable template is called an *instantiated variable*. A static data member instantiated from a static data member template is called an *instantiated static data member*. A variable template may be introduced by a template declaration at namespace scope, where variable-declaration declares a variable. ``` template<class T> constexpr T pi = T(3.1415926535897932385L); // variable template template<class T> T circular_area(T r) // function template { return pi<T> * r * r; // pi<T> is a variable template instantiation } ``` When used at class scope, variable template declares a static data member template. ``` using namespace std::literals; struct matrix_constants { template<class T> using pauli = hermitian_matrix<T, 2>; // alias template template<class T> // static data member template static constexpr pauli<T> sigmaX = {{0, 1}, {1, 0}}; template<class T> static constexpr pauli<T> sigmaY = {{0, -1i}, {1i, 0}}; template<class T> static constexpr pauli<T> sigmaZ = {{1, 0}, {0, -1}}; }; ``` As with other [static members](static "cpp/language/static"), a definition of a static data member template may be required. Such definition is provided outside the class definition. A template declaration of a static data member at namespace scope may also be a definition of a non-template [data member of a class template](member_template "cpp/language/member template"): ``` struct limits { template<typename T> static const T min; // declaration of a static data member template }; template<typename T> const T limits::min = { }; // definition of a static data member template template<class T> class X { static T s; // declaration of a non-template static data member of a class template }; template<class T> T X<T>::s = 0; // definition of a non-template data member of a class template ``` Unless a variable template was [explicitly specialized](template_specialization "cpp/language/template specialization") or explicitly instantiated, it is implicitly instantiated when a specialization of the variable template is referenced in a context that requires [a variable definition to exist](definition#ODR-use "cpp/language/definition") or if the existence of the definition affects the semantics of the program, i.e. if the variable is [needed for constant evaluation](constant_expression#Functions_and_variables_needed_for_constant_evaluation "cpp/language/constant expression") by an expression (the definition may be not used). The existence of a definition of a variable is considered to affect the semantics of the program if the variable is needed for constant evaluation by an expression, even if constant evaluation of the expression is not required or if constant expression evaluation does not use the definition. ### Notes Until variable templates were introduced in C++14, parametrized variables were typically implemented as either static data members of class templates or as constexpr function templates returning the desired values. Variable templates cannot be used as [template template arguments](template_parameters#Template_template_arguments "cpp/language/template parameters"). ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 2255](https://cplusplus.github.io/CWG/issues/2255.html) | C++14 | it was unclear whether a specialization of a staticdata member template is a static data member | it is | cpp Type Type ==== [Objects](object "cpp/language/object"), [references](reference "cpp/language/reference"), [functions](functions "cpp/language/functions") including [function template specializations](template_specialization "cpp/language/template specialization"), and [expressions](expressions "cpp/language/expressions") have a property called *type*, which both restricts the operations that are permitted for those entities and provides semantic meaning to the otherwise generic sequences of bits. ### Type classification The C++ type system consists of the following types: * [fundamental types](types "cpp/language/types") (see also `[std::is\_fundamental](http://en.cppreference.com/w/cpp/types/is_fundamental)`): + the type `void` (see also `[std::is\_void](http://en.cppreference.com/w/cpp/types/is_void)`); | | | | --- | --- | | * the type `[std::nullptr\_t](http://en.cppreference.com/w/cpp/types/nullptr_t)` (see also `[std::is\_null\_pointer](http://en.cppreference.com/w/cpp/types/is_null_pointer)`); | (since C++11) | * arithmetic types (see also `[std::is\_arithmetic](http://en.cppreference.com/w/cpp/types/is_arithmetic)`): * floating-point types (`float`, `double`, `long double` and their [cv-qualified versions](cv "cpp/language/cv")) (see also `[std::is\_floating\_point](http://en.cppreference.com/w/cpp/types/is_floating_point)`); * integral types (including [cv-qualified versions](cv "cpp/language/cv"), see also `[std::is\_integral](http://en.cppreference.com/w/cpp/types/is_integral)`): * the type `bool`; * character types: * narrow character types: + ordinary character types (`char`, `signed char`, `unsigned char`) | | | | --- | --- | | * the type `char8_t` | (since C++20) | * wide character types (`char16_t`, `char32_t`, (since C++11)`wchar_t`); * signed integer types (`short int`, `int`, `long int`, `long long int`); * unsigned integer types (`unsigned short int`, `unsigned int`, `unsigned long int`, `unsigned long long int`); * compound types (see also `[std::is\_compound](http://en.cppreference.com/w/cpp/types/is_compound)`): * [reference types](reference "cpp/language/reference") (see also `[std::is\_reference](http://en.cppreference.com/w/cpp/types/is_reference)`): * [lvalue reference types](reference#Lvalue_references "cpp/language/reference") (see also `[std::is\_lvalue\_reference](http://en.cppreference.com/w/cpp/types/is_lvalue_reference)`): + lvalue reference to object types; + lvalue reference to function types; * [rvalue reference types](reference#Rvalue_references "cpp/language/reference") (see also `[std::is\_rvalue\_reference](http://en.cppreference.com/w/cpp/types/is_rvalue_reference)`): + rvalue reference to object types; + rvalue reference to function types; * [pointer types](pointer#Pointers "cpp/language/pointer") (see also `[std::is\_pointer](http://en.cppreference.com/w/cpp/types/is_pointer)`): + [pointer-to-object types](pointer#Pointers_to_objects "cpp/language/pointer"); + [pointer-to-function types](pointer#Pointers_to_functions "cpp/language/pointer"); * [pointer-to-member types](pointer#Pointers_to_members "cpp/language/pointer") (see also `[std::is\_member\_pointer](http://en.cppreference.com/w/cpp/types/is_member_pointer)`): + [pointer-to-data-member](pointer#Pointers_to_data_members "cpp/language/pointer") types (see also `[std::is\_member\_object\_pointer](http://en.cppreference.com/w/cpp/types/is_member_object_pointer)`); + [pointer-to-member-function](pointer#Pointers_to_member_functions "cpp/language/pointer") types (see also `[std::is\_member\_function\_pointer](http://en.cppreference.com/w/cpp/types/is_member_function_pointer)`); * [array types](array "cpp/language/array") (see also `[std::is\_array](http://en.cppreference.com/w/cpp/types/is_array)`); * [function types](function "cpp/language/function") (see also `[std::is\_function](http://en.cppreference.com/w/cpp/types/is_function)`); * [enumeration types](enum "cpp/language/enum") (see also `[std::is\_enum](http://en.cppreference.com/w/cpp/types/is_enum)`); + [unscoped enumeration types](enum#Unscoped_enumerations "cpp/language/enum"); + [scoped enumeration types](enum#Scoped_enumerations "cpp/language/enum") (see also `std::is_scoped_enum`); * [class types](class "cpp/language/class"): + non-union types (see also `[std::is\_class](http://en.cppreference.com/w/cpp/types/is_class)`); + [union types](union "cpp/language/union") (see also `[std::is\_union](http://en.cppreference.com/w/cpp/types/is_union)`). For every type other than reference and function, the type system supports three additional [cv-qualified versions](cv "cpp/language/cv") of that type (`const`, `volatile`, and `const volatile`). Types are grouped in various categories based on their properties: * object types are (possibly cv-qualified) types that are not function types, reference types, or possibly cv-qualified `void` (see also `[std::is\_object](http://en.cppreference.com/w/cpp/types/is_object)`); * [scalar types](../named_req/scalartype "cpp/named req/ScalarType") are (possibly cv-qualified) object types that are not array types or class types (see also `[std::is\_scalar](http://en.cppreference.com/w/cpp/types/is_scalar)`); * [trivial types](../named_req/trivialtype "cpp/named req/TrivialType") (see also `[std::is\_trivial](http://en.cppreference.com/w/cpp/types/is_trivial)`), [POD types](../named_req/podtype "cpp/named req/PODType") (see also `[std::is\_pod](http://en.cppreference.com/w/cpp/types/is_pod)`), [literal types](../named_req/literaltype "cpp/named req/LiteralType") (see also `[std::is\_literal\_type](http://en.cppreference.com/w/cpp/types/is_literal_type)`), and other categories listed in the [type traits library](../types "cpp/types") or as [named type requirements](../named_req "cpp/named req"). ### Type naming A [name](name "cpp/language/name") can be declared to refer to a type by means of: * [class](class "cpp/language/class") declaration; * [union](union "cpp/language/union") declaration; * [enum](enum "cpp/language/enum") declaration; * [typedef](typedef "cpp/language/typedef") declaration; * [type alias](type_alias "cpp/language/type alias") declaration. Types that do not have names often need to be referred to in C++ programs; the syntax for that is known as type-id. The syntax of the type-id that names type `T` is exactly the syntax of a [declaration](declarations "cpp/language/declarations") of a variable or function of type `T`, with the identifier omitted, except that decl-specifier-seq of the declaration grammar is constrained to type-specifier-seq, and that new types may be defined only if the type-id appears on the right-hand side of a non-template type alias declaration. ``` int* p; // declaration of a pointer to int static_cast<int*>(p); // type-id is "int*" int a[3]; // declaration of an array of 3 int new int[3]; // type-id is "int[3]" (called new-type-id) int (*(*x[2])())[3]; // declaration of an array of 2 pointers to functions // returning pointer to array of 3 int new (int (*(*[2])())[3]); // type-id is "int (*(*[2])())[3]" void f(int); // declaration of a function taking int and returning void std::function<void(int)> x = f; // type template parameter is a type-id "void(int)" std::function<auto(int) -> void> y = f; // same std::vector<int> v; // declaration of a vector of int sizeof(std::vector<int>); // type-id is "std::vector<int>" struct { int x; } b; // creates a new type and declares an object b of that type sizeof(struct { int x; }); // error: cannot define new types in a sizeof expression using t = struct { int x; }; // creates a new type and declares t as an alias of that type sizeof(static int); // error: storage class specifiers not part of type-specifier-seq std::function<inline void(int)> f; // error: neither are function specifiers ``` The declarator part of the declaration grammar with the name removed is referred to as abstract-declarator. Type-id may be used in the following situations: * to specify the target type in [cast expressions](expressions#Conversions "cpp/language/expressions"); * as arguments to [sizeof](sizeof "cpp/language/sizeof"), [alignof](alignof "cpp/language/alignof"), [alignas](alignas "cpp/language/alignas"), [new](new "cpp/language/new"), and [typeid](typeid "cpp/language/typeid"); * on the right-hand side of a [type alias](type_alias "cpp/language/type alias") declaration; * as the trailing return type of a [function](function "cpp/language/function") declaration; * as the default argument of a [template type parameter](template_parameters#Type_template_parameter "cpp/language/template parameters"); * as the template argument for a [template type parameter](template_parameters#Template_type_arguments "cpp/language/template parameters"); | | | | --- | --- | | * in [dynamic exception specification](except_spec "cpp/language/except spec"). | (until C++17) | Type-id can be used with some modifications in the following situations: * in the parameter list of a [function](function#Parameter_list "cpp/language/function") (when the parameter name is omitted), type-id uses decl-specifier-seq instead of type-specifier-seq (in particular, some storage class specifiers are allowed); * in the name of a [user-defined conversion function](cast_operator "cpp/language/cast operator"), the abstract declarator cannot include function or array operators. ### Elaborated type specifier Elaborated type specifiers may be used to refer to a previously-declared class name (class, struct, or union) or to a previously-declared enum name even if the name was [hidden by a non-type declaration](lookup "cpp/language/lookup"). They may also be used to declare new class names. See [elaborated type specifier](elaborated_type_specifier "cpp/language/elaborated type specifier") for details. ### Static type The type of an expression that results from the compile-time analysis of the program is known as the *static type* of the expression. The static type does not change while the program is executing. ### Dynamic type If some [glvalue expression](value_category "cpp/language/value category") refers to a [polymorphic object](object "cpp/language/object"), the type of its most derived object is known as the dynamic type. ``` // given struct B { virtual ~B() {} }; // polymorphic type struct D: B {}; // polymorphic type D d; // most-derived object B* ptr = &d; // the static type of (*ptr) is B // the dynamic type of (*ptr) is D ``` For prvalue expressions, the dynamic type is always the same as the static type. ### Incomplete type The following types are *incomplete types*: * the type `void` (possibly [cv](cv "cpp/language/cv")-qualified); * *incompletely-defined object types*: + class type that has been declared (e.g. by [forward declaration](class#Forward_declaration "cpp/language/class")) but not defined; + [array of unknown bound](array#Arrays_of_unknown_bound "cpp/language/array"); + array of elements of incomplete type; + [enumeration type](enum "cpp/language/enum") from the point of declaration until its underlying type is determined. All other types are complete. Any of the following contexts requires type `T` to be complete: * [definition](function "cpp/language/function") of or call to a function with return type `T` or argument type `T`; * [definition](definition "cpp/language/definition") of an object of type `T`; * declaration of a [non-static class data member](data_members "cpp/language/data members") of type `T`; * [new-expression](new "cpp/language/new") for an object of type `T` or an array whose element type is `T`; * [lvalue-to-rvalue conversion](implicit_cast#Lvalue_to_rvalue_conversion "cpp/language/implicit cast") applied to a glvalue of type `T`; * an [implicit](implicit_cast "cpp/language/implicit cast") or [explicit](explicit_cast "cpp/language/explicit cast") conversion to type `T`; * a [standard conversion](implicit_cast "cpp/language/implicit cast"), [dynamic\_cast](dynamic_cast "cpp/language/dynamic cast"), or [static\_cast](static_cast "cpp/language/static cast") to type `T*` or `T&`, except when converting from the [null pointer constant](pointer#Null_pointers "cpp/language/pointer") or from a [pointer to possibly cv-qualified void](pointer#Pointers_to_void "cpp/language/pointer"); * [class member access operator](operator_member_access "cpp/language/operator member access") applied to an expression of type `T`; * [typeid](typeid "cpp/language/typeid"), [sizeof](sizeof "cpp/language/sizeof"), or [alignof](alignof "cpp/language/alignof") operator applied to type `T`; * [arithmetic operator](operator_arithmetic "cpp/language/operator arithmetic") applied to a pointer to `T`; * definition of a class with base class `T`; * assignment to an lvalue of type `T`; * a [catch-clause](try_catch "cpp/language/try catch") for an exception of type `T`, `T&`, or `T*`. (In general, when the size and layout of `T` must be known.). If any of these situations occur in a translation unit, the definition of the type must appear in the same translation unit. Otherwise, it is not required. An incompletely-defined object type can be completed: * A class type (such as `class X`) might be incomplete at one point in a translation unit and complete later on; the type `class X` is the same type at both points: ``` struct X; // X is an incomplete type extern X* xp; // xp is a pointer to an incomplete type void foo() { xp++; // ill-formed: X is incomplete } struct X { int i; }; // now X is a complete type X x; void bar() { xp = &x; // OK: type is “pointer to X” xp++; // OK: X is complete } ``` * The declared type of an array object might be an array of incomplete class type and therefore incomplete; if the class type is completed later on in the translation unit, the array type becomes complete; the array type at those two points is the same type. * The declared type of an array object might be an array of unknown bound and therefore be incomplete at one point in a translation unit and complete later on; the array types at those two points ("array of unknown bound of `T`" and "array of `N` `T`") are different types. The type of a pointer to array of unknown bound, or to a type defined by a `typedef` declaration to be an array of unknown bound, cannot be completed. ``` extern int arr[]; // the type of arr is incomplete typedef int UNKA[]; // UNKA is an incomplete type UNKA* arrp; // arrp is a pointer to an incomplete type UNKA** arrpp; void foo() { arrp++; // error: incomplete type arrpp++; // OK: sizeof UNKA* is known } int arr[10]; // now the type of arr is complete void bar() { arrp = &arr; // error: different types arrp++; // error: UNKA can’t be completed } ``` ### Defect Reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 328](https://cplusplus.github.io/CWG/issues/328.html) | C++98 | class members of incomplete type were not prohibited if an object of the class type was never created | non-static class data membersneed to be complete | | [CWG 977](https://cplusplus.github.io/CWG/issues/977.html) | C++98 | the point when an enumeration type becomescomplete in its definition was unclear | the type is complete once theunderlying type is determined | | [CWG 1362](https://cplusplus.github.io/CWG/issues/1362.html) | C++98 | user-defined conversions to type `T*` or `T&` required `T` to be complete | not required | | [CWG 2006](https://cplusplus.github.io/CWG/issues/2006.html) | C++98 | cv-qualified `void` types were object type and complete type | excluded from both categories | | [CWG 2448](https://cplusplus.github.io/CWG/issues/2448.html) | C++98 | only cv-unqualified types could be integral and floating-point types | allowed cv-qualified types | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/type "c/language/type") for Type |
programming_docs
cpp Lambda expressions (since C++11) Lambda expressions (since C++11) ================================ Constructs a [closure](https://en.wikipedia.org/wiki/Closure_(computer_science) "enwiki:Closure (computer science)"): an unnamed function object capable of capturing variables in scope. ### Syntax | | | | | --- | --- | --- | | `[` captures `]` `(` params `)` specs requires(optional) `{` body `}` | (1) | | | `[` captures `]` `{` body `}` | (2) | (until C++23) | | `[` captures `]` specs `{` body `}` | (2) | (since C++23) | | `[` captures `]` `<` tparams `>` requires(optional) `(` params `)` specs requires(optional) `{` body `}` | (3) | (since C++20) | | `[` captures `]` `<` tparams `>` requires(optional) `{` body `}` | (4) | (since C++20)(until C++23) | | `[` captures `]` `<` tparams `>` requires(optional) specs `{` body `}` | (4) | (since C++23) | 1) Full form. 2) Omitted parameter list: function takes no arguments, as if the parameter list were `()`. 3) Same as 1), but specifies a generic lambda and explicitly provides a list of template parameters. 4) Same as 2), but specifies a generic lambda and explicitly provides a list of template parameters. ### Explanation | | | | | --- | --- | --- | | captures | - | a comma-separated list of zero or more [captures](#Lambda_capture), optionally beginning with a capture-default. See [below](#Lambda_capture) for the detailed description of captures. A lambda expression can use a variable without capturing it if the variable.* is a non-local variable or has static or thread local [storage duration](storage_duration "cpp/language/storage duration") (in which case the variable cannot be captured), or * is a reference that has been initialized with a [constant expression](constant_expression#Constant_expression "cpp/language/constant expression"). A lambda expression can read the value of a variable without capturing it if the variable.* has const non-volatile integral or enumeration type and has been initialized with a [constant expression](constant_expression#Constant_expression "cpp/language/constant expression"), or * is `constexpr` and has no mutable members. | | tparams | - | a non-empty comma-separated list of [template parameters](template_parameters "cpp/language/template parameters"), used to provide names to the template parameters of a generic lambda (see `ClosureType::operator()` below). | | params | - | The list of parameters, as in [named functions](function "cpp/language/function"). | | specs | - | consists of specifiers, exception, attr and trailing-return-type in that order; each of these components is optional | | specifiers | - | Optional sequence of specifiers. If not provided, the objects captured by copy are const in the lambda body. The following specifiers are allowed at most once in each sequence: * `mutable`: allows body to modify the objects captured by copy, and to call their non-const member functions | | | | --- | --- | | * `constexpr`: explicitly specifies that the function call operator or any given operator template specialization is a [constexpr](constexpr "cpp/language/constexpr") function. When this specifier is not present, the function call operator or any given operator template specialization will be `constexpr` anyway, if it happens to satisfy all constexpr function requirements | (since C++17) | | | | | --- | --- | | * `consteval`: specifies that the function call operator or any given operator template specialization is an [immediate function](consteval "cpp/language/consteval"). `consteval` and `constexpr` cannot be used at the same time. | (since C++20) | | | exception | - | provides the [dynamic exception specification](except_spec "cpp/language/except spec") or (until C++20) the [noexcept specifier](noexcept_spec "cpp/language/noexcept spec") for `operator()` of the closure type | | attr | - | provides the [attribute specification](attributes "cpp/language/attributes") for the type of the function call operator or operator template of the closure type. Any attribute so specified does not appertain to the function call operator or operator template itself, but its type. (For example, the `[[[noreturn](attributes/noreturn "cpp/language/attributes/noreturn")]]` attribute cannot be used.) | | trailing-return-type | - | `->` ret, where ret specifies the return type. If trailing-return-type is not present, the return type of the closure's `operator()` is [deduced](template_argument_deduction "cpp/language/template argument deduction") from [return](return "cpp/language/return") statements as if for a function whose [return type is declared auto](function#Return_type_deduction "cpp/language/function"). | | requires | - | (since C++20) adds [constraints](constraints "cpp/language/constraints") to `operator()` of the closure type | | body | - | Function body | | | | | --- | --- | | If [`auto`](auto "cpp/language/auto") is used as a type of a parameter or an explicit template parameter list is provided (since C++20), the lambda is a *generic lambda*. | (since C++14) | A variable `__func__` is implicitly defined at the beginning of body, with semantics as described [here](function#func "cpp/language/function"). The lambda expression is a prvalue expression of unique unnamed non-union non-aggregate class type, known as *closure type*, which is declared (for the purposes of [ADL](adl "cpp/language/adl")) in the smallest block scope, class scope, or namespace scope that contains the lambda expression. The closure type has the following members, they cannot be [explicitly instantiated](function_template#Explicit_instantiation "cpp/language/function template"), [explicitly specialized](template_specialization "cpp/language/template specialization"), or (since C++14) named in a [friend declaration](friend "cpp/language/friend"): ClosureType::operator()(params) -------------------------------- | | | | | --- | --- | --- | | ``` ret operator()(params) const { body } ``` | | (the keyword mutable was not used) | | ``` ret operator()(params) { body } ``` | | (the keyword mutable was used) | | ``` template<template-params> ret operator()(params) const { body } ``` | | (since C++14) (generic lambda) | | ``` template<template-params> ret operator()(params) { body } ``` | | (since C++14) (generic lambda, the keyword mutable was used) | Executes the body of the lambda-expression, when invoked. When accessing a variable, accesses its captured copy (for the entities captured by copy), or the original object (for the entities captured by reference). Unless the keyword `mutable` was used in the lambda-expression, the function-call operator or operator template is const-qualified and the objects that were captured by copy are non-modifiable from inside this `operator()`. The function-call operator or operator template is never volatile-qualified and never virtual. | | | | --- | --- | | The function-call operator or any given operator template specialization is always `constexpr` if it satisfies the requirements of a [constexpr function](constexpr "cpp/language/constexpr"). It is also constexpr if the keyword constexpr was used in the lambda expression. | (since C++17) | | | | | --- | --- | | The function-call operator or any given operator template specialization is an [immediate function](consteval "cpp/language/consteval") if the keyword `consteval` was used in the lambda expression. | (since C++20) | | | | | --- | --- | | For each parameter in params whose type is specified as `auto`, an invented template parameter is added to template-params, in order of appearance. The invented template parameter may be a [parameter pack](parameter_pack "cpp/language/parameter pack") if the corresponding function member of params is a function parameter pack. ``` // generic lambda, operator() is a template with two parameters auto glambda = [](auto a, auto&& b) { return a < b; }; bool b = glambda(3, 3.14); // ok // generic lambda, operator() is a template with one parameter auto vglambda = [](auto printer) { return [=](auto&&... ts) // generic lambda, ts is a parameter pack { printer(std::forward<decltype(ts)>(ts)...); return [=] { printer(ts...); }; // nullary lambda (takes no parameters) }; }; auto p = vglambda([](auto v1, auto v2, auto v3) { std::cout << v1 << v2 << v3; }); auto q = p(1, 'a', 3.14); // outputs 1a3.14 q(); // outputs 1a3.14 ``` | (since C++14) | | | | | --- | --- | | If the lambda definition uses an explicit template parameter list, that template parameter list is used with `operator()`. For each parameter in params whose type is specified as `auto`, an additional invented template parameter is appended to the end of that template parameter list: ``` // generic lambda, operator() is a template with two parameters auto glambda = []<class T>(T a, auto&& b) { return a < b; }; // generic lambda, operator() is a template with one parameter pack auto f = []<typename... Ts>(Ts&&... ts) { return foo(std::forward<Ts>(ts)...); }; ``` | (since C++20) | the exception specification exception on the lambda-expression applies to the function-call operator or operator template. For the purpose of [name lookup](lookup "cpp/language/lookup"), determining the type and value of the [`this` pointer](this "cpp/language/this") and for accessing non-static class members, the body of the closure type's function call operator or operator template is considered in the context of the lambda-expression. ``` struct X { int x, y; int operator()(int); void f() { // the context of the following lambda is the member function X::f [=]() -> int { return operator()(this->x + y); // X::operator()(this->x + (*this).y) // this has type X* }; } }; ``` ### Dangling references If a non-reference entity is captured by reference, implicitly or explicitly, and the function call operator or a specialization of the function call operator template of the closure object is invoked after the entity's lifetime has ended, undefined behavior occurs. The C++ closures do not extend the lifetimes of objects captured by reference. Same applies to the lifetime of the current `*this` object captured via `this`. ClosureType::operator ret(\*)(params)() ---------------------------------------- | | | | | --- | --- | --- | | capture-less non-generic lambda | | | | ``` using F = ret(*)(params); operator F() const noexcept; ``` | | (until C++17) | | ``` using F = ret(*)(params); constexpr operator F() const noexcept; ``` | | (since C++17) | | capture-less generic lambda | | | | ``` template<template-params> using fptr_t = /*see below*/; template<template-params> operator fptr_t<template-params>() const noexcept; ``` | | (since C++14) (until C++17) | | ``` template<template-params> using fptr_t = /*see below*/; template<template-params> constexpr operator fptr_t<template-params>() const noexcept; ``` | | (since C++17) | This [user-defined conversion function](cast_operator "cpp/language/cast operator") is only defined if the capture list of the lambda-expression is empty. It is a public, constexpr, (since C++17) non-virtual, non-explicit, const noexcept member function of the closure object. | | | | --- | --- | | This function is an [immediate function](consteval "cpp/language/consteval") if the function call operator (or specialization, for generic lambdas) is an immediate function. | (since C++20) | | | | | --- | --- | | A generic captureless lambda has a user-defined conversion function template with the same invented template parameter list as the function-call operator template. If the return type is empty or auto, it is obtained by return type deduction on the function template specialization, which, in turn, is obtained by [template argument deduction](template_argument_deduction "cpp/language/template argument deduction") for conversion function templates. ``` void f1(int (*)(int)) {} void f2(char (*)(int)) {} void h(int (*)(int)) {} // #1 void h(char (*)(int)) {} // #2 auto glambda = [](auto a) { return a; }; f1(glambda); // OK f2(glambda); // error: not convertible h(glambda); // OK: calls #1 since #2 is not convertible int& (*fpi)(int*) = [](auto* a) -> auto& { return *a; }; // OK ``` | (since C++14) | The value returned by this conversion function (template) (since C++14) is a pointer to a function with C++ [language linkage](language_linkage "cpp/language/language linkage") that, when invoked, has the same effect as: * for non-generic lambdas, (since C++14) invoking the closure type's function call operator on a default-constructed instance of the closure type. | | | | --- | --- | | * for generic lambdas, invoking the generic lambda's corresponding function call operator template specialization on a default-constructed instance of the closure type. | (since C++14) | | | | | --- | --- | | This function is constexpr if the function call operator (or specialization, for generic lambdas) is constexpr. ``` auto Fwd = [](int(*fp)(int), auto a){ return fp(a); }; auto C = [](auto a){ return a; }; static_assert(Fwd(C, 3) == 3); // OK auto NC = [](auto a){ static int s; return a; }; static_assert(Fwd(NC, 3) == 3); // error: no specialization can be // constexpr because of static s ``` If the closure object's `operator()` has a non-throwing exception specification, then the pointer returned by this function has the type pointer to noexcept function. | (since C++17) | ClosureType::ClosureType() --------------------------- | | | | | --- | --- | --- | | ``` ClosureType() = default; ``` | | (since C++20) (only if no captures are specified) | | ``` ClosureType(const ClosureType&) = default; ``` | | | | ``` ClosureType(ClosureType&&) = default; ``` | | | | | | | --- | --- | | Closure types are not [DefaultConstructible](../named_req/defaultconstructible "cpp/named req/DefaultConstructible"). Closure types have no default constructor. | (until C++20) | | If no captures are specified, the closure type has a defaulted default constructor. Otherwise, it has no default constructor (this includes the case when there is a capture-default, even if it does not actually capture anything). | (since C++20) | The copy constructor and the move constructor are declared as defaulted and may be implicitly-defined according to the usual rules for [copy constructors](copy_constructor "cpp/language/copy constructor") and [move constructors](move_constructor "cpp/language/move constructor"). ClosureType::operator=(const ClosureType&) ------------------------------------------- | | | | | --- | --- | --- | | ``` ClosureType& operator=(const ClosureType&) = delete; ``` | | (until C++20) | | ``` ClosureType& operator=(const ClosureType&) = default; ClosureType& operator=(ClosureType&&) = default; ``` | | (since C++20) (only if no captures are specified) | | ``` ClosureType& operator=(const ClosureType&) = delete; ``` | | (since C++20) (otherwise) | | | | | --- | --- | | The copy assignment operator is defined as deleted (and the move assignment operator is not declared). Closure types are not [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"). | (until C++20) | | If no captures are specified, the closure type has a defaulted copy assignment operator and a defaulted move assignment operator. Otherwise, it has a deleted copy assignment operator (this includes the case when there is a capture-default, even if it does not actually capture anything). | (since C++20) | ClosureType::~ClosureType() ---------------------------- | | | | | --- | --- | --- | | ``` ~ClosureType() = default; ``` | | | The destructor is implicitly-declared. ClosureType::Captures ---------------------- | | | | | --- | --- | --- | | ``` T1 a; T2 b; ... ``` | | | If the lambda-expression captures anything by copy (either implicitly with capture clause `[=]` or explicitly with a capture that does not include the character &, e.g. `[a, b, c]`), the closure type includes unnamed non-static data members, declared in unspecified order, that hold copies of all entities that were so captured. Those data members that correspond to captures without initializers are [direct-initialized](direct_initialization "cpp/language/direct initialization") when the lambda-expression is evaluated. Those that correspond to captures with initializers are initialized as the initializer requires (could be copy- or direct-initialization). If an array is captured, array elements are direct-initialized in increasing index order. The order in which the data members are initialized is the order in which they are declared (which is unspecified). The type of each data member is the type of the corresponding captured entity, except if the entity has reference type (in that case, references to functions are captured as lvalue references to the referenced functions, and references to objects are captured as copies of the referenced objects). For the entities that are captured by reference (with the default capture `[&]` or when using the character &, e.g. `[&a, &b, &c]`), it is unspecified if additional data members are declared in the closure type, but any such additional members must satisfy [LiteralType](../named_req/literaltype "cpp/named req/LiteralType") (since C++17). | | | | --- | --- | | Lambda-expressions are not allowed in [unevaluated expressions](expressions#Unevaluated_expressions "cpp/language/expressions"), [template arguments](template_parameters "cpp/language/template parameters"), [alias declarations](type_alias "cpp/language/type alias"), [typedef declarations](typedef "cpp/language/typedef"), and anywhere in a function (or function template) declaration except the function body and the function's [default arguments](default_arguments "cpp/language/default arguments"). | (until C++20) | ### Lambda capture The captures is a comma-separated list of zero or more *captures*, optionally beginning with the capture-default. The capture list defines the outside variables that are accessible from within the lambda function body. The only capture defaults are. * `&` (implicitly capture the used automatic variables by reference) and * `=` (implicitly capture the used automatic variables by copy). The current object (`*this`) can be implicitly captured if either capture default is present. If implicitly captured, it is always captured by reference, even if the capture default is `=`. The implicit capture of `*this` when the capture default is `=` is deprecated. (since C++20). The syntax of an individual capture in captures is. | | | | | --- | --- | --- | | identifier | (1) | | | identifier `...` | (2) | | | identifier initializer | (3) | (since C++14) | | `&` identifier | (4) | | | `&` identifier `...` | (5) | | | `&` identifier initializer | (6) | (since C++14) | | `this` | (7) | | | `*` `this` | (8) | (since C++17) | | `...` identifier initializer | (9) | (since C++20) | | `&` `...` identifier initializer | (10) | (since C++20) | 1) simple by-copy capture 2) simple by-copy capture that is a [pack expansion](parameter_pack "cpp/language/parameter pack") 3) by-copy capture with an [initializer](initialization "cpp/language/initialization") 4) simple by-reference capture 5) simple by-reference capture that is a [pack expansion](parameter_pack "cpp/language/parameter pack") 6) by-reference capture with an initializer 7) simple by-reference capture of the current object 8) simple by-copy capture of the current object 9) by-copy capture with an initializer that is a pack expansion 10) by-reference capture with an initializer that is a pack expansion If the capture-default is `&`, subsequent simple captures must not begin with `&`. ``` struct S2 { void f(int i); }; void S2::f(int i) { [&]{}; // OK: by-reference capture default [&, i]{}; // OK: by-reference capture, except i is captured by copy [&, &i] {}; // Error: by-reference capture when by-reference is the default [&, this] {}; // OK, equivalent to [&] [&, this, i]{}; // OK, equivalent to [&, i] } ``` If the capture-default is `=`, subsequent simple captures must begin with `&` or be `*this` (since C++17) or `this` (since C++20). ``` struct S2 { void f(int i); }; void S2::f(int i) { [=]{}; // OK: by-copy capture default [=, &i]{}; // OK: by-copy capture, except i is captured by reference [=, *this]{}; // until C++17: Error: invalid syntax // since C++17: OK: captures the enclosing S2 by copy [=, this] {}; // until C++20: Error: this when = is the default // since C++20: OK, same as [=] } ``` Any capture may appear only once, and its name must be different from any parameter name: ``` struct S2 { void f(int i); }; void S2::f(int i) { [i, i] {}; // Error: i repeated [this, *this] {}; // Error: "this" repeated (C++17) [i] (int i) {}; // Error: parameter and capture have the same name } ``` Only lambda-expressions defined at block scope or in a [default member initializer](data_members#Member_initialization "cpp/language/data members") may have a capture-default or captures without initializers. For such lambda-expression, the *reaching scope* is defined as the set of enclosing scopes up to and including the innermost enclosing function (and its parameters). This includes nested block scopes and the scopes of enclosing lambdas if this lambda is nested. The identifier in any capture without an initializer (other than the `this`-capture) is looked up using usual [unqualified name lookup](lookup "cpp/language/lookup") in the *reaching scope* of the lambda. The result of the lookup must be a [variable](object "cpp/language/object") with automatic storage duration declared in the reaching scope, or a [structured binding](structured_binding "cpp/language/structured binding") whose corresponding variable satisfies such requirements (since C++20). The entity is *explicitly captured*. | | | | --- | --- | | A capture with an initializer acts as if it declares and explicitly captures a variable declared with type [`auto`](auto "cpp/language/auto"), whose declarative region is the body of the lambda expression (that is, it is not in scope within its initializer), except that:* if the capture is by-copy, the non-static data member of the closure object is another way to refer to that auto variable. * if the capture is by-reference, the reference variable's lifetime ends when the lifetime of the closure object ends This is used to capture move-only types with a capture such as `x = std::move(x)`. This also makes it possible to capture by const reference, with `&cr = [std::as\_const](http://en.cppreference.com/w/cpp/utility/as_const)(x)` or similar. ``` int x = 4; auto y = [&r = x, x = x + 1]() -> int { r += 2; return x * x; }(); // updates ::x to 6 and initializes y to 25. ``` | (since C++14) | If a capture list has a capture-default and does not explicitly capture the enclosing object (as `this` or `*this`), or an automatic variable that is [odr-usable](definition#ODR-use "cpp/language/definition") in the lambda body, or a [structured binding](structured_binding "cpp/language/structured binding") whose corresponding variable has atomic storage duration (since C++20), it captures it *implicitly* if. * the body of the lambda [odr-uses](definition#ODR-use "cpp/language/definition") the entity | | | | --- | --- | | * or the entity is named in a potentially-evaluated expression within an expression that depends on a generic lambda parameter (until C++17) (including when the implicit `this->` is added before a use of non-static class member). For this purpose, the operand of [`typeid`](typeid "cpp/language/typeid") is always considered potentially-evaluated. Entities might be implicitly captured even if they are only named within a [discarded statement](if#Constexpr_if "cpp/language/if"). (since C++17) ``` void f(int, const int (&)[2] = {}) {} // #1 void f(const int&, const int (&)[1]) {} // #2 void test() { const int x = 17; auto g0 = [](auto a) { f(x); }; // OK: calls #1, does not capture x auto g1 = [=](auto a) { f(x); }; // does not capture x in C++14, captures x in C++17 // the capture can be optimized away auto g2 = [=](auto a) { int selector[sizeof(a) == 1 ? 1 : 2] = {}; f(x, selector); // OK: is a dependent expression, so captures x }; auto g3 = [=](auto a) { typeid(a + x); // captures x regardless of // whether a + x is an unevaluated operand }; } ``` | (since C++14) | If the body of a lambda [odr-uses](definition#ODR-use "cpp/language/definition") an entity captured by copy, the member of the closure type is accessed. If it is not odr-using the entity, the access is to the original object: ``` void f(const int*); void g() { const int N = 10; [=] { int arr[N]; // not an odr-use: refers to g's const int N f(&N); // odr-use: causes N to be captured (by copy) // &N is the address of the closure object's member N, not g's N }(); } ``` If a lambda odr-uses a reference that is captured by reference, it is using the object referred-to by the original reference, not the captured reference itself: ``` #include <iostream> auto make_function(int& x) { return [&]{ std::cout << x << '\n'; }; } int main() { int i = 3; auto f = make_function(i); // the use of x in f binds directly to i i = 5; f(); // OK: prints 5 } ``` Within the body of a lambda with capture default `=`, the type of any capturable entity is as if it were captured (and thus const-qualification is often added if the lambda is not `mutable`), even though the entity is in an unevaluated operand and not captured (e.g. in [`decltype`](decltype "cpp/language/decltype")): ``` void f3() { float x, &r = x; [=] { // x and r are not captured (appearance in a decltype operand is not an odr-use) decltype(x) y1; // y1 has type float decltype((x)) y2 = y1; // y2 has type float const& because this lambda // is not mutable and x is an lvalue decltype(r) r1 = y1; // r1 has type float& (transformation not considered) decltype((r)) r2 = y2; // r2 has type float const& }; } ``` Any entity captured by a lambda (implicitly or explicitly) is odr-used by the lambda-expression (therefore, implicit capture by a nested lambda triggers implicit capture in the enclosing lambda). All implicitly-captured variables must be declared within the *reaching scope* of the lambda. If a lambda captures the enclosing object (as `this` or `*this`), either the nearest enclosing function must be a non-static member function or the lambda must be in a [default member initializer](data_members#Member_initialization "cpp/language/data members"): ``` struct s2 { double ohseven = .007; auto f() // nearest enclosing function for the following two lambdas { return [this] // capture the enclosing s2 by reference { return [*this] // capture the enclosing s2 by copy (C++17) { return ohseven; // OK } }(); } auto g() { return [] // capture nothing { return [*this]{}; // error: *this not captured by outer lambda-expression }(); } }; ``` If a lambda expression (or an instantiation of a generic lambda's function call operator) (since C++14) ODR-uses `*this` or any variable with automatic storage duration, it must be captured by the lambda expression. ``` void f1(int i) { int const N = 20; auto m1 = [=] { int const M = 30; auto m2 = [i] { int x[N][M]; // N and M are not odr-used // (ok that they are not captured) x[0][0] = i; // i is explicitly captured by m2 // and implicitly captured by m1 }; }; struct s1 // local class within f1() { int f; void work(int n) // non-static member function { int m = n * n; int j = 40; auto m3 = [this, m] { auto m4 = [&, j] // error: j is not captured by m3 { int x = n; // error: n is implicitly captured by m4 // but not captured by m3 x += m; // OK: m is implicitly captured by m4 // and explicitly captured by m3 x += i; // error: i is outside of the reaching scope // (which ends at work()) x += f; // OK: this is captured implicitly by m4 // and explicitly captured by m3 }; }; } }; } ``` Class members cannot be captured explicitly by a capture without initializer (as mentioned above, only [variables](object "cpp/language/object") are permitted in the capture list): ``` class S { int x = 0; void f() { int i = 0; // auto l1 = [i, x]{ use(i, x); }; // error: x is not a variable auto l2 = [i, x=x]{ use(i, x); }; // OK, copy capture i = 1; x = 1; l2(); // calls use(0,0) auto l3 = [i, &x=x]{ use(i, x); }; // OK, reference capture i = 2; x = 2; l3(); // calls use(1,2) } }; ``` When a lambda captures a member using implicit by-copy capture, it does not make a copy of that member variable: the use of a member variable `m` is treated as an expression `(*this).m`, and `*this` is always implicitly captured by reference: ``` class S { int x = 0; void f() { int i = 0; auto l1 = [=]{ use(i, x); }; // captures a copy of i and // a copy of the this pointer i = 1; x = 1; l1(); // calls use(0, 1), as if // i by copy and x by reference auto l2 = [i, this]{ use(i, x); }; // same as above, made explicit i = 2; x = 2; l2(); // calls use(1, 2), as if // i by copy and x by reference auto l3 = [&]{ use(i, x); }; // captures i by reference and // a copy of the this pointer i = 3; x = 2; l3(); // calls use(3, 2), as if // i and x are both by reference auto l4 = [i, *this]{ use(i, x); }; // makes a copy of *this, // including a copy of x i = 4; x = 4; l4(); // calls use(3, 2), as if // i and x are both by copy } }; ``` | | | | --- | --- | | If a lambda expression appears in a [default argument](default_arguments "cpp/language/default arguments"), it cannot explicitly or implicitly capture anything, unless all captures have initializers which satisfy the constraints of an expression appearing in a default argument (since C++14): ``` void f2() { int i = 1; void g1(int = ([i]{ return i; })()); // error: captures something void g2(int = ([i]{ return 0; })()); // error: captures something void g3(int = ([=]{ return i; })()); // error: captures something void g4(int = ([=]{ return 0; })()); // OK: capture-less void g5(int = ([]{ return sizeof i; })()); // OK: capture-less // C++14 void g6(int = ([x = 1] { return x; }))(); // OK: 1 can appear // in a default argument void g7(int = ([x = i] { return x; }))(); // error: i cannot appear // in a default argument } ``` | (since C++11) | Members of [anonymous unions](union "cpp/language/union") members cannot be captured. [Bit-fields](bit_field "cpp/language/bit field") can only captured by copy. If a nested lambda `m2` captures something that is also captured by the immediately enclosing lambda `m1`, then `m2`'s capture is transformed as follows: * if the enclosing lambda `m1` captures by copy, `m2` is capturing the non-static member of `m1`'s closure type, not the original variable or `*this`; if `m1` is not mutable, the non-static data member is considered to be const-qualified. * if the enclosing lambda `m1` captures by reference, `m2` is capturing the original variable or `*this`. ``` #include <iostream> int main() { int a = 1, b = 1, c = 1; auto m1 = [a, &b, &c]() mutable { auto m2 = [a, b, &c]() mutable { std::cout << a << b << c << '\n'; a = 4; b = 4; c = 4; }; a = 3; b = 3; c = 3; m2(); }; a = 2; b = 2; c = 2; m1(); // calls m2() and prints 123 std::cout << a << b << c << '\n'; // prints 234 } ``` ### Example This example shows how to pass a lambda to a generic algorithm and how objects resulting from a lambda expression can be stored in `[std::function](../utility/functional/function "cpp/utility/functional/function")` objects. ``` #include <vector> #include <iostream> #include <algorithm> #include <functional> int main() { std::vector<int> c = {1, 2, 3, 4, 5, 6, 7}; int x = 5; c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; }), c.end()); std::cout << "c: "; std::for_each(c.begin(), c.end(), [](int i){ std::cout << i << ' '; }); std::cout << '\n'; // the type of a closure cannot be named, but can be inferred with auto // since C++14, lambda could own default arguments auto func1 = [](int i = 6) { return i + 4; }; std::cout << "func1: " << func1() << '\n'; // like all callable objects, closures can be captured in std::function // (this may incur unnecessary overhead) std::function<int(int)> func2 = [](int i) { return i + 4; }; std::cout << "func2: " << func2(6) << '\n'; constexpr int fib_max {8}; std::cout << "Emulate `recursive lambda` calls:\nFibonacci numbers: "; auto nth_fibonacci = [](int n) { std::function<int(int, int, int)> fib = [&](int n, int a, int b) { return n ? fib(n - 1, a + b, a) : b; }; return fib(n, 0, 1); }; for (int i{1}; i <= fib_max; ++i) { std::cout << nth_fibonacci(i) << (i < fib_max ? ", " : "\n"); } std::cout << "Alternative approach to lambda recursion:\nFibonacci numbers: "; auto nth_fibonacci2 = [](auto self, int n, int a = 0, int b = 1) -> int { return n ? self(self, n - 1, a + b, a) : b; }; for (int i{1}; i <= fib_max; ++i) { std::cout << nth_fibonacci2(nth_fibonacci2, i) << (i < fib_max ? ", " : "\n"); } #ifdef __cpp_explicit_this_parameter std::cout << "C++23 approach to lambda recursion:\n"; auto nth_fibonacci3 = [](this auto self, int n, int a = 0, int b = 1) { return n ? self(n - 1, a + b, a) : b; }; for (int i{1}; i <= fib_max; ++i) { std::cout << nth_fibonacci3(i) << (i < fib_max ? ", " : "\n"); } #endif } ``` Possible output: ``` c: 5 6 7 func1: 10 func2: 10 Emulate `recursive lambda` calls: Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13 Alternative approach to lambda recursion: Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 974](https://cplusplus.github.io/CWG/issues/974.html) | C++11 | default argument was not allowed in theparameter list of a lambda expression | allowed | | [CWG 975](https://cplusplus.github.io/CWG/issues/975.html) | C++11 | the return type of closure's `operator()` was onlydeduced if lambda body contains a single return | deduced as if for C++14auto-returning function | | [CWG 1249](https://cplusplus.github.io/CWG/issues/1249.html) | C++11 | it is not clear that whether the captured member of theenclosing non-mutable lambda is considered `const` or not | considered `const` | | [CWG 1557](https://cplusplus.github.io/CWG/issues/1557.html) | C++11 | the language linkage of the returned function type ofthe closure type's conversion function was not specified | it has C++language linkage | | [CWG 1607](https://cplusplus.github.io/CWG/issues/1607.html) | C++11 | lambda expressions could appear infunction and function template signatures | not allowed | | [CWG 1612](https://cplusplus.github.io/CWG/issues/1612.html) | C++11 | members of anonymous unions could be captured | not allowed | | [CWG 1722](https://cplusplus.github.io/CWG/issues/1722.html) | C++11 | the conversion function for captureless lambdashad unspecified exception specification | conversion functionis noexcept | | [CWG 1772](https://cplusplus.github.io/CWG/issues/1772.html) | C++11 | the semantic of `__func__` in lambda body was not clear | it refers to the closureclass's operator() | | [CWG 1780](https://cplusplus.github.io/CWG/issues/1780.html) | C++14 | it was unclear whether the members of the closure types of genericlambdas can be explicitly instantiated or explicitly specialized | neither is allowed | | [CWG 1891](https://cplusplus.github.io/CWG/issues/1891.html) | C++11 | closure had a deleted default constructorand implicit copy/move constructors | no default and defaultedcopy/move constructors | | [CWG 1937](https://cplusplus.github.io/CWG/issues/1937.html) | C++11 | as for the effect of invoking the result of the conversion function, it wasunspecified on which object calling its operator() has the same effect | on a default-constructedinstance of the closure type | | [CWG 2011](https://cplusplus.github.io/CWG/issues/2011.html) | C++11 | for a reference captured by reference, it was unspecifiedwhich entity the identifier of the capture refers to | it refers to the originallyreferenced entity | | [CWG 2095](https://cplusplus.github.io/CWG/issues/2095.html) | C++11 | the behavior of capturing rvalue referencesto functions by copy was not clear | made clear | | [CWG 2211](https://cplusplus.github.io/CWG/issues/2211.html) | C++11 | the behavior was unspecified if a capturehas the same name as a parameter | the program is ill-formed in this case | | [CWG 2358](https://cplusplus.github.io/CWG/issues/2358.html) | C++14 | lambda expressions appearing in default arguments hadto be capture-less even if all captures are initialized withexpressions which can appear in default arguments | allow such lambdaexpressions with captures | | [CWG 2509](https://cplusplus.github.io/CWG/issues/2509.html) | C++17 | each specifier could have multipleoccurences in the specifier sequence | each specifier can onlyappear at most once inthe specifier sequence | ### See also | | | | --- | --- | | [`auto` specifier](auto "cpp/language/auto") (C++11) | specifies a type deduced from an expression | | [function](../utility/functional/function "cpp/utility/functional/function") (C++11) | wraps callable object of any copy constructible type with specified function call signature (class template) | | [move\_only\_function](../utility/functional/move_only_function "cpp/utility/functional/move only function") (C++23) | wraps callable object of any type with specified function call signature (class template) | ### External links * [Nested function](https://en.wikipedia.org/wiki/Nested_function "enwiki:Nested function") - a function which is defined within another (*enclosing*) function.
programming_docs
cpp Modules (since C++20) Modules (since C++20) ===================== Most C++ projects use multiple translation units, and so they need to share [declarations](declarations "cpp/language/declarations") and [definitions](definition "cpp/language/definition") across those units. The usage of header files is prominent for this purpose, an example being the standard library whose declarations are provided by [`#include`](../preprocessor/include "cpp/preprocessor/include")-ing the corresponding header. Modules are a language feature to share declarations and definitions across translation units. They are an alternative to some use cases of header files. Modules are orthogonal to [namespaces](namespace "cpp/language/namespace"). ``` // helloworld.cpp export module helloworld; // module declaration import <iostream>; // import declaration export void hello() { // export declaration std::cout << "Hello world!\n"; } ``` ``` // main.cpp import helloworld; // import declaration int main() { hello(); } ``` ### Syntax | | | | | --- | --- | --- | | `export`(optional) `module` module-name module-partition(optional) attr(optional) `;` | (1) | | | `export` declaration | (2) | | | `export` `{` declaration-seq(optional) `}` | (3) | | | `export`(optional) `import` module-name attr(optional) `;` | (4) | | | `export`(optional) `import` module-partition attr(optional) `;` | (5) | | | `export`(optional) `import` header-name attr(optional) `;` | (6) | | | `module` `;` | (7) | | | `module : private` `;` | (8) | | 1) Module declaration. Declares that the current translation unit is a *module unit*. 2,3) Export declaration. Export all namespace-scope declarations in declaration or declaration-seq. 4,5,6) Import declaration. Import a module unit/module partition/header unit. 7) Starts a *global module fragment*. 8) Starts a *private module fragment*. ### Module declarations Translation units may have a module declaration, in which case they are considered *module unit*. The *module declaration*, if provided, must be the first declaration of the translation unit (excepted the *global module fragment*, which is covered later on). Each module unit is associated to a *module name* (and optionally a partition), provided in the module declaration. | | | | | --- | --- | --- | | `export`(optional) `module` module-name module-partition(optional) attr(optional) `;` | | | The module name consists of one or more identifiers separated by dots (for example: `mymodule`, `mymodule.mysubmodule`, `mymodule2`...). Dots have no intrinsic meaning, however they are used informally to represent hierarchy. A *named module* is the collection of module units with the same module name. Module units whose declaration has the keyword `export` are *module interface units*. Other module units are called *module implementation units*. For every named module, there must be exactly one module interface unit with no module partition specified. This module unit is called *primary module interface unit*. Its exported content will be available when importing the corresponding named module. ``` // (each line represents a separate translation unit) export module A; // declares the primary module interface unit for named module 'A' module A; // declares a module implementation unit for named module 'A' module A; // declares another module implementation unit for named module 'A' export module A.B; // declares the primary module interface unit for named module 'A.B' module A.B; // declares a module implementation unit for named module 'A.B' ``` ### Exporting declarations and definitions Module interface units can export declarations and definitions, which can be imported by other translation units. They can either be prefixed by the `export` keyword, or be inside an `export` block. | | | | | --- | --- | --- | | `export` declaration | | | | `export` `{` declaration-seq(optional) `}` | | | ``` export module A; // declares the primary module interface unit for named module 'A' // hello() will be visible by translations units importing 'A' export char const* hello() { return "hello"; } // world() will NOT be visible. char const* world() { return "world"; } // Both one() and zero() will be visible. export { int one() { return 1; } int zero() { return 0; } } // Exporting namespaces also works: hi::english() and hi::french() will be visible. export namespace hi { char const* english() { return "Hi!"; } char const* french() { return "Salut!"; } } ``` ### Importing modules and headers Modules can be imported with an *import declaration*: | | | | | --- | --- | --- | | `export`(optional) `import` module-name attr(optional) `;` | | | All declarations and definitions exported in the module interface units of the given named module will be available in the translation unit using the import declaration. Import declarations can be exported in a module interface unit. That is, if module A export-imports B, then importing A will also make visible all exports from B. In module units, all import declarations (including export-imports) must be grouped after the module declaration and before all other declarations. ``` /////// A.cpp (primary module interface unit of 'A') export module A; export char const* hello() { return "hello"; } /////// B.cpp (primary module interface unit of 'B') export module B; export import A; export char const* world() { return "world"; } /////// main.cpp (not a module unit) #include <iostream> import B; int main() { std::cout << hello() << ' ' << world() << '\n'; } ``` [`#include`](../preprocessor/include "cpp/preprocessor/include") should not be used in a module unit (outside the *global module fragment*), because all included declarations and definitions would be considered part of the module. Instead, headers can also be imported with an *import declaration*: | | | | | --- | --- | --- | | `export`(optional) `import` header-name attr(optional) `;` | | | Importing a header file will make accessible all its definitions and declarations. Preprocessor macros are also accessible (because import declarations are recognized by the preprocessor). However, contrary to `#include`, preprocessing macros defined in the translation unit will not affect the processing of the header file. This may be inconvenient in some cases (some header files uses preprocessing macros as a form of configuration), in which case the usage of *global module fragment* is needed. ``` /////// A.cpp (primary module interface unit of 'A') export module A; import <iostream>; export import <string_view>; export void print(std::string_view message) { std::cout << message << std::endl; } /////// main.cpp (not a module unit) import A; int main() { std::string_view message = "Hello, world!"; print(message); } ``` ### Global module fragment Module units can be prefixed by a *global module fragment*, which can be used to include header files when importing them is not possible (notably when the header file uses preprocessing macros as configuration). | | | | | --- | --- | --- | | `module;` preprocessing-directives(optional). module-declaration. | | | If a module-unit has a global module fragment, then its first declaration must be `module;`. Then, only [preprocessing directives](../preprocessor#Directives "cpp/preprocessor") can appear in the global module fragment. Then, a standard module declaration marks the end of the global module fragment and the start of the module content. ``` /////// A.cpp (primary module interface unit of 'A') module; // Defining _POSIX_C_SOURCE adds functions to standard headers, // according to the POSIX standard. #define _POSIX_C_SOURCE 200809L #include <stdlib.h> export module A; import <ctime>; // Only for demonstration (bad source of randomness). Use C++ <random> instead. export double weak_random() { std::timespec ts; std::timespec_get(&ts, TIME_UTC); // from <ctime> // Provided in <stdlib.h> according to the POSIX standard. srand48(ts.tv_nsec); // drand48() returns a random number between 0 and 1. return drand48(); } /////// main.cpp (not a module unit) import <iostream>; import A; int main() { std::cout << "Random value between 0 and 1: " << weak_random() << '\n'; } ``` ### Private module fragment Primary module interface unit can be suffixed by a *private module fragment*, which allows a module to be represented as a single translation unit without making all of the contents of the module reachable to importers. | | | | | --- | --- | --- | | `module : private` `;` declaration-seq(optional). | | | *Private module fragment* ends the portion of the module interface unit that can affect the behavior of other translation units. If a module unit contains a *private module fragment*, it will be the only module unit of its module. ``` export module foo; export int f(); module :private; // ends the portion of the module interface unit that // can affect the behavior of other translation units // starts a private module fragment int f() { // definition not reachable from importers of foo return 42; } ``` ### Module partitions A module can have *module partition units*. They are module units whose module declarations include a module partition, which starts with a colon `:` and is placed after the module name. ``` export module A:B; // Declares a module interface unit for module 'A', partition ':B'. ``` A module partition represents exactly one module unit (two module units cannot designate the same module partition). They are visible only from inside the named module (translation units outside the named module cannot import a module partition directly). A module partition can be imported by module units of the same named module. | | | | | --- | --- | --- | | `export`(optional) `import` module-partition attr(optional) `;` | | | ``` /////// A-B.cpp export module A:B; ... /////// A-C.cpp module A:C; ... /////// A.cpp export module A; import :C; export import :B; ... ``` All definitions and declarations in a module partition are visible by the importing module unit, whether exported or not. Module partitions can be module interface units (when their module declarations have `export`). They must be export-imported by the primary module interface unit, and their exported statements will be visible when the module is imported. | | | | | --- | --- | --- | | `export`(optional) `import` module-partition attr(optional) `;` | | | ``` /////// A.cpp export module A; // primary module interface unit export import :B; // Hello() is visible when importing 'A'. import :C; // WorldImpl() is now visible only for 'A.cpp'. // export import :C; // ERROR: Cannot export a module implementation unit. // World() is visible by any translation unit importing 'A'. export char const* World() { return WorldImpl(); } ``` ``` /////// A-B.cpp export module A:B; // partition module interface unit // Hello() is visible by any translation unit importing 'A'. export char const* Hello() { return "Hello"; } ``` ``` /////// A-C.cpp module A:C; // partition module implementation unit // WorldImpl() is visible by any module unit of 'A' importing ':C'. char const* WorldImpl() { return "World"; } ``` ``` /////// main.cpp import A; import <iostream>; int main() { std::cout << Hello() << ' ' << World() << '\n'; // WorldImpl(); // ERROR: WorldImpl() is not visible. } ``` ### Keywords [`export`](../keyword/export "cpp/keyword/export"), [`import`](../keyword/import "cpp/keyword/import"), [`module`](../keyword/module "cpp/keyword/module"). cpp try-block try-block ========= Associates one or more exception handlers (catch-clauses) with a compound statement. ### Syntax | | | | | --- | --- | --- | | `try` compound-statement handler-sequence | | | where handler-sequence is a sequence of one or more handlers, which have the following syntax: | | | | | --- | --- | --- | | `catch` `(` attr(optional) type-specifier-seq declarator `)` compound-statement | (1) | | | `catch` `(` attr(optional) type-specifier-seq abstract-declarator(optional) `)` compound-statement | (2) | | | `catch` `(` `...` `)` compound-statement | (3) | | | | | | | --- | --- | --- | | compound-statement | - | brace-enclosed [sequence of statements](statements#Compound_statements "cpp/language/statements") | | attr | - | (since C++11) any number of [attributes](attributes "cpp/language/attributes"), applies to the formal parameter | | type-specifier-seq | - | part of a formal parameter declaration, same as in a [function](function "cpp/language/function") parameter list | | declarator | - | part of a formal parameter declaration, same as in a [function](function "cpp/language/function") parameter list | | abstract-declarator | - | part of an unnamed formal parameter declaration, same as in [function](function "cpp/language/function") parameter list | 1) Catch-clause that declares a named formal parameter ``` try { /* */ } catch (const std::exception& e) { /* */ } ``` 2) Catch-clause that declares an unnamed parameter ``` try { /* */ } catch (const std::exception&) { /* */ } ``` 3) Catch-all handler, which is activated for any exception ``` try { /* */ } catch (...) { /* */ } ``` ### Explanation See [throw exceptions](throw "cpp/language/throw") for more information about throw-expressions A try-block is a [statement](statements "cpp/language/statements"), and as such, can appear anywhere a statement can appear (that is, as one of the statements in a compound statement, including the function body compound statement). See [function-try-block](function-try-block "cpp/language/function-try-block") for the try blocks around function bodies. The following description applies to both try-blocks and [function-try-blocks](function-try-block "cpp/language/function-try-block"). The formal parameter of the catch clause (type-specifier-seq and declarator or type-specifier-seq and abstract-declarator) determines which types of exceptions cause this catch clause to be entered. It cannot be an [incomplete type](incomplete_type "cpp/language/incomplete type"), [abstract class](abstract_class "cpp/language/abstract class") type, [rvalue reference](reference "cpp/language/reference") type, (since C++11) or pointer to incomplete type (except that pointers to (possibly [cv](cv "cpp/language/cv")-qualified) `void` are allowed). If the type of the formal parameter is array type or function type, it is treated as the corresponding pointer type (similar to a [function declaration](function "cpp/language/function")). When an exception is thrown by any statement in compound-statement, the [exception object](throw#The_exception_object "cpp/language/throw") of type `E` is matched against the types of the formal parameters `T` of each catch-clause in handler-seq, in the order in which the catch clauses are listed. The exception is a match if any of the following is true: * `E` and `T` are the same type (ignoring top-level cv-qualifiers on `T`) * `T` is an lvalue-reference to (possibly cv-qualified) `E` * `T` is an unambiguous public base class of `E` * `T` is a reference to an unambiguous public base class of `E` * `T` is (possibly cv-qualified) `U` or `const U&` (since C++14), and `U` is a pointer or pointer to member type, and `E` is also a pointer or pointer to member type that is implicitly convertible to `U` by one or more of + a standard [pointer conversion](implicit_cast#Pointer_conversions "cpp/language/implicit cast") other than one to a private, protected, or ambiguous base class + a [qualification conversion](implicit_cast#Qualification_conversions "cpp/language/implicit cast") | | | | --- | --- | | * a [function pointer conversion](implicit_cast#Function_pointer_conversions "cpp/language/implicit cast") | (since C++17) | | | | | --- | --- | | * `T` is a pointer or a pointer to member or a reference to a const pointer (since C++14), while `E` is `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")`. | (since C++11) | ``` try { f(); } catch (const std::overflow_error& e) {} // this executes if f() throws std::overflow_error (same type rule) catch (const std::runtime_error& e) {} // this executes if f() throws std::underflow_error (base class rule) catch (const std::exception& e) {} // this executes if f() throws std::logic_error (base class rule) catch (...) {} // this executes if f() throws std::string or int or any other unrelated type ``` The catch-all clause `catch (...)` matches exceptions of any type. If present, it has to be the last catch clause in the handler-seq. Catch-all block may be used to ensure that no uncaught exceptions can possibly escape from a function that offers [nothrow exception guarantee](exceptions "cpp/language/exceptions"). If no matches are found after all catch-clauses were examined, the exception propagation continues to the containing try-block, as described in [throw-expression](throw "cpp/language/throw"). If there are no containing try-blocks left, `[std::terminate](../error/terminate "cpp/error/terminate")` is executed (in this case, it is implementation-defined whether any stack unwinding occurs at all: throwing an uncaught exception is permitted to terminate the program without invoking any destructors). When entering a catch clause, if its formal parameter is a base class of the exception type, it is [copy-initialized](copy_initialization "cpp/language/copy initialization") from the base class subobject of the exception object. Otherwise, it is copy-initialized from the exception object (this copy is subject to [copy elision](copy_elision "cpp/language/copy elision")). ``` try { std::string("abc").substr(10); // throws std::length_error } // catch (std::exception e) // copy-initialization from the std::exception base // { // std::cout << e.what(); // information from length_error is lost // } catch (const std::exception& e) // reference to the base of a polymorphic object { std::cout << e.what(); // information from length_error printed } ``` If the parameter of the catch-clause is a reference type, any changes made to it are reflected in the exception object, and can be observed by another handler if the exception is rethrown with `throw;`. If the parameter is not a reference, any changes made to it are local and its lifetime ends when the handler exits. | | | | --- | --- | | Within a catch-clause, `[std::current\_exception](../error/current_exception "cpp/error/current exception")` can be used to capture the exception in an `[std::exception\_ptr](../error/exception_ptr "cpp/error/exception ptr")`, and `[std::throw\_with\_nested](../error/throw_with_nested "cpp/error/throw with nested")` may be used to build nested exceptions. | (since C++11) | A [goto](goto "cpp/language/goto") or [switch](switch "cpp/language/switch") statement shall not be used to transfer control into a try block or into a handler. Other than by throwing or rethrowing the exception, the catch-clause after a regular try block (not [function-try-block](function-try-block "cpp/language/function-try-block")) may be exited with a [return](return "cpp/language/return"), [continue](continue "cpp/language/continue"), [break](break "cpp/language/break"), [goto](goto "cpp/language/goto"), or by reaching the end of its compound-statement. In any case, this destroys the exception object (unless an instance of `[std::exception\_ptr](../error/exception_ptr "cpp/error/exception ptr")` exists that refers to it). ### Notes The throw-expression `throw [NULL](http://en.cppreference.com/w/cpp/types/NULL);` is not guaranteed to be matched by a pointer catch clause, because the exception object type may be `int`, but `throw nullptr;` is assuredly matched by any pointer or pointer-to-member catch clause. If a catch-clause for a derived class is placed after the catch-clause for a base class, the derived catch-clause will never be executed: ``` try { f(); } catch (const std::exception& e) {} // will be executed if f() throws std::runtime_error catch (const std::runtime_error& e) {} // dead code! ``` If [goto](goto "cpp/language/goto") is used to exit a try-block and if any of the destructors of block-scoped automatic variables that are executed by the `goto` throw exceptions, those exceptions are caught by the try blocks in which the variables are defined: ``` label: try { T1 t1; try { T2 t2; if (condition) goto label; // destroys t2, then destroys t1, then jumps to label } catch (...) {} // catches the exception from the destructor of t2 } catch (...) {} // catches the exception from the destructor of t1 ``` ### Keywords [`try`](../keyword/try "cpp/keyword/try"), [`catch`](../keyword/catch "cpp/keyword/catch"), [`throw`](../keyword/throw "cpp/keyword/throw"). ### Example The following example demonstrates several usage cases of the `try-catch` block. ``` #include <iostream> #include <vector> int main() { try { std::cout << "Throwing an integer exception...\n"; throw 42; } catch (int i) { std::cout << " the integer exception was caught, with value: " << i << '\n'; } try { std::cout << "Creating a vector of size 5... \n"; std::vector<int> v(5); std::cout << "Accessing the 11th element of the vector...\n"; std::cout << v.at(10); // vector::at() throws std::out_of_range } catch (const std::exception& e) // caught by reference to base { std::cout << " a standard exception was caught, with message '" << e.what() << "'\n"; } } ``` Possible output: ``` Throwing an integer exception... the integer exception was caught, with value: 42 Creating a vector of size 5... Accessing the 11th element of the vector... a standard exception was caught, with message 'out_of_range' ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 98](https://cplusplus.github.io/CWG/issues/98.html) | C++98 | a switch statement can transfer controlinto a try block or into a handler | prohibited | | [CWG 210](https://cplusplus.github.io/CWG/issues/210.html) | C++98 | the throw expression was matched against the catch clauses | the exception object is matchedagainst the catch clauses | | [CWG 1166](https://cplusplus.github.io/CWG/issues/1166.html) | C++98 | the behavior was unspecified when a catch clause whoseexception type is a reference to an abstract class type is matched | abstract class types are notallowed for catch clauses | | [CWG 1769](https://cplusplus.github.io/CWG/issues/1769.html) | C++98 | when the type of the exception declared in the catch-clause is abase of the type of the exception object, a converting constructormight be used for the initialization of the catch-clause parameter | the parameter is copy-initializedfrom the corresponding base classsubobject of the exception object | | [CWG 2093](https://cplusplus.github.io/CWG/issues/2093.html) | C++98 | an exception object of pointer to object type could not match ahandler of pointer to object type through qualification conversion | allowed |
programming_docs
cpp Translation-unit-local entities (since C++20) Translation-unit-local entities (since C++20) ============================================= Translation-unit-local (TU-local) entities are introduced to prevent entities that are supposed to be local (not used in any other translation unit) being exposed and used in other translation units. An example from [Understanding C++ Modules: Part 2](https://vector-of-bool.github.io/2019/03/31/modules-2.html) illustrates the problem of not constraining exposures: ``` // Module unit without TU-local constraints export module Foo; import <iostream>; namespace { class LolWatchThis { // internal linkage, cannot be exported static void say_hello() { std::cout << "Hello, everyone!\n"; } }; } export LolWatchThis lolwut() { // LolWatchThis is exposed as return type return LolWatchThis(); } ``` ``` // main.cpp import Foo; int main() { auto evil = lolwut(); // 'evil' has type of 'LolWatchThis' decltype(evil)::say_hello(); // definition of 'LolWatchThis' is not internal anymore } ``` ### TU-local entities An entity is *TU-local* if it is. 1. a type, function, variable, or template that 1. has a name with [internal linkage](storage_duration#internal_linkage "cpp/language/storage duration"), or 2. does not have a name with linkage and is declared, or introduced by a [lambda expression](lambda "cpp/language/lambda"), within the definition of a TU-local entity, 2. a type with no name that is defined outside a [class-specifier](class "cpp/language/class"), function body, or initializer or is introduced by a defining-type-specifier (type-specifier, class-specifier or enum-specifier) that is used to declare only TU-local entities, 3. a specialization of a TU-local template, 4. a specialization of a template with any TU-local template argument, or 5. a specialization of a template whose (possibly instantiated) declaration is an exposure (defined below). ``` // TU-local entities with internal linkage namespace { // all names declared in unnamed namespace have internal linkage int tul_var = 1; // TU-local variable int tul_func() { return 1; } // TU-local function struct tul_type { int mem; }; // TU-local (class) type } template<typename T> static int tul_func_temp() { return 1; } // TU-local template // TU-local template specialization template<> static int tul_func_temp<int>() { return 3; } // TU-local specialization // template specialization with TU-local template argument template <> struct std::hash<tul_type> { // TU-local specialization std::size_t operator()(const tul_type& t) const { return 4u; } }; ``` A value or object is *TU-local* if either. 1. it is, or is a pointer to, a TU-local function or the object associated with a TU-local variable, or 2. it is an object of class or array type and any of its [subobjects](object#Subobjects "cpp/language/object") or any of the objects or functions to which its non-static data members of reference type refer is TU-local and is [usable in constant expressions](constant_expression#Usable_in_constant_expressions "cpp/language/constant expression"). ``` static int tul_var = 1; // TU-local variable static int tul_func() { return 1; } // TU-local function int* tul_var_ptr = &tul_var; // TU-local: pointer to TU-local variable int (* tul_func_ptr)() = &tul_func; // TU-local: pointer to TU-local function constexpr static int tul_const = 1; // TU-local variable usable in constant expressions int tul_arr[] = { tul_const }; // TU-local: array of constexpr TU-local object struct tul_class { int mem; }; tul_class tul_obj{tul_const}; // TU-local: has member constexpr TU-local object ``` ### Exposures A declaration D *names* an entity E if. 1. D contains a lambda expression whose closure type is E, 2. E is not a function or function template and D contains an id-expression, type-specifier, nested-name-specifier, template-name, or concept-name denoting E, or 3. E is a function or function template and D contains an expression that names E or an id-expression that refers to a set of overloads that contains E. ``` // lambda naming auto x = [] {}; // names decltype(x) // non-function (template) naming int y1 = 1; // names y1 (id-expression) struct y2 { int mem; }; y2 y2_obj{1}; // names y2 (type-specifier) struct y3 { int mem_func(); }; int y3::mem_func() { return 0; } // names y3 (nested-name-specifier) template<typename T> int y4 = 1; int var = y4<y2>; // names y4 (template-name) template<typename T> concept y5 = true; template<typename T> void func(T&&) requires y5<T>; // names y5 (concept-name) // function (template) naming int z1(int arg) { std::cout << "no overload"; return 0; } int z2(int arg) { std::cout << "overload 1"; return 1; } int z2(double arg) { std::cout << "overload 2"; return 2; } int val1 = z1(0); // names z1 int val2 = z2(0); // names z2 ( int z2(int) ) ``` A declaration is an *exposure* if it either names a TU-local entity, ignoring. 1. the function-body for a non-inline function or function template (but not the deduced return type for a (possibly instantiated) definition of a function with a declared return type that uses a [placeholder type](auto "cpp/language/auto")), 2. the initializer for a variable or variable template (but not the variable’s type), 3. friend declarations in a class definition, and 4. any reference to a non-volatile const object or reference with internal or no linkage initialized with a constant expression that is not an [odr-use](definition#ODR-use "cpp/language/definition") , or defines a constexpr variable initialized to a TU-local value. ### TU-local constraints If a (possibly instantiated) [declaration](declarations "cpp/language/declarations") of, or a [deduction guide](class_template_argument_deduction#Deduction_for_class_templates "cpp/language/class template argument deduction") for, a non-TU-local entity in a [module interface unit](modules "cpp/language/modules") (outside the private-module-fragment, if any) or module partition is an exposure, the program is ill-formed. Such a declaration in any other context is deprecated. If a declaration that appears in one translation unit names a TU-local entity declared in another translation unit that is not a header unit, the program is ill-formed. A declaration instantiated for a template specialization appears at the point of instantiation of the specialization. ### Example Translation unit #1: ``` export module A; static void f() {} inline void it() { f(); } // error: is an exposure of f static inline void its() { f(); } // OK template<int> void g() { its(); } // OK template void g<0>(); decltype(f) *fp; // error: f (though not its type) is TU-local auto &fr = f; // OK constexpr auto &fr2 = fr; // error: is an exposure of f constexpr static auto fp2 = fr; // OK struct S { void (&ref)(); } s{f}; // OK: value is TU-local constexpr extern struct W { S &s; } wrap{s}; // OK: value is not TU-local static auto x = []{f();}; // OK auto x2 = x; // error: the closure type is TU-local int y = ([]{f();}(),0); // error: the closure type is not TU-local int y2 = (x,0); // OK namespace N { struct A {}; void adl(A); static void adl(int); } void adl(double); inline void h(auto x) { adl(x); } // OK, but a specialization might be an exposure ``` Translation unit #2: ``` module A; void other() { g<0>(); // OK: specialization is explicitly instantiated g<1>(); // error: instantiation uses TU-local its h(N::A{}); // error: overload set contains TU-local N::adl(int) h(0); // OK: calls adl(double) adl(N::A{}); // OK; N::adl(int) not found, calls N::adl(N::A) fr(); // OK: calls f constexpr auto ptr = fr; // error: fr is not usable in constant expressions here } ``` cpp Lifetime Lifetime ======== Every [object](object "cpp/language/object") and [reference](reference "cpp/language/reference") has a *lifetime*, which is a runtime property: for any object or reference, there is a point of execution of a program when its lifetime begins, and there is a moment when it ends. The lifetime of an object begins when: * storage with the proper alignment and size for its type is obtained, and * its initialization (if any) is complete (including [default initialization](default_initialization "cpp/language/default initialization") via no constructor or [trivial default constructor](default_constructor#Trivial_default_constructor "cpp/language/default constructor")), except that + if the object is a [union member](union#Member_lifetime "cpp/language/union") or subobject thereof, its lifetime only begins if that union member is the initialized member in the union, or it is made active, + if the object is nested in a union object, its lifetime may begin if the containing union object is assigned or constructed by a trivial special member function, + an array object's lifetime may also begin if it is allocated by `[std::allocator::allocate](../memory/allocator/allocate "cpp/memory/allocator/allocate")`. Some operations [implicitly create objects](object#Object_creation "cpp/language/object") of [implicit-lifetime types](../named_req/implicitlifetimetype "cpp/named req/ImplicitLifetimeType") in given region of storage and start their lifetime. If a subobject of an implicitly created object is not of an implicit-lifetime type, its lifetime does not begin implicitly. The lifetime of an object ends when: * if it is of a non-class type, the object is destroyed (maybe via a pseudo-destructor call), or * if it is of a class type, the [destructor](destructor "cpp/language/destructor") call starts, or * the storage which the object occupies is released, or is reused by an object that is not nested within it. Lifetime of an object is equal to or is nested within the lifetime of its storage, see [storage duration](storage_duration "cpp/language/storage duration"). The lifetime of a [reference](reference "cpp/language/reference") begins when its initialization is complete and ends as if it were a scalar object. Note: the lifetime of the referred object may end before the end of the lifetime of the reference, which makes [dangling references](reference#Dangling_references "cpp/language/reference") possible. Lifetimes of non-static data members and base subobjects begin and end following [class initialization order](initializer_list#Initialization_order "cpp/language/initializer list"). ### Temporary object lifetime Temporary objects are created when a prvalue is [materialized](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion") so that it can be used as a glvalue, which occurs (since C++17) in the following situations: * [binding a reference to a prvalue](reference_initialization "cpp/language/reference initialization") | | | | --- | --- | | * [initializing](list_initialization "cpp/language/list initialization") an object of type `[std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<T>` from a braced-init-list | (since C++11) | | | | | | | --- | --- | --- | --- | | * returning a prvalue from a function * [conversion](expressions#Conversions "cpp/language/expressions") that creates a prvalue ([including](explicit_cast "cpp/language/explicit cast") `T(a,b,c)` and `T{}`) | | | | --- | --- | | * [lambda expression](lambda "cpp/language/lambda") | (since C++11) | * [copy-initialization](copy_initialization "cpp/language/copy initialization") that requires conversion of the initializer, * [reference-initialization](reference_initialization "cpp/language/reference initialization") to a different but convertible type or to a bitfield. | (until C++17) | | * when performing [member access](operator_member_access#Built-in_member_access_operators "cpp/language/operator member access") on a class prvalue * when performing an [array-to-pointer](array#Array-to-pointer_decay "cpp/language/array") conversion or [subscripting](operator_member_access#Built-in_subscript_operator "cpp/language/operator member access") on an array prvalue * for unevaluated operands in [`sizeof`](sizeof "cpp/language/sizeof") and [`typeid`](typeid "cpp/language/typeid") * when a prvalue appears as a [discarded-value expression](expressions#Discarded-value_expressions "cpp/language/expressions") * if supported by the implementation, when passing or returning an object of trivially-copyable type in a [function call expression](operator_other#Built-in_function_call_operator "cpp/language/operator other") (this models passing structs in CPU registers) | (since C++17) | | | | | --- | --- | | The materialization of a temporary object is generally delayed as long as possible in order to avoid creating unnecessary temporary object: see [copy elision](copy_elision "cpp/language/copy elision"). | (since C++17) | All temporary objects are destroyed as the last step in evaluating the [full-expression](expressions#Full-expressions "cpp/language/expressions") that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that evaluation ends in throwing an exception. There are two exceptions from that: * The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see [reference initialization](reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization") for details. * The lifetime of a temporary object created when evaluating the default arguments of a default or copy constructor used to initialize or copy an element of an array ends before the next element of the array begins initialization. ### Storage reuse A program is not required to call the destructor of an object to end its lifetime if the object is [trivially-destructible](destructor#Trivial_destructor "cpp/language/destructor") or if the program does not rely on the side effects of the destructor. However, if a program ends the lifetime of an non-trivially destructible object that is a variable explicitly, it must ensure that a new object of the same type is constructed in-place (e.g. via placement new) before the destructor may be called implicitly, i.e. due to scope exit or exception for automatic objects, due to thread exit for thread-local objects, or due to program exit for static objects; otherwise the behavior is undefined. ``` class T {}; // trivial struct B { ~B() {} // non-trivial }; void x() { long long n; // automatic, trivial new (&n) double(3.14); // reuse with a different type okay } // okay void h() { B b; // automatic non-trivially destructible b.~B(); // end lifetime (not required, since no side-effects) new (&b) T; // wrong type: okay until the destructor is called } // destructor is called: undefined behavior ``` It is undefined behavior to reuse storage that is or was occupied by a const complete object of static, thread-local, or automatic storage duration because such objects may be stored in read-only memory. ``` struct B { B(); // non-trivial ~B(); // non-trivial }; const B b; // const static void h() { b.~B(); // end the lifetime of b new (const_cast<B*>(&b)) const B; // undefined behavior: attempted reuse of a const } ``` If a new object is created at the address that was occupied by another object, then all pointers, references, and the name of the original object will automatically refer to the new object and, once the lifetime of the new object begins, can be used to manipulate the new object, but only if the original object is transparently replaceable by the new object. Object `x` is *transparently replaceable* by object `y` if: * the storage for `y` exactly overlays the storage location which `x` occupied * `y` is of the same type as `x` (ignoring the top-level cv-qualifiers) * `x` is not a complete const object * neither `x` nor `y` is a base class subobject, or a member subobject declared with `[[[no\_unique\_address](attributes/no_unique_address "cpp/language/attributes/no unique address")]]` (since C++20) * either + `x` and `y` are both complete objects, or + `x` and `y` are direct subobjects of objects `ox` and `oy` respectively, and `ox` is transparently replaceable by `oy`. ``` struct C { int i; void f(); const C& operator=(const C&); }; const C& C::operator=(const C& other) { if (this != &other) { this->~C(); // lifetime of *this ends new (this) C(other); // new object of type C created f(); // well-defined } return *this; } C c1; C c2; c1 = c2; // well-defined c1.f(); // well-defined; c1 refers to a new object of type C ``` | | | | --- | --- | | If the conditions listed above are not met, a valid pointer to the new object may still be obtained by applying the pointer optimization barrier `[std::launder](../utility/launder "cpp/utility/launder")`: ``` struct A { virtual int transmogrify(); }; struct B : A { int transmogrify() override { ::new(this) A; return 2; } }; inline int A::transmogrify() { ::new(this) B; return 1; } void test() { A i; int n = i.transmogrify(); // int m = i.transmogrify(); // undefined behavior: // the new A object is a base subobject, while the old one is a complete object int m = std::launder(&i)->transmogrify(); // OK assert(m + n == 3); } ``` | (since C++17) | Similarly, if an object is created in the storage of a class member or array element, the created object is only a subobject (member or element) of the original object's containing object if: * the lifetime of the containing object has begun and not ended * the storage for the new object exactly overlays the storage of the original object * the new object is of the same type as the original object (ignoring cv-qualification). | | | | --- | --- | | Otherwise, the name of the original subobject cannot be used to access the new object without `[std::launder](../utility/launder "cpp/utility/launder")`: | (since C++17) | As a special case, objects can be created in arrays of `unsigned char` or [`std::byte`](../types/byte "cpp/types/byte") (since C++17) (in which case it is said that the array *provides storage* for the object) if. * the lifetime of the array has begun and not ended * the storage for the new object fits entirely within the array * there is no array object that satisfies these constraints nested within the array. If that portion of the array previously provided storage for another object, the lifetime of that object ends because its storage was reused, however the lifetime of the array itself does not end (its storage is not considered to have been reused). ``` template<typename... T> struct AlignedUnion { alignas(T...) unsigned char data[max(sizeof(T)...)]; }; int f() { AlignedUnion<int, char> au; int *p = new (au.data) int; // OK, au.data provides storage char *c = new (au.data) char(); // OK, ends lifetime of *p char *d = new (au.data + 1) char(); return *c + *d; // OK } ``` ### Access outside of lifetime Before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, the behaviors of the following uses of the glvalue expression that identifies that object are undefined, unless the object is being constructed or destructed (separate set of rules applies): 1. Lvalue to rvalue conversion (e.g. function call to a function that takes a value). 2. Access to a non-static data member or a call to a non-static member function. 3. Binding a reference to a virtual base class subobject. 4. [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") or [`typeid`](typeid "cpp/language/typeid") expressions. The above rules apply to pointers as well (binding a reference to virtual base is replaced by implicit conversion to a pointer to virtual base), with two additional rules: 1. [`static_cast`](static_cast "cpp/language/static cast") of a pointer to storage without an object is only allowed when casting to (possibly cv-qualified) `void*`. 2. Pointers to storage without an object that were cast to possibly cv-qualified `void*` can only be [`static_cast`](static_cast "cpp/language/static cast") to pointers to possibly cv-qualified `char`, or possibly cv-qualified `unsigned char`, or possibly cv-qualified [`std::byte`](../types/byte "cpp/types/byte") (since C++17). During construction and destruction it is generally allowed to call non-static member functions, access non-static data members, and use [`typeid`](typeid "cpp/language/typeid") and [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast"). However, because the lifetime either has not begun yet (during construction) or has already ended (during destruction), only specific operations are allowed. For one restriction, see [virtual function calls during construction and destruction](virtual#During_construction_and_destruction "cpp/language/virtual"). ### Notes Until the resolution of [core issue 2256](https://wg21.link/p1358r0#2256), the end of lifetime rules are different between non-class objects (end of storage duration) and class objects (reverse order of construction): ``` struct A { int* p; ~A() { std::cout << *p; } // undefined behavior since CWG2256: n does not outlive a // well-defined until CWG2256: prints 123 }; void f() { A a; int n = 123; // if n did not outlive a, this could have been optimized out (dead store) a.p = &n; } ``` Until the resolution of [RU007](https://wg21.link/p1971r0#RU007), a non-static member of a const-qualified type or a reference type prevents its containing object from being transparently replaceable, which makes `[std::vector](../container/vector "cpp/container/vector")` and `[std::deque](../container/deque "cpp/container/deque")` hard to implement: ``` struct X { const int n; }; union U { X x; float f; }; void tong() { U u = { { 1 } }; u.f = 5.f; // OK: creates new subobject of 'u' X *p = new (&u.x) X {2}; // OK: creates new subobject of 'u' assert(p->n == 2); // OK assert(u.x.n == 2); // undefined until RU007: // 'u.x' does not name the new subobject assert(*std::launder(&u.x.n) == 2); // OK even until RU007 } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 119](https://cplusplus.github.io/CWG/issues/119.html) | C++98 | an object of a class type with a non-trivial constructor canonly start its lifetime when theconstructor call has completed | lifetime also startedfor other initializations | | [CWG 201](https://cplusplus.github.io/CWG/issues/201.html) | C++98 | lifetime of a temporary object in a default argumentof a default constructor was required to endwhen the initialization of the array completes | lifetime ends beforeinitializing the next element(also resolves [CWG 124](https://cplusplus.github.io/CWG/issues/124.html)) | | [CWG 274](https://cplusplus.github.io/CWG/issues/274.html) | C++98 | an lvalue designating an out-of-lifetime object could beused as the operand of static\_cast only if the conversionwas ultimately to cv-unqualified `char&` or `unsigned char&` | cv-qualified `char&`and `unsigned char&`also allowed | | [CWG 597](https://cplusplus.github.io/CWG/issues/597.html) | C++98 | the following behaviors were undefined:1. a pointer to an out-of-lifetime object is implicitlyconverted to a pointer to a non-virtual base class2. an lvalue referring to an out-of-lifetime objectis bound to a reference to a non-virtual base class3. an lvalue referring to an out-of-lifetime object is usedas the operand of a `static_cast` (with a few exceptions) | made well-defined | | [CWG 2012](https://cplusplus.github.io/CWG/issues/2012.html) | C++98 | lifetime of references was specified to match storage duration,requiring that extern references are alive before their initializers run | lifetime beginsat initialization | | [CWG 2107](https://cplusplus.github.io/CWG/issues/2107.html) | C++98 | the resolution of [CWG 124](https://cplusplus.github.io/CWG/issues/124.html) was not applied to copy constructors | applied | | [P0137R1](https://wg21.link/P0137R1) | C++98 | creating an object in an array of `unsigned char` reused its storage | its storage is not reused | | [CWG 2256](https://cplusplus.github.io/CWG/issues/2256.html) | C++98 | lifetime of trivially destructible objects were inconsistent with other objects | made consistent | | [P1971R0](https://wg21.link/P1971R0) | C++98 | a non-static data member of a const-qualified type or a reference typeprevented its containing object from being transparently replaceable | restriction removed | | [P2103R0](https://wg21.link/P2103R0) | C++98 | transparently replaceability did not require keeping the original structure | requires | | [P0593R6](https://wg21.link/P0593R6) | C++98 | a pseudo-destructor call had no effects | it destroys the object | | [CWG 2470](https://cplusplus.github.io/CWG/issues/2470.html) | C++98 | more than one arrays may provide storage for the same object | only one provides | ### References * C++20 standard (ISO/IEC 14882:2020): + 6.7.3 Object lifetime [basic.life] + 11.10.4 Construction and destruction [class.cdtor] * C++17 standard (ISO/IEC 14882:2017): + 6.8 Object lifetime [basic.life] + 15.7 Construction and destruction [class.cdtor] * C++14 standard (ISO/IEC 14882:2014): + 3 Object lifetime [basic.life] + 12.7 Construction and destruction [class.cdtor] * C++11 standard (ISO/IEC 14882:2011): + 3.8 Object lifetime [basic.life] + 12.7 Construction and destruction [class.cdtor] * C++03 standard (ISO/IEC 14882:2003): + 3.8 Object lifetime [basic.life] + 12.7 Construction and destruction [class.cdtor] * C++98 standard (ISO/IEC 14882:1998): + 3.8 Object lifetime [basic.life] + 12.7 Construction and destruction [class.cdtor] ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/lifetime "c/language/lifetime") for Lifetime |
programming_docs
cpp Assignment operators Assignment operators ==================== Assignment operators modify the value of the object. | Operator name | Syntax | [Over​load​able](operators "cpp/language/operators") | Prototype examples (for `class T`) | | --- | --- | --- | --- | | Inside class definition | Outside class definition | | simple assignment | `a = b` | Yes | `T& T::operator =(const T2& b);` | N/A | | addition assignment | `a += b` | Yes | `T& T::operator +=(const T2& b);` | `T& operator +=(T& a, const T2& b);` | | subtraction assignment | `a -= b` | Yes | `T& T::operator -=(const T2& b);` | `T& operator -=(T& a, const T2& b);` | | multiplication assignment | `a *= b` | Yes | `T& T::operator *=(const T2& b);` | `T& operator *=(T& a, const T2& b);` | | division assignment | `a /= b` | Yes | `T& T::operator /=(const T2& b);` | `T& operator /=(T& a, const T2& b);` | | modulo assignment | `a %= b` | Yes | `T& T::operator %=(const T2& b);` | `T& operator %=(T& a, const T2& b);` | | bitwise AND assignment | `a &= b` | Yes | `T& T::operator &=(const T2& b);` | `T& operator &=(T& a, const T2& b);` | | bitwise OR assignment | `a |= b` | Yes | `T& T::operator |=(const T2& b);` | `T& operator |=(T& a, const T2& b);` | | bitwise XOR assignment | `a ^= b` | Yes | `T& T::operator ^=(const T2& b);` | `T& operator ^=(T& a, const T2& b);` | | bitwise left shift assignment | `a <<= b` | Yes | `T& T::operator <<=(const T2& b);` | `T& operator <<=(T& a, const T2& b);` | | bitwise right shift assignment | `a >>= b` | Yes | `T& T::operator >>=(const T2& b);` | `T& operator >>=(T& a, const T2& b);` | | **Notes*** All built-in assignment operators return `*this`, and most [user-defined overloads](operators "cpp/language/operators") also return `*this` so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including `void`). * `T2` can be any type including `T` | ### Explanation *copy assignment* operator replaces the contents of the object `a` with a copy of the contents of `b` (`b` is not modified). For class types, this is a special member function, described in [copy assignment operator](copy_assignment "cpp/language/copy assignment"). | | | | --- | --- | | *move assignment* operator replaces the contents of the object `a` with the contents of `b`, avoiding copying if possible (`b` may be modified). For class types, this is a special member function, described in [move assignment operator](move_assignment "cpp/language/move assignment"). | (since C++11) | For non-class types, copy and move assignment are indistinguishable and are referred to as *direct assignment*. *compound assignment* operators replace the contents of the object `a` with the result of a binary operation between the previous value of `a` and the value of `b`. #### Builtin direct assignment The direct assignment expressions have the form. | | | | | --- | --- | --- | | lhs `=` rhs | (1) | | | lhs `= {}` | (2) | (since C++11) | | lhs `= {` rhs `}` | (3) | (since C++11) | For the built-in operator, lhs may have any non-const scalar type and rhs must be implicitly convertible to the type of lhs. The direct assignment operator expects a modifiable lvalue as its left operand and an rvalue expression or a *braced-init-list* (since C++11) as its right operand, and returns an lvalue identifying the left operand after modification. The result is a bit-field if the left operand is a bit-field. For non-class types, the right operand is first [implicitly converted](implicit_conversion "cpp/language/implicit conversion") to the cv-unqualified type of the left operand, and then its value is copied into the object identified by left operand. When the left operand has reference type, the assignment operator modifies the referred-to object. If the left and the right operands identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same). | | | | --- | --- | | If the right operand is a *braced-init-list*.* if the expression `E1` has scalar type, + the expression `E1 = {}` is equivalent to `E1 = T{}`, where `T` is the type of `E1`. + the expression `E1 = {E2}` is equivalent to `E1 = T{E2}`, where `T` is the type of `E1`. * if the expression `E1` has class type, the syntax `E1 = {args...}` generates a call to the assignment operator with the *braced-init-list* as the argument, which then selects the appropriate assignment operator following the rules of [overload resolution](overload_resolution "cpp/language/overload resolution"). Note that, if a non-template assignment operator from some non-class type is available, it is preferred over the copy/move assignment in `E1 = {}` because `{}` to non-class is an [identity conversion](overload_resolution#Implicit_conversion_sequence_in_list-initialization "cpp/language/overload resolution"), which outranks the user-defined conversion from `{}` to a class type. | (since C++11) | | | | | --- | --- | | Using an lvalue of volatile-qualified non-class type as left operand of built-in direct assignment operator is deprecated, unless the assignment expression appears in an [unevaluated context](expressions#Unevaluated_expressions "cpp/language/expressions") or is a [discarded-value expression](expressions#Discarded-value_expressions "cpp/language/expressions"). | (since C++20) | In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for every type `T`, the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` T*& operator=(T*&, T*); ``` | | | | ``` T*volatile & operator=(T*volatile &, T*); ``` | | | For every enumeration or pointer to member type `T`, optionally volatile-qualified, the following function signature participates in overload resolution: | | | | | --- | --- | --- | | ``` T& operator=(T&, T); ``` | | | For every pair A1 and A2, where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution: | | | | | --- | --- | --- | | ``` A1& operator=(A1&, A2); ``` | | | ### Example ``` #include <iostream> int main() { int n = 0; // not an assignment n = 1; // direct assignment std::cout << n << ' '; n = {}; // zero-initialization, then assignment std::cout << n << ' '; n = 'a'; // integral promotion, then assignment std::cout << n << ' '; n = {'b'}; // explicit cast, then assignment std::cout << n << ' '; n = 1.0; // floating-point conversion, then assignment std::cout << n << ' '; // n = {1.0}; // compiler error (narrowing conversion) int& r = n; // not an assignment r = 2; // assignment through reference std::cout << n << '\n'; [[maybe_unused]] int* p; p = &n; // direct assignment p = nullptr; // null-pointer conversion, then assignment struct { int a; std::string s; } obj; obj = {1, "abc"}; // assignment from a braced-init-list std::cout << obj.a << ':' << obj.s << '\n'; } ``` Output: ``` 1 0 97 98 1 2 1:abc ``` #### Builtin compound assignment The compound assignment expressions have the form. | | | | | --- | --- | --- | | lhs op rhs | (1) | | | lhs op `{}` | (2) | (since C++11) | | lhs op `{` rhs `}` | (3) | (since C++11) | | | | | | --- | --- | --- | | op | - | one of `*=`, `/=` `%=`, `+=` `-=`, `<<=`, `>>=`, `&=`, `^=`, `|=` | | lhs | - | for the built-in operator, lhs may have any arithmetic type, except when op is `+=` or `-=`, which also accept pointer types with the same restrictions as + and - | | rhs | - | for the built-in operator, rhs must be implicitly convertible to lhs | The behavior of every builtin compound-assignment expression `E1 op= E2` (where E1 is a modifiable lvalue expression and E2 is an rvalue expression or a *braced-init-list* (since C++11)) is exactly the same as the behavior of the expression `E1 = E1 op E2`, except that the expression `E1` is evaluated only once and that it behaves as a single operation with respect to indeterminately-sequenced function calls (e.g. in `f(a += b, g())`, the += is either not started at all or is completed as seen from inside `g()`). | | | | --- | --- | | Using an lvalue of volatile-qualified non-class type as left operand of built-in compound assignment operator other than `|=`, `&=`, or `^=` is deprecated. | (since C++20) | In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for every pair A1 and A2, where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` A1& operator*=(A1&, A2); ``` | | | | ``` A1& operator/=(A1&, A2); ``` | | | | ``` A1& operator+=(A1&, A2); ``` | | | | ``` A1& operator-=(A1&, A2); ``` | | | For every pair I1 and I2, where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` I1& operator%=(I1&, I2); ``` | | | | ``` I1& operator<<=(I1&, I2); ``` | | | | ``` I1& operator>>=(I1&, I2); ``` | | | | ``` I1& operator&=(I1&, I2); ``` | | | | ``` I1& operator^=(I1&, I2); ``` | | | | ``` I1& operator|=(I1&, I2); ``` | | | For every optionally cv-qualified object type `T`, the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` T*& operator+=(T*&, std::ptrdiff_t); ``` | | | | ``` T*& operator-=(T*&, std::ptrdiff_t); ``` | | | | ``` T*volatile & operator+=(T*volatile &, std::ptrdiff_t); ``` | | | | ``` T*volatile & operator-=(T*volatile &, std::ptrdiff_t); ``` | | | ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1527](https://cplusplus.github.io/CWG/issues/1527.html) | C++11 | for assignments to class type objects, the right operandcould be an initializer list only when the assignmentis defined by a user-defined assignment operator | removed user-definedassignment constraint | | [CWG 1538](https://cplusplus.github.io/CWG/issues/1538.html) | C++11 | `E1 = {E2}` was equivalent to `E1 = T(E2)`(`T` is the type of `E1`), this introduced a C-style cast | it is equivalentto `E1 = T{E2}` | | [P2327R1](https://wg21.link/P2327R1) | C++20 | bitwise compound assignment operators for volatile typeswere deprecated while being useful for some platforms | they are not deprecated | ### See also [Operator precedence](operator_precedence "cpp/language/operator precedence"). [Operator overloading](operators "cpp/language/operators"). | Common operators | | --- | | **assignment** | [incrementdecrement](operator_incdec "cpp/language/operator incdec") | [arithmetic](operator_arithmetic "cpp/language/operator arithmetic") | [logical](operator_logical "cpp/language/operator logical") | [comparison](operator_comparison "cpp/language/operator comparison") | [memberaccess](operator_member_access "cpp/language/operator member access") | [other](operator_other "cpp/language/operator other") | | `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b a <=> b`. | `a[b] *a &a a->b a.b a->*b a.*b`. | `a(...) a, b a ? b : c`. | | Special operators | | [`static_cast`](static_cast "cpp/language/static cast") converts one type to another related type [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") converts within inheritance hierarchies [`const_cast`](const_cast "cpp/language/const cast") adds or removes [cv](cv "cpp/language/cv") qualifiers [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") converts type to unrelated type [C-style cast](explicit_cast "cpp/language/explicit cast") converts one type to another by a mix of `static_cast`, `const_cast`, and `reinterpret_cast` [`new`](new "cpp/language/new") creates objects with dynamic storage duration [`delete`](delete "cpp/language/delete") destructs objects previously created by the new expression and releases obtained memory area [`sizeof`](sizeof "cpp/language/sizeof") queries the size of a type [`sizeof...`](sizeof... "cpp/language/sizeof...") queries the size of a [parameter pack](parameter_pack "cpp/language/parameter pack") (since C++11) [`typeid`](typeid "cpp/language/typeid") queries the type information of a type [`noexcept`](noexcept "cpp/language/noexcept") checks if an expression can throw an exception (since C++11) [`alignof`](alignof "cpp/language/alignof") queries alignment requirements of a type (since C++11). | | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/operator_assignment "c/language/operator assignment") for Assignment operators | cpp The this pointer The `this` pointer ================== ### Syntax | | | | | --- | --- | --- | | `this` | | | The expression `this` is an [rvalue](value_category#rvalue "cpp/language/value category") (until C++11)a [prvalue](value_category#prvalue "cpp/language/value category") (since C++11) [expression](expressions "cpp/language/expressions") whose value is the address of the [implicit object parameter](overload_resolution#Implicit_object_parameter "cpp/language/overload resolution") (object on which the non-static member function is being called). It can appear in the following contexts: 1) Within the body of any non-static [member function](member_functions "cpp/language/member functions"), including [member initializer list](initializer_list "cpp/language/initializer list"), and [lambda-expression body](lambda#closure_type_fun_operator "cpp/language/lambda") (since C++11) 2) within the [declaration](function "cpp/language/function") of a non-static member function anywhere after the (optional) cv-qualifier sequence, including | | | | --- | --- | | * [dynamic exception specification](except_spec "cpp/language/except spec"), | (until C++17) | | | | | --- | --- | | * [noexcept specification](noexcept_spec "cpp/language/noexcept spec"), and * the trailing return type | (since C++11) | | | | | --- | --- | | 3) within [default member initializer](data_members#Member_initialization "cpp/language/data members") 4) within [lambda-expression capture](lambda#Lambda_capture "cpp/language/lambda") list | (since C++11) | ### Explanation `this` can only associate with the innermost enclosing class of its appearance, even if the appearance is invalid in the context: ``` class Outer { int a[sizeof(*this)]; // error: not inside a member function unsigned int sz = sizeof(*this); // OK: in default member initializer void f() { int b[sizeof(*this)]; // OK struct Inner { int c[sizeof(*this)]; // error: not inside a member function of Inner // 'this' is not associated with Outer // even if it is inside a member function of Outer }; } }; ``` The type of `this` in a member function of class `X` is `X*` (pointer to X). If the member function is [declared with a cv-qualifier sequence](member_functions#member_functions_with_cv-qualifiers "cpp/language/member functions") *cv*, the type of `this` is `*cv* X*` (pointer to identically cv-qualified X). Since constructors and destructors cannot be declared with cv-qualifiers, the type of `this` in them is always `X*`, even when constructing or destroying a const object. When a non-static class member is used in any of the contexts where the `this` keyword is allowed (non-static member function bodies, member initializer lists, default member initializers), the implicit `this->` is automatically added before the name, resulting in a member access expression (which, if the member is a virtual member function, results in a virtual function call). In class templates, `this` is a [dependent expression](dependent_name "cpp/language/dependent name"), and explicit `this->` may be used to force another expression to become dependent. ``` template<typename T> struct B { int var; }; template<typename T> struct D : B<T> { D() { // var = 1; // error: 'var' was not declared in this scope this->var = 1; // OK } }; ``` [During construction](constructor "cpp/language/constructor") of an object, if the value of the object or any of its subobjects is accessed through a glvalue that is not obtained, directly or indirectly, from the constructor's `this` pointer, the value of the object or subobject thus obtained is unspecified. In other words, the this pointer cannot be aliased in a constructor: ``` extern struct D d; struct D { D(int a) : a(a), b(d.a) {} // b(a) or b(this->a) would be correct int a, b; }; D d = D(1); // because b(d.a) did not obtain a through this, d.b is now unspecified ``` It is possible to execute `delete this;`, if the program can guarantee that the object was allocated by `new`, however, this renders every pointer to the deallocated object invalid, including the `this` pointer itself: after `delete this;` returns, such member function cannot refer to a member of a class (since this involves an implicit dereference of `this`) and no other member function may be called. | | | | --- | --- | | This is used, for example, in the member function of the control block of `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` responsible for decrementing the reference count, when the last reference to the managed object goes out of scope. | (since C++11) | ``` class ref { // ... void incRef() { ++mnRef; } void decRef() { if (--mnRef == 0) delete this; } }; ``` ### Keywords [`this`](../keyword/this "cpp/keyword/this"). ### Example ``` class T { int x; void foo() { x = 6; // same as this->x = 6; this->x = 5; // explicit use of this-> } void foo() const { // x = 7; // Error: *this is constant } void foo(int x) // parameter x shadows the member with the same name { this->x = x; // unqualified x refers to the parameter // 'this->' required for disambiguation } int y; T(int x) : x(x), // uses parameter x to initialize member x y(this->x) // uses member x to initialize member y {} T& operator=(const T& b) { x = b.x; return *this; // many overloaded operators return *this } }; ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 760](https://cplusplus.github.io/CWG/issues/760.html) | C++98 | when `this` is used in a nested class, it wasunspecified whether it is associated withthe nested class or the enclosing class | `this` always associates withthe innermost nested class,regardless of whether it is ina non-static member function | | [CWG 2271](https://cplusplus.github.io/CWG/issues/2271.html) | C++98 | `this` could be aliased when constructing a non-const object | alias is alsoprohibited in this case |
programming_docs
cpp typedef specifier typedef specifier ================= * `typedef` - creates an alias that can be used anywhere in place of a (possibly complex) type name. ### Explanation The `typedef` specifier, when used in a [declaration](declarations "cpp/language/declarations"), specifies that the declaration is a *typedef declaration* rather than a variable or function declaration. Typically, the `typedef` specifier appears at the start of the declaration, though it is permitted to appear after the type specifiers, or between two type specifiers. A typedef declaration may declare one or many identifiers on the same line (e.g. int and a pointer to int), it may declare array and function types, pointers and references, class types, etc. Every identifier introduced in this declaration becomes a typedef-name, which is a synonym for the type of the object or function that it would become if the keyword `typedef` were removed. The `typedef` specifier cannot be combined with any other specifier except for [*type-specifier*s](declarations#Specifiers "cpp/language/declarations"). The typedef-names are aliases for existing types, and are not declarations of new types. Typedef cannot be used to change the meaning of an existing type name (including a typedef-name). Once declared, a typedef-name may only be redeclared to refer to the same type again. Typedef names are only in effect in the scope where they are visible: different functions or class declarations may define identically-named types with different meaning. The `typedef` specifier may not appear in the declaration of a function parameter nor in the decl-specifier-seq of a [function definition](function#Function_definition "cpp/language/function"): ``` void f1(typedef int param); // ill-formed typedef int f2() {} // ill-formed ``` The `typedef` specifier may not appear in a declaration that does not contain a declarator: ``` typedef struct X {}; // ill-formed ``` ### typedef-name for linkage purposes Formally, if the typedef declaration defines an unnamed [class](classes "cpp/language/classes") or [enum](enum "cpp/language/enum"), the first typedef-name declared by the declaration to be that class type or enum type is used to denote the class type or enum type for linkage purposes only. For example, in `typedef struct { /* ... */ } S;`, `S` is a typedef-name for linkage purposes. The class or enum type defined in this way has [external linkage](storage_duration#Linkage "cpp/language/storage duration") (unless it's in an unnamed namespace). | | | | --- | --- | | An unnamed class defined in this way should only contain C-compatible constructs. In particular, it must not.* declare any members other than non-static data members, member enumerations, or member classes, * have any [base classes](derived_class "cpp/language/derived class") or [default member initializers](data_members#Member_initialization "cpp/language/data members"), or * contain a [lambda-expression](lambda "cpp/language/lambda"), and all member classes must also satisfy these requirements (recursively). | (since C++20) | ### Keywords [`typedef`](../keyword/typedef "cpp/keyword/typedef"). ### Notes [type aliases](type_alias "cpp/language/type alias") provide the same functionality as typedefs using a different syntax, and are also applicable to template names. ### Example ``` // simple typedef typedef unsigned long ulong; // the following two objects have the same type unsigned long l1; ulong l2; // more complicated typedef typedef int int_t, *intp_t, (&fp)(int, ulong), arr_t[10]; // the following two objects have the same type int a1[10]; arr_t a2; // beware: the following two objects do not have the same type const intp_t p1 = 0; // int *const p1 = 0 const int *p2; // common C idiom to avoid having to write "struct S" typedef struct {int a; int b;} S, *pS; // the following two objects have the same type pS ps1; S* ps2; // error: storage-class-specifier cannot appear in a typedef declaration // typedef static unsigned int uint; // typedef can be used anywhere in the decl-specifier-seq long unsigned typedef int long ullong; // more conventionally spelled "typedef unsigned long long int ullong;" // std::add_const, like many other metafunctions, use member typedefs template<class T> struct add_const { typedef const T type; }; typedef struct Node { struct listNode* next; // declares a new (incomplete) struct type named listNode } listNode; // error: conflicts with the previously declared struct name // C++20 error: "struct with typedef name for linkage" has member functions typedef struct { void f() {} } C_Incompatible; ``` ### Defect Reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 576](https://cplusplus.github.io/CWG/issues/576.html) | C++98 | `typedef` was not allowed in the entire function definition | allowed in function body | | [CWG 2071](https://cplusplus.github.io/CWG/issues/2071.html) | C++98 | `typedef` could appear in a declaration that does not contain a declarator | now allowed | ### See also * [Type alias](type_alias "cpp/language/type alias") * [Alias template](type_alias "cpp/language/type alias") | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/typedef "c/language/typedef") for `Typedef declaration` | cpp Name lookup Name lookup =========== Name lookup is the procedure by which a [name](name "cpp/language/name"), when encountered in a program, is associated with the [declaration](declarations "cpp/language/declarations") that introduced it. For example, to compile `[std::cout](http://en.cppreference.com/w/cpp/io/cout) << [std::endl](http://en.cppreference.com/w/cpp/io/manip/endl);`, the compiler performs: * unqualified name lookup for the name `std`, which finds the declaration of namespace std in the header [`<iostream>`](../header/iostream "cpp/header/iostream") * qualified name lookup for the name `cout`, which finds a variable declaration in the namespace `std` * qualified name lookup for the name `endl`, which finds a function template declaration in the namespace `std` * both [argument-dependent lookup](adl "cpp/language/adl") for the name `operator<<` which finds multiple function template declarations in the namespace std and qualified name lookup for the name `std::ostream::operator<<` which finds multiple member function declarations in class `[std::ostream](../io/basic_ostream "cpp/io/basic ostream")`. For function and function template names, name lookup can associate multiple declarations with the same name, and may obtain additional declarations from [argument-dependent lookup](adl "cpp/language/adl"). [Template argument deduction](function_template "cpp/language/function template") may also apply, and the set of declarations is passed to [overload resolution](overload_resolution "cpp/language/overload resolution"), which selects the declaration that will be used. [Member access](access "cpp/language/access") rules, if applicable, are considered only after name lookup and overload resolution. For all other names (variables, namespaces, classes, etc), name lookup can associate multiple declarations only if they declare the same [entity](basic_concepts "cpp/language/basic concepts"), otherwise it must produce a single declaration in order for the program to compile. Lookup for a name in a scope finds all declarations of that name, with one exception, known as the "struct hack" or "type/non-type hiding": Within the same scope, some occurrences of a name may refer to a declaration of a class/struct/union/enum that is not a `typedef`, while all other occurrences of the same name either all refer to the same variable, non-static data member, or enumerator, or they all refer to possibly overloaded function or function template names. In this case, there is no error, but the type name is hidden from lookup (the code must use [elaborated type specifier](elaborated_type_specifier "cpp/language/elaborated type specifier") to access it). ### Types of lookup If the name appears immediately to the right of the scope resolution operator `::` or possibly after `::` followed by the disambiguating keyword `template`, see. * [Qualified name lookup](qualified_lookup "cpp/language/qualified lookup") Otherwise, see. * [Unqualified name lookup](unqualified_lookup "cpp/language/unqualified lookup") + (which, for function names, includes [Argument-dependent lookup](adl "cpp/language/adl")) ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 2063](https://cplusplus.github.io/CWG/issues/2063.html) | C++98 | "struct hack" did not apply in class scope (breaks C compatibility) | applied | | [CWG 2218](https://cplusplus.github.io/CWG/issues/2218.html) | C++98 | lookup for non-function (template) names could not associatemultiple declarations, even if they declare the same entity | allowed | ### See also * [Scope](scope "cpp/language/scope") * [Argument-dependent lookup](adl "cpp/language/adl") * [Template argument deduction](function_template#Template_argument_deduction "cpp/language/function template") * [Overload resolution](overload_resolution "cpp/language/overload resolution") | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/name_space "c/language/name space") for Lookup and name spaces | cpp String literal String literal ============== ### Syntax | | | | | --- | --- | --- | | `"`s-char-sequence(optional)`"` | (1) | | | `L"`s-char-sequence(optional)`"` | (2) | | | `u8"`s-char-sequence(optional)`"` | (3) | (since C++11) | | `u"`s-char-sequence(optional)`"` | (4) | (since C++11) | | `U"`s-char-sequence(optional)`"` | (5) | (since C++11) | | prefix(optional) `R"`d-char-sequence(optional)`(`r-char-sequence(optional)`)`d-char-sequence(optional)`"` | (6) | (since C++11) | ### Explanation | | | | | --- | --- | --- | | s-char-sequence | - | A sequence of one or more s-chars | | s-char | - | One of * a basic-s-char * an escape sequence, as defined in [escape sequences](escape "cpp/language/escape") * a universal character name, as defined in [escape sequences](escape "cpp/language/escape") | | basic-s-char | - | A character from the [source character set](translation_phases#Phase_5 "cpp/language/translation phases") (until C++23)[translation character set](charset#Translation_character_set "cpp/language/charset") (since C++23), except the double-quote `"`, backslash `\`, or new-line character | | prefix | - | One of `L`, `u8`, `u`, `U` | | d-char-sequence | - | A sequence of one or more d-chars, at most 16 characters long | | d-char | - | A character from the [basic source character set](charset#Basic_source_character_set "cpp/language/charset") (until C++23)[basic character set](charset#Basic_character_set "cpp/language/charset") (since C++23), except parentheses, backslash and [spaces](../string/byte/isspace "cpp/string/byte/isspace") | | r-char-sequence | - | A sequence of one or more r-chars, except that it must not contain the closing sequence`)`d-char-sequence`"` | | r-char | - | A character from the [source character set](translation_phases#Phase_5 "cpp/language/translation phases") (until C++23)[translation character set](charset#Translation_character_set "cpp/language/charset") (since C++23) | 1) Ordinary string literal. The type of an unprefixed string literal is `const char[N]`, where `N` is the size of the string in code units of the execution narrow encoding (until C++23)[ordinary literal encoding](charset#Code_unit_and_literal_encoding "cpp/language/charset") (since C++23), including the null terminator. 2) Wide string literal. The type of a `L"..."` string literal is `const wchar_t[N]`, where `N` is the size of the string in code units of the execution wide encoding (until C++23)wide literal encoding (since C++23), including the null terminator. 3) UTF-8 string literal. The type of a `u8"..."` string literal is `const char[N]` (until C++20)`const char8_t[N]` (since C++20), where `N` is the size of the string in UTF-8 code units including the null terminator. 4) UTF-16 string literal. The type of a `u"..."` string literal is `const char16_t[N]`, where `N` is the size of the string in UTF-16 code units including the null terminator. 5) UTF-32 string literal. The type of a `U"..."` string literal is `const char32_t[N]`, where `N` is the size of the string in UTF-32 code units including the null terminator. 6) Raw string literal. Used to avoid escaping of any character. Anything between the delimiters becomes part of the string. prefix, if present, has the same meaning as described above. The terminating d-char-sequence is the same sequence of characters as the initial d-char-sequence. Each s-char (originally from non-raw string literals) or r-char (originally from raw string literals) (since C++11) initializes the corresponding element(s) in the string literal object. An s-char or r-char (since C++11) corresponds to more than one element if and only if it is represented by a sequence of more than one code units in the string literal's associated character encoding. | | | | --- | --- | | If a character lacks representation in the associated character encoding,* if the string literal is an ordinary string literal or wide string literal, it is conditionally-supported and an implementation-defined code unit sequence is encoded; * otherwise (the string literal is UTF-encoded), the string literal is ill-formed. | (since C++23) | Each numeric escape sequence corresponds to a single element. If the value specified by the escape sequence fits within the unsigned version of the element type, the element has the specified value (possibly after conversion to the element type); otherwise (the specified value is out of range), the string literal is ill-formed. (since C++23). #### Concatenation String literals placed side-by-side are concatenated at [translation phase 6](translation_phases#Phase_6 "cpp/language/translation phases") (after the preprocessor). That is, `"Hello," " world!"` yields the (single) string `"Hello, world!"`. If the two strings have the same encoding prefix (or neither has one), the resulting string will have the same encoding prefix (or no prefix). | | | | --- | --- | | If one of the strings has an encoding prefix and the other doesn't, the one that doesn't will be considered to have the same encoding prefix as the other. ``` L"Δx = %" PRId16 // at phase 4, PRId16 expands to "d" // at phase 6, L"Δx = %" and "d" form L"Δx = %d" ``` If a UTF-8 string literal and a wide string literal are side by side, the program is ill-formed. | (since C++11) | | | | | --- | --- | | Any other combination of encoding prefixes may or may not be supported by the implementation. The result of such a concatenation is implementation-defined. | (since C++11)(until C++23) | | Any other combination of encoding prefixes is ill-formed. | (since C++23) | ### Notes The null character (`'\0'`, `L'\0'`, `char16_t()`, etc) is always appended to the string literal: thus, a string literal `"Hello"` is a `const char[6]` holding the characters `'H'`, `'e'`, `'l'`, `'l'`, `'o'`, and `'\0'`. The encoding of ordinary string literals (1) and wide string literals (2) is implementation-defined. For example, gcc selects them with the [command line options](https://gcc.gnu.org/onlinedocs/cpp/Invocation.html) `-fexec-charset` and `-fwide-exec-charset`. String literals have [static storage duration](storage_duration "cpp/language/storage duration"), and thus exist in memory for the life of the program. String literals can be used to [initialize character arrays](aggregate_initialization "cpp/language/aggregate initialization"). If an array is initialized like `char str[] = "foo";`, `str` will contain a copy of the string `"foo"`. Whether string literals can overlap and whether successive evaluations of a string-literal yield the same object is unspecified. That means that identical string literals may or may not compare equal when compared by pointer. ``` bool b = "bar" == 3+"foobar"; // could be true or false, implementation-defined ``` Attempting to modify a string literal results in *undefined behavior*: they may be stored in read-only storage (such as `.rodata`) or combined with other string literals: ``` const char* pc = "Hello"; char* p = const_cast<char*>(pc); p[0] = 'M'; // undefined behavior ``` | | | | --- | --- | | String literals are convertible and assignable to non-const `char*` or `wchar_t*` in order to be compatible with C, where string literals are of types `char[N]` and `wchar_t[N]`. Such implicit conversion is deprecated. | (until C++11) | | String literals are not convertible or assignable to non-const `CharT*`. An explicit cast (e.g. [`const_cast`](const_cast "cpp/language/const cast")) must be used if such conversion is wanted. | (since C++11) | A string literal is not necessarily a null-terminated character sequence: if a string literal has embedded null characters, it represents an array which contains more than one string. ``` const char* p = "abc\0def"; // std::strlen(p) == 3, but the array has size 8 ``` If a valid hex digit follows a hex escape in a string literal, it would fail to compile as an invalid escape sequence. String concatenation can be used as a workaround: ``` //const char* p = "\xfff"; // error: hex escape sequence out of range const char* p = "\xff""f"; // OK: the literal is const char[3] holding {'\xff','f','\0'} ``` Although mixed wide string literal concatenation is allowed in C++11, all known C++ compilers reject such concatenation, and its usage experience is unknown. As a result, allowance of mixed wide string literal concatenation is removed in C++23. ### Example ``` #include <iostream> char array1[] = "Foo" "bar"; // same as char array2[] = { 'F', 'o', 'o', 'b', 'a', 'r', '\0' }; const char* s1 = R"foo( Hello World )foo"; // same as const char* s2 = "\nHello\n World\n"; // same as const char* s3 = "\n" "Hello\n" " World\n"; const wchar_t* s4 = L"ABC" L"DEF"; // ok, same as const wchar_t* s5 = L"ABCDEF"; const char32_t* s6 = U"GHI" "JKL"; // ok, same as const char32_t* s7 = U"GHIJKL"; const char16_t* s9 = "MN" u"OP" "QR"; // ok, same as const char16_t* sA = u"MNOPQR"; // const auto* sB = u"Mixed" U"Types"; // before C++23 may or may not be supported by // the implementation; ill-formed since C++23 const wchar_t* sC = LR"--(STUV)--"; // ok, raw string literal int main() { std::cout << array1 << ' ' << array2 << '\n' << s1 << s2 << s3 << std::endl; std::wcout << s4 << ' ' << s5 << ' ' << sC << std::endl; } ``` Output: ``` Foobar Foobar Hello World Hello World Hello World ABCDEF ABCDEF STUV ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1759](https://cplusplus.github.io/CWG/issues/1759.html) | C++11 | A UTF-8 string literal might have codeunits that are not representable in `char` | `char` can represent all UTF-8 code units | | [CWG 1823](https://cplusplus.github.io/CWG/issues/1823.html) | C++98 | whether string literals are distinctwas implementation-defined | distinctness is unspecified, and samestring literal can yield different object | ### See also | | | | --- | --- | | [user-defined literals](user_literal "cpp/language/user literal")(C++11) | literals with user-defined suffix | | [C documentation](https://en.cppreference.com/w/c/language/string_literal "c/language/string literal") for String literals |
programming_docs
cpp Basic concepts Basic concepts ============== This section provides definitions for the specific terminology and the concepts used when describing the C++ programming language. A C++ program is a sequence of text files (typically header and source files) that contain [declarations](declarations "cpp/language/declarations"). They undergo [translation](translation_phases "cpp/language/translation phases") to become an executable program, which is executed when the C++ implementation calls its [main function](main_function "cpp/language/main function"). Certain words in a C++ program have special meaning, and these are known as [keywords](../keyword "cpp/keyword"). Others can be used as [identifiers](identifiers "cpp/language/identifiers"). [Comments](../comment "cpp/comment") are ignored during translation. C++ programs also contain [literals](expressions#Literals "cpp/language/expressions"), the values of characters inside them are determined by [character sets and encodings](charset "cpp/language/charset"). Certain characters in the program have to be represented with [escape sequences](escape "cpp/language/escape"). The *entities* of a C++ program are values, [objects](objects "cpp/language/objects"), [references](reference "cpp/language/reference"), [structured bindings](structured_binding "cpp/language/structured binding") (since C++17), [functions](functions "cpp/language/functions"), [enumerators](enum "cpp/language/enum"), [types](type "cpp/language/type"), class members, [templates](templates "cpp/language/templates"), [template specializations](template_specialization "cpp/language/template specialization"), [namespaces](namespace "cpp/language/namespace"), and [parameter packs](parameter_pack "cpp/language/parameter pack"). Preprocessor [macros](../preprocessor/replace "cpp/preprocessor/replace") are not C++ entities. *[Declarations](declarations "cpp/language/declarations")* may introduce entities, associate them with [names](name "cpp/language/name") and define their properties. The declarations that define all properties required to use an entity are [definitions](definition "cpp/language/definition"). A program must contain only one definition of any non-inline function or variable that is [odr-used](definition#ODR-use "cpp/language/definition"). Definitions of functions usually include sequences of [statements](statements "cpp/language/statements"), some of which include [expressions](expressions "cpp/language/expressions"), which specify the computations to be performed by the program. Names encountered in a program are associated with the declarations that introduced them using [name lookup](lookup "cpp/language/lookup"). Each name is only valid within a part of the program called its [scope](scope "cpp/language/scope"). Some names have [linkage](storage_duration "cpp/language/storage duration") which makes them refer to the same entities when they appear in different scopes or translation units. Each object, reference, function, expression in C++ is associated with a [type](type "cpp/language/type"), which may be [fundamental](types "cpp/language/types"), compound, or [user-defined](classes "cpp/language/classes"), complete or [incomplete](incomplete_type "cpp/language/incomplete type"), etc. Declared objects and declared references that are not [non-static data members](data_members "cpp/language/data members") are *variables*. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/basic_concepts "c/language/basic concepts") for Basic concepts | cpp Storage class specifiers Storage class specifiers ======================== The storage class specifiers are a part of the decl-specifier-seq of a name's [declaration syntax](declarations "cpp/language/declarations"). Together with the [scope](scope "cpp/language/scope") of the name, they control two independent properties of the name: its *storage duration* and its *linkage*. * `auto` or (until C++11)no specifier - *automatic* storage duration. | * `register` - *automatic* storage duration. Also hints to the compiler to place the object in the processor's register. (deprecated) | (until C++17) | * `static` - *static* or *thread* storage duration and *internal* linkage (or *external* linkage for static class members not in an anonymous namespace). * `extern` - *static* or *thread* storage duration and *external* linkage. | | | | --- | --- | | * `thread_local` - *thread* storage duration. | (since C++11) | * `mutable` - does not affect storage duration or linkage. See [const/volatile](cv "cpp/language/cv") for the explanation. Only one storage class specifier may appear in a declaration except that `thread_local` may be combined with `static` or with `extern` (since C++11). ### Explanation | | | | --- | --- | | 1) The `auto` specifier was only allowed for objects declared at block scope or in function parameter lists. It indicated automatic storage duration, which is the default for these kinds of declarations. The meaning of this keyword was changed in C++11. | (until C++11) | | 2) The `register` specifier is only allowed for objects declared at block scope and in function parameter lists. It indicates automatic storage duration, which is the default for these kinds of declarations. Additionally, the presence of this keyword may be used as a hint for the optimizer to store the value of this variable in a CPU register. This keyword is deprecated. | (until C++17) | 3) The `static` specifier is only allowed in the declarations of objects (except in function parameter lists), declarations of functions (except at block scope), and declarations of anonymous unions. When used in a declaration of a class member, it declares a [static member](static "cpp/language/static"). When used in a declaration of an object, it specifies static storage duration (except if accompanied by `thread_local`). When used in a declaration at namespace scope, it specifies internal linkage. 4) The `extern` specifier is only allowed in the declarations of variables and functions (except class members or function parameters). It specifies external linkage, and does not technically affect storage duration, but it cannot be used in a definition of an automatic storage duration object, so all `extern` objects have static or thread durations. In addition, a variable declaration that uses `extern` and has no initializer is not a [definition](definition "cpp/language/definition"). | | | | --- | --- | | 5) The `thread_local` keyword is only allowed for objects declared at namespace scope, objects declared at block scope, and static data members. It indicates that the object has thread storage duration. If `thread_local` is the only storage class specifier applied to a block scope variable, `static` is also implied. It can be combined with `static` or `extern` to specify internal or external linkage (except for static data members which always have external linkage) respectively. | (since C++11) | #### Storage duration All [objects](object "cpp/language/object") in a program have one of the following storage durations: * ***automatic*** storage duration. The storage for the object is allocated at the beginning of the enclosing code block and deallocated at the end. All local objects have this storage duration, except those declared `static`, `extern` or `thread_local`. + ***static*** storage duration. The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration, plus those declared with `static` or `extern`. See [Non-local variables](initialization#Non-local_variables "cpp/language/initialization") and [Static local variables](#Static_local_variables) for details on initialization of objects with this storage duration. | | | | --- | --- | | * ***thread*** storage duration. The storage for the object is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the object. Only objects declared `thread_local` have this storage duration. `thread_local` can appear together with `static` or `extern` to adjust linkage. See [Non-local variables](initialization#Non-local_variables "cpp/language/initialization") and [Static local variables](#Static_local_variables) for details on initialization of objects with this storage duration. | (since C++11) | * ***dynamic*** storage duration. The storage for the object is allocated and deallocated upon request by using [dynamic memory allocation](../memory "cpp/memory") functions. See [new-expression](new "cpp/language/new") for details on initialization of objects with this storage duration. The storage duration of [subobjects](object#Subobjects "cpp/language/object") and reference members is that of their complete object. #### Linkage A name that denotes object, reference, function, type, template, namespace, or value, may have *linkage*. If a name has linkage, it refers to the same entity as the same name introduced by a declaration in another scope. If a variable, function, or another entity with the same name is declared in several scopes, but does not have sufficient linkage, then several instances of the entity are generated. The following linkages are recognized: ##### no linkage The name can be referred to only from the scope it is in. Any of the following names declared at block scope have no linkage: * variables that aren't explicitly declared `extern` (regardless of the `static` modifier); * [local classes](class#Local_classes "cpp/language/class") and their member functions; * other names declared at block scope such as typedefs, enumerations, and enumerators. Names not specified with external, module, (since C++20) or internal linkage also have no linkage, regardless of which scope they are declared in. ##### internal linkage The name can be referred to from all scopes in the current translation unit. Any of the following names declared at namespace scope have internal linkage: * variables, variable templates (since C++14), functions, or function templates declared `static`; * non-volatile non-template (since C++14) non-inline (since C++17) non-[exported](modules "cpp/language/modules") (since C++20) [const-qualified](cv "cpp/language/cv") variables (including [constexpr](constexpr "cpp/language/constexpr")) (since C++11) that aren't declared `extern` and aren't previously declared to have external linkage; * data members of [anonymous unions](union "cpp/language/union"). | | | | --- | --- | | In addition, all names declared in [unnamed namespace](namespace "cpp/language/namespace") or a namespace within an unnamed namespace, even ones explicitly declared `extern`, have internal linkage. | (since C++11) | ##### external linkage The name can be referred to from the scopes in the other translation units. Variables and functions with external linkage also have [language linkage](language_linkage "cpp/language/language linkage"), which makes it possible to link translation units written in different programming languages. Any of the following names declared at namespace scope have external linkage, unless they are declared in an unnamed namespace or their declarations are attached to a named module and are not exported (since C++20): * variables and functions not listed above (that is, functions not declared `static`, non-const variables not declared `static`, and any variables declared `extern`); * enumerations; * names of classes, their member functions, static data members (const or not), nested classes and enumerations, and functions first introduced with [friend](friend "cpp/language/friend") declarations inside class bodies; * names of all templates not listed above (that is, not function templates declared `static`). Any of the following names first declared at block scope have external linkage: * names of variables declared `extern`; * names of functions. | | | | --- | --- | | module linkage The name can be referred to only from the scopes in the same module unit or in the other translation units of the same named module. Names declared at namespace scope have module linkage if their declarations are attached to a named module and are not exported, and don't have internal linkage. | (since C++20) | ### Static local variables Variables declared at block scope with the specifier `static` or `thread_local` (since C++11) have static or thread (since C++11) storage duration but are initialized the first time control passes through their declaration (unless their initialization is [zero-](zero_initialization "cpp/language/zero initialization") or [constant-initialization](constant_initialization "cpp/language/constant initialization"), which can be performed before the block is first entered). On all further calls, the declaration is skipped. If the initialization [throws an exception](throw "cpp/language/throw"), the variable is not considered to be initialized, and initialization will be attempted again the next time control passes through the declaration. If the initialization recursively enters the block in which the variable is being initialized, the behavior is undefined. | | | | --- | --- | | If multiple threads attempt to initialize the same static local variable concurrently, the initialization occurs exactly once (similar behavior can be obtained for arbitrary functions with `[std::call\_once](../thread/call_once "cpp/thread/call once")`). Note: usual implementations of this feature use variants of the double-checked locking pattern, which reduces runtime overhead for already-initialized local statics to a single non-atomic boolean comparison. | (since C++11) | The destructor for a block-scope static variable [is called at program exit](../utility/program/exit "cpp/utility/program/exit"), but only if the initialization took place successfully. Function-local static objects in all definitions of the same [inline function](inline "cpp/language/inline") (which may be implicitly inline) all refer to the same object defined in one translation unit, as long as the function has external linkage. ### Translation-unit-local entities The concept of translation-unit-local entities is standardized in C++20, see [this page](tu_local "cpp/language/tu local") for more details. An entity is *translation-unit-local* (or *TU-local* for short) if. * it has a name with internal linkage, or * it does not have a name with linkage and is introduced within the definition of a TU-local entity, or * it is a template or template specialization whose template argument or template declaration uses a TU-local entity. Bad things (usually violation of [ODR](definition "cpp/language/definition")) can happen if the type of a non-TU-local entity depends on a TU-local entity, or if a declaration of, or a [deduction guide](ctad "cpp/language/ctad") for, (since C++17) a non-TU-local entity names a TU-local entity outside its. * function-body for a non-inline function or function template * initializer for a variable or variable template * friend declarations in a class definition * use of value of a variable, if the variable is [usable in constant expressions](constant_expression#Usable_in_constant_expressions "cpp/language/constant expression") | | | | --- | --- | | Such uses are disallowed in a [module interface unit](modules "cpp/language/modules") (outside its private-module-fragment, if any) or a module partition, and are deprecated in any other context. A declaration that appears in one translation unit cannot name a TU-local entity declared in another translation unit that is not a header unit. A declaration instantiated for a [template](templates "cpp/language/templates") appears at the point of instantiation of the specialization. | (since C++20) | ### Notes Names at the top-level namespace scope (file scope in C) that are `const` and not `extern` have external linkage in C, but internal linkage in C++. Since C++11, `auto` is no longer a storage class specifier; it is used to indicate type deduction. | | | | --- | --- | | In C, the address of a `register` variable cannot be taken, but in C++, a variable declared `register` is semantically indistinguishable from a variable declared without any storage class specifiers. | (until C++17) | | In C++, unlike C, variables cannot be declared `register`. | (since C++17) | Names of `thread_local` variables with internal or external linkage referred from different scopes may refer to the same or to different instances depending on whether the code is executing in the same or in different threads. The `extern` keyword can also be used to specify [language linkage](language_linkage "cpp/language/language linkage") and [explicit template instantiation declarations](class_template "cpp/language/class template"), but it's not a storage class specifier in those cases (except when a declaration is directly contained in a language linkage specification, in which case the declaration is treated as if it contains the `extern` specifier). [The keyword `mutable`](cv "cpp/language/cv") is a storage class specifier in the C++ language grammar, although it doesn't affect storage duration or linkage. Storage class specifiers, except for `thread_local`, are not allowed on [explicit specializations](template_specialization "cpp/language/template specialization") and [explicit instantiations](class_template#Explicit_instantiation "cpp/language/class template"): ``` template<class T> struct S { thread_local static int tlm; }; template<> thread_local int S<float>::tlm = 0; // "static" does not appear here ``` ### Keywords [`auto`](../keyword/auto "cpp/keyword/auto"), [`register`](../keyword/register "cpp/keyword/register"), [`static`](../keyword/static "cpp/keyword/static"), [`extern`](../keyword/extern "cpp/keyword/extern"), [`thread_local`](../keyword/thread_local "cpp/keyword/thread local"), [`mutable`](../keyword/mutable "cpp/keyword/mutable"). ### Example ``` #include <iostream> #include <string> #include <thread> #include <mutex> thread_local unsigned int rage = 1; std::mutex cout_mutex; void increase_rage(const std::string& thread_name) { ++rage; // modifying outside a lock is okay; this is a thread-local variable std::lock_guard<std::mutex> lock(cout_mutex); std::cout << "Rage counter for " << thread_name << ": " << rage << '\n'; } int main() { std::thread a(increase_rage, "a"), b(increase_rage, "b"); { std::lock_guard<std::mutex> lock(cout_mutex); std::cout << "Rage counter for main: " << rage << '\n'; } a.join(); b.join(); } ``` Possible output: ``` Rage counter for a: 2 Rage counter for main: 1 Rage counter for b: 2 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 216](https://cplusplus.github.io/CWG/issues/216.html) | C++98 | unnamed class and enumeration in class scope havedifferent linkage from those in namespace scope | they all have externallinkage in these scopes | | [CWG 389](https://cplusplus.github.io/CWG/issues/389.html) | C++98 | a name with no linkage should not beused to declare an entity with linkage | a type without linkage shall not be usedas the type of a variable or functionwith linkage, unless the variableor function has C language linkage | | [CWG 426](https://cplusplus.github.io/CWG/issues/426.html) | C++98 | an entity could be declared with both internaland external linkage in the same translation unit | the program is ill-formed in this case | | [CWG 527](https://cplusplus.github.io/CWG/issues/527.html) | C++98 | the type restriction introduced by the resolution of CWG389 was also applied to variables and functions thatcannot be named outside their own translation units | the restriction is lifted for thesevariables and functions (i.e. with nolinkage or internal linkage, or declaredwithin unnamed namesapces) | | [CWG 809](https://cplusplus.github.io/CWG/issues/809.html) | C++98 | `register` served very little function | deprecated | | [CWG 1648](https://cplusplus.github.io/CWG/issues/1648.html) | C++11 | `static` was implied even if`thread_local` is combined with `extern` | implied only if no other storageclass specifier is present | | [CWG 1686](https://cplusplus.github.io/CWG/issues/1686.html) | C++98C++11 | the name of a non-static variable declared in namespacescope had internal linkage only if it is explicitlydeclared `const` (C++98) or `constexpr` (C++11) | only required the typeto be const-qualified | | [CWG 2019](https://cplusplus.github.io/CWG/issues/2019.html) | C++98 | the storage duration of reference members were unspecified | same as their complete object | | [CWG 2387](https://cplusplus.github.io/CWG/issues/2387.html) | C++14 | unclear whether const-qualified variabletemplate have internal linkage by default | const qualifier does not affectthe linkage of variabletemplates or their instances | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/storage_duration "c/language/storage duration") for storage duration |
programming_docs
cpp The rule of three/five/zero The rule of three/five/zero =========================== ### Rule of three If a class requires a user-defined [destructor](destructor "cpp/language/destructor"), a user-defined [copy constructor](copy_constructor "cpp/language/copy constructor"), or a user-defined [copy assignment operator](as_operator "cpp/language/as operator"), it almost certainly requires all three. Because C++ copies and copy-assigns objects of user-defined types in various situations (passing/returning by value, manipulating a container, etc), these special member functions will be called, if accessible, and if they are not user-defined, they are implicitly-defined by the compiler. The implicitly-defined special member functions are typically incorrect if the class manages a resource whose handle is an object of non-class type (raw pointer, POSIX file descriptor, etc), whose destructor does nothing and copy constructor/assignment operator performs a "shallow copy" (copy the value of the handle, without duplicating the underlying resource). ``` #include <iostream> #include <cstddef> #include <cstring> class rule_of_three { char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block rule_of_three(const char* s, std::size_t n) // to avoid counting twice : cstring(new char[n]) // allocate { std::memcpy(cstring, s, n); // populate } public: rule_of_three(const char* s = "") : rule_of_three(s, std::strlen(s) + 1) {} ~rule_of_three() // I. destructor { delete[] cstring; // deallocate } rule_of_three(const rule_of_three& other) // II. copy constructor : rule_of_three(other.cstring) {} rule_of_three& operator=(const rule_of_three& other) // III. copy assignment { if (this == &other) return *this; std::size_t n{std::strlen(other.cstring) + 1}; char* new_cstring = new char[n]; // allocate std::memcpy(new_cstring, other.cstring, n); // populate delete[] cstring; // deallocate cstring = new_cstring; return *this; } operator const char *() const // accessor { return cstring; } }; int main() { rule_of_three o1{"abc"}; std::cout << o1 << ' '; auto o2{ o1 }; // I. uses copy constructor std::cout << o2 << ' '; rule_of_three o3("def"); std::cout << o3 << ' '; o3 = o2; // III. uses copy assignment std::cout << o3 << ' '; } // <- II. all destructors are called 'here' ``` Classes that manage non-copyable resources through copyable handles may have to declare copy assignment and copy constructor private and not provide their definitions or define them as deleted. This is another application of the rule of three: deleting one and leaving the other to be implicitly-defined will most likely result in errors. ### Rule of five Because the presence of a user-defined (or `= default` or `= delete` declared) destructor, copy-constructor, or copy-assignment operator prevents implicit definition of the [move constructor](move_constructor "cpp/language/move constructor") and the [move assignment operator](move_operator "cpp/language/move operator"), any class for which move semantics are desirable, has to declare all five special member functions: ``` class rule_of_five { char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block public: rule_of_five(const char* s = "") : cstring(nullptr) { if (s) { std::size_t n = std::strlen(s) + 1; cstring = new char[n]; // allocate std::memcpy(cstring, s, n); // populate } } ~rule_of_five() { delete[] cstring; // deallocate } rule_of_five(const rule_of_five& other) // copy constructor : rule_of_five(other.cstring) {} rule_of_five(rule_of_five&& other) noexcept // move constructor : cstring(std::exchange(other.cstring, nullptr)) {} rule_of_five& operator=(const rule_of_five& other) // copy assignment { return *this = rule_of_five(other); } rule_of_five& operator=(rule_of_five&& other) noexcept // move assignment { std::swap(cstring, other.cstring); return *this; } // alternatively, replace both assignment operators with // rule_of_five& operator=(rule_of_five other) noexcept // { // std::swap(cstring, other.cstring); // return *this; // } }; ``` Unlike Rule of Three, failing to provide move constructor and move assignment is usually not an error, but a missed optimization opportunity. ### Rule of zero Classes that have custom destructors, copy/move constructors or copy/move assignment operators should deal exclusively with ownership (which follows from the [Single Responsibility Principle](https://en.wikipedia.org/wiki/Single_responsibility_principle "enwiki:Single responsibility principle")). Other classes should not have custom destructors, copy/move constructors or copy/move assignment operators[[1]](#cite_note-1). This rule also appears in the C++ Core Guidelines as [C.20: If you can avoid defining default operations, do](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-zero). ``` class rule_of_zero { std::string cppstring; public: rule_of_zero(const std::string& arg) : cppstring(arg) {} }; ``` When a base class is intended for polymorphic use, its destructor may have to be declared public and virtual. This blocks implicit moves (and deprecates implicit copies), and so the special member functions have to be declared as defaulted[[2]](#cite_note-2). ``` class base_of_five_defaults { public: base_of_five_defaults(const base_of_five_defaults&) = default; base_of_five_defaults(base_of_five_defaults&&) = default; base_of_five_defaults& operator=(const base_of_five_defaults&) = default; base_of_five_defaults& operator=(base_of_five_defaults&&) = default; virtual ~base_of_five_defaults() = default; }; ``` however, this makes the class prone to slicing, which is why polymorphic classes often define copy as deleted (see [C.67: A polymorphic class should suppress copying](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-copy-virtual) in C++ Core Guidelines), which leads to the following generic wording for the Rule of Five: [C.21: If you define or =delete any default operation, define or =delete them all](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-five). ### External links 1. ["Rule of Zero", R. Martinho Fernandes 08/15/2012](https://web.archive.org/web/20130211035910/http://flamingdangerzone.com/cxx11/2012/08/15/rule-of-zero.html) 2. ["A Concern about the Rule of Zero", Scott Meyers, 3/13/2014](http://scottmeyers.blogspot.fr/2014/03/a-concern-about-rule-of-zero.html). cpp Memory model Memory model ============ Defines the semantics of computer memory storage for the purpose of the C++ abstract machine. The memory available to a C++ program is one or more contiguous sequences of *bytes*. Each byte in memory has a unique *address*. ### Byte A *byte* is the smallest addressable unit of memory. It is defined as a contiguous sequence of bits, large enough to hold. | | | | --- | --- | | * the value of any `UTF-8` code unit (256 distinct values) and of | (since C++14) | | | | | --- | --- | | * any member of the [basic execution character set](charset#Basic_execution_character_set "cpp/language/charset"). | (until C++23) | | | | | --- | --- | | * the ordinary literal encoding of any element of the [basic literal character set](charset#Basic_literal_character_set "cpp/language/charset"). | (since C++23) | Similar to C, C++ supports bytes of sizes 8 bits and greater. The [types](types "cpp/language/types") `char`, `unsigned char`, and `signed char` use one byte for both storage and [value representation](object "cpp/language/object"). The number of bits in a byte is accessible as `[CHAR\_BIT](../types/climits "cpp/types/climits")` or `[std::numeric\_limits](http://en.cppreference.com/w/cpp/types/numeric_limits)<unsigned char>::digits`. ### Memory location A *memory location* is. * an object of [scalar type](type "cpp/language/type") (arithmetic type, pointer type, enumeration type, or std::nullptr\_t) * or the largest contiguous sequence of [bit fields](bit_field "cpp/language/bit field") of non-zero length Note: Various features of the language, such as [references](reference "cpp/language/reference") and [virtual functions](virtual "cpp/language/virtual"), might involve additional memory locations that are not accessible to programs but are managed by the implementation. ``` struct S { char a; // memory location #1 int b : 5; // memory location #2 int c : 11, // memory location #2 (continued) : 0, d : 8; // memory location #3 struct { int ee : 8; // memory location #4 } e; } obj; // The object 'obj' consists of 4 separate memory locations ``` ### Threads and data races A thread of execution is a flow of control within a program that begins with the invocation of a top-level function by `[std::thread::thread](../thread/thread/thread "cpp/thread/thread/thread")`, `[std::async](../thread/async "cpp/thread/async")`, or other means. Any thread can potentially access any object in the program (objects with automatic and thread-local [storage duration](storage_duration "cpp/language/storage duration") may still be accessed by another thread through a pointer or by reference). Different threads of execution are always allowed to access (read and modify) different *memory locations* concurrently, with no interference and no synchronization requirements. When an [evaluation](eval_order "cpp/language/eval order") of an expression writes to a memory location and another evaluation reads or modifies the same memory location, the expressions are said to *conflict*. A program that has two conflicting evaluations has a *data race* unless. * both evaluations execute on the same thread or in the same [signal handler](../utility/program/signal#Signal_handler "cpp/utility/program/signal"), or * both conflicting evaluations are atomic operations (see `[std::atomic](../atomic/atomic "cpp/atomic/atomic")`), or * one of the conflicting evaluations *happens-before* another (see `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`) If a data race occurs, the behavior of the program is undefined. (In particular, release of a `[std::mutex](../thread/mutex "cpp/thread/mutex")` is *synchronized-with*, and therefore, *happens-before* acquisition of the same mutex by another thread, which makes it possible to use mutex locks to guard against data races.). ``` int cnt = 0; auto f = [&]{cnt++;}; std::thread t1{f}, t2{f}, t3{f}; // undefined behavior ``` ``` std::atomic<int> cnt{0}; auto f = [&]{cnt++;}; std::thread t1{f}, t2{f}, t3{f}; // OK ``` ### Memory order When a thread reads a value from a memory location, it may see the initial value, the value written in the same thread, or the value written in another thread. See `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")` for details on the order in which writes made from threads become visible to other threads. ### Forward progress #### Obstruction freedom When only one thread that is not blocked in a standard library function executes an [atomic function](../thread#Atomic_operations "cpp/thread") that is lock-free, that execution is guaranteed to complete (all standard library lock-free operations are [obstruction-free](https://en.wikipedia.org/wiki/Non-blocking_algorithm#Obstruction-freedom "enwiki:Non-blocking algorithm")). #### Lock freedom When one or more lock-free atomic functions run concurrently, at least one of them is guaranteed to complete (all standard library lock-free operations are [lock-free](https://en.wikipedia.org/wiki/Non-blocking_algorithm#Lock-freedom "enwiki:Non-blocking algorithm") -- it is the job of the implementation to ensure they cannot be live-locked indefinitely by other threads, such as by continuously stealing the cache line). #### Progress guarantee In a valid C++ program, every thread eventually does one of the following: * terminate * makes a call to an I/O library function * performs an access through a [volatile](cv "cpp/language/cv") glvalue * performs an atomic operation or a synchronization operation No thread of execution can execute forever without performing any of these observable behaviors. Note that it means that a program with endless recursion or endless loop (whether implemented as a [for-statement](for "cpp/language/for") or by looping [goto](goto "cpp/language/goto") or otherwise) has [undefined behavior](ub "cpp/language/ub"). This allows the compilers to remove all loops that have no observable behavior, without having to prove that they would eventually terminate. A thread is said to *make progress* if it performs one of the execution steps above (I/O, volatile, atomic, or synchronization), blocks in a standard library function, or calls an atomic lock-free function that does not complete because of a non-blocked concurrent thread. | | | | --- | --- | | Concurrent forward progress If a thread offers *concurrent forward progress guarantee*, it will *make progress* (as defined above) in finite amount of time, for as long as it has not terminated, regardless of whether other threads (if any) are making progress. The standard encourages, but doesn't require that the main thread and the threads started by `[std::thread](../thread/thread "cpp/thread/thread")` offer concurrent forward progress guarantee. Parallel forward progress If a thread offers *parallel forward progress guarantee*, the implementation is not required to ensure that the thread will eventually make progress if it has not yet executed any execution step (I/O, volatile, atomic, or synchronization), but once this thread has executed a step, it provides *concurrent forward progress* guarantees (this rule describes a thread in a thread pool that executes tasks in arbitrary order). Weakly parallel forward progress If a thread offers *weakly parallel forward progress guarantee*, it does not guarantee to eventually make progress, regardless of whether other threads make progress or not. Such threads can still be guaranteed to make progress by blocking with forward progress guarantee delegation: if a thread P blocks in this manner on the completion of a set of threads S, then at least one thread in S will offer a forward progress guarantee that is same or stronger than P. Once that thread completes, another thread in S will be similarly strengthened. Once the set is empty, P will unblock. The [parallel algorithms](../algorithm "cpp/algorithm") from the C++ standard library block with forward progress delegation on the completion of an unspecified set of library-managed threads. | (since C++17) | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/memory_model "c/language/memory model") for Memory model | cpp while loop while loop ========== Executes a statement repeatedly, until the value of condition becomes `false`. The test takes place before each iteration. ### Syntax | | | | | --- | --- | --- | | attr(optional) `while (` condition `)` statement | | | | | | | | --- | --- | --- | | attr | - | (since C++11) any number of [attributes](attributes "cpp/language/attributes") | | condition | - | any [expression](expressions "cpp/language/expressions") which is [contextually convertible](implicit_cast "cpp/language/implicit cast") to bool or a [declaration](declarations "cpp/language/declarations") of a single variable with a brace-or-equals [initializer](initialization "cpp/language/initialization"). This expression is evaluated before each iteration, and if it yields `false`, the loop is exited. If this is a declaration, the initializer is evaluated before each iteration, and if the value of the declared variable converts to `false`, the loop is exited. | | statement | - | any [statement](statements "cpp/language/statements"), typically a compound statement, which is the body of the loop | ### Explanation Whether statement is a compound statement or not, it always introduces a [block scope](scope "cpp/language/scope"). Variables declared in it are only visible in the loop body, in other words, ``` while (--x >= 0) int i; // i goes out of scope ``` is the same as. ``` while (--x >= 0) { int i; } // i goes out of scope ``` If condition is a declaration such as `T t = x`, the declared variable is only in scope in the body of the loop, and is destroyed and recreated on every iteration, in other words, such while loop is equivalent to. ``` label: { // start of condition scope T t = x; if (t) { statement goto label; // calls the destructor of t } } ``` If the execution of the loop needs to be terminated at some point, [break statement](break "cpp/language/break") can be used as terminating statement. If the execution of the loop needs to be continued at the end of the loop body, [continue statement](continue "cpp/language/continue") can be used as shortcut. ### Notes As part of the C++ [forward progress guarantee](memory_model#Forward_progress "cpp/language/memory model"), the behavior is [undefined](ub "cpp/language/ub") if a loop that has no [observable behavior](as_if "cpp/language/as if") (does not make calls to I/O functions, access volatile objects, or perform atomic or synchronization operations) does not terminate. Compilers are permitted to remove such loops. ### Keywords [`while`](../keyword/while "cpp/keyword/while"). ### Example ``` #include <iostream> int main() { // while loop with a single statement int i = 0; while (i < 10) i++; std::cout << i << '\n'; // while loop with a compound statement int j = 2; while (j < 9) { std::cout << j << ' '; j += 2; } std::cout << '\n'; // while loop with a declaration condition char cstr[] = "Hello"; int k = 0; while (char c = cstr[k++]) std::cout << c; std::cout << '\n'; } ``` Output: ``` 10 2 4 6 8 Hello ``` ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/while "c/language/while") for `while` | cpp Initialization Initialization ============== *Initialization* of a variable provides its initial value at the time of construction. The initial value may be provided in the initializer section of a [declarator](declarations "cpp/language/declarations") or a [new expression](new "cpp/language/new"). It also takes place during function calls: function parameters and the function return values are also initialized. For each declarator, the initializer may be one of the following: | | | | | --- | --- | --- | | `(` expression-list `)` | (1) | | | `=` expression | (2) | | | `{` initializer-list `}` | (3) | | 1) comma-separated list of arbitrary expressions and braced-init-lists in parentheses 2) the equals sign followed by an expression 3) braced-init-list: possibly empty, comma-separated list of expressions and other braced-init-lists Depending on context, the initializer may invoke: * [Value initialization](value_initialization "cpp/language/value initialization"), e.g. `[std::string](http://en.cppreference.com/w/cpp/string/basic_string) s{};` * [Direct initialization](direct_initialization "cpp/language/direct initialization"), e.g. `[std::string](http://en.cppreference.com/w/cpp/string/basic_string) s("hello");` * [Copy initialization](copy_initialization "cpp/language/copy initialization"), e.g. `[std::string](http://en.cppreference.com/w/cpp/string/basic_string) s = "hello";` * [List initialization](list_initialization "cpp/language/list initialization"), e.g. `[std::string](http://en.cppreference.com/w/cpp/string/basic_string) s{'a', 'b', 'c'};` * [Aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization"), e.g. `char a[3] = {'a', 'b'};` * [Reference initialization](reference_initialization "cpp/language/reference initialization"), e.g. `char& c = a[0];` If no initializer is provided, the rules of [default initialization](default_initialization "cpp/language/default initialization") apply. ### Non-local variables All non-local variables with static [storage duration](storage_duration "cpp/language/storage duration") are initialized as part of program startup, before the execution of the [main function](main_function "cpp/language/main function") begins (unless deferred, see below). All non-local variables with thread-local storage duration are initialized as part of thread launch, sequenced-before the execution of the thread function begins. For both of these classes of variables, initialization occurs in two distinct stages: #### Static initialization There are two forms of static initialization: 1) If possible, [constant initialization](constant_initialization "cpp/language/constant initialization") is applied. 2) Otherwise, non-local static and thread-local variables are [zero-initialized](zero_initialization "cpp/language/zero initialization"). In practice: * Constant initialization is usually applied at compile time. Pre-calculated object representations are stored as part of the program image. If the compiler doesn't do that, it must still guarantee that the initialization happens before any dynamic initialization. * Variables to be zero-initialized are placed in the `.bss` segment of the program image, which occupies no space on disk and is zeroed out by the OS when loading the program. #### Dynamic initialization After all static initialization is completed, dynamic initialization of non-local variables occurs in the following situations: 1) *Unordered dynamic initialization*, which applies only to (static/thread-local) class template [static data members](static "cpp/language/static") and [variable templates](variable_template "cpp/language/variable template") (since C++14) that aren't [explicitly specialized](template_specialization "cpp/language/template specialization"). Initialization of such static variables is indeterminately sequenced with respect to all other dynamic initialization except if the program starts a thread before a variable is initialized, in which case its initialization is unsequenced (since C++17). Initialization of such thread-local variables is unsequenced with respect to all other dynamic initialization. | | | | --- | --- | | 2) *Partially-ordered dynamic initialization*, which applies to all inline variables that are not an implicitly or explicitly instantiated specialization. If a partially-ordered V is defined before ordered or partially-ordered W in every translation unit, the initialization of V is sequenced before the initialization of W (or happens-before, if the program starts a thread). | (since C++17) | 3) *Ordered dynamic initialization*, which applies to all other non-local variables: within a single translation unit, initialization of these variables is always [sequenced](eval_order "cpp/language/eval order") in exact order their definitions appear in the source code. Initialization of static variables in different translation units is indeterminately sequenced. Initialization of thread-local variables in different translation units is unsequenced. If the initialization of a non-local variable with static or thread storage duration exits via an exception, `[std::terminate](../error/terminate "cpp/error/terminate")` is called. #### Early dynamic initialization The compilers are allowed to initialize dynamically-initialized variables as part of static initialization (essentially, at compile time), if the following conditions are both true: 1) the dynamic version of the initialization does not change the value of any other object of namespace scope prior to its initialization 2) the static version of the initialization produces the same value in the initialized variable as would be produced by the dynamic initialization if all variables not required to be initialized statically were initialized dynamically. Because of the rule above, if initialization of some object `o1` refers to an namespace-scope object `o2`, which potentially requires dynamic initialization, but is defined later in the same translation unit, it is unspecified whether the value of `o2` used will be the value of the fully initialized `o2` (because the compiler promoted initialization of `o2` to compile time) or will be the value of `o2` merely zero-initialized. ``` inline double fd() { return 1.0; } extern double d1; double d2 = d1; // unspecified: // dynamically initialized to 0.0 if d1 is dynamically initialized, or // dynamically initialized to 1.0 if d1 is statically initialized, or // statically initialized to 0.0 (because that would be its value // if both variables were dynamically initialized) double d1 = fd(); // may be initialized statically or dynamically to 1.0 ``` #### Deferred dynamic initialization It is implementation-defined whether dynamic initialization happens-before the first statement of the main function (for statics) or the initial function of the thread (for thread-locals), or deferred to happen after. If the initialization of a non-inline variable (since C++17) is deferred to happen after the first statement of main/thread function, it happens before the first [odr-use](definition#ODR-use "cpp/language/definition") of any variable with static/thread storage duration defined in the same translation unit as the variable to be initialized. If no variable or function is odr-used from a given translation unit, the non-local variables defined in that translation unit may never be initialized (this models the behavior of an on-demand dynamic library). However, as long as anything from a translation unit is odr-used, all non-local variables whose initialization or destruction has side effects will be initialized even if they are not used in the program. | | | | --- | --- | | If the initialization of an inline variable is deferred, it happens before the first [odr-use](definition#ODR-use "cpp/language/definition") of that specific variable. | (since C++17) | ``` // ============ // == File 1 == #include "a.h" #include "b.h" B b; A::A() { b.Use(); } // ============ // == File 2 == #include "a.h" A a; // ============ // == File 3 == #include "a.h" #include "b.h" extern A a; extern B b; int main() { a.Use(); b.Use(); } // If a is initialized before main is entered, b may still be uninitialized // at the point where A::A() uses it (because dynamic initialization is // indeterminately sequenced across translation units) // If a is initialized at some point after the first statement of main (which odr-uses // a function defined in File 1, forcing its dynamic initialization to run), // then b will be initialized prior to its use in A::A ``` ### Static local variables For initialization of locals (that is, block scope) static and thread-local variables, see [static local variables](storage_duration#Static_local_variables "cpp/language/storage duration"). Initializer is not allowed in a block-scope declaration of a variable with [external or internal linkage](storage_duration#Linkage "cpp/language/storage duration"). Such a declaration must appear with `extern` and cannot be a definition. ### Class members Non-static data members can be initialized with [member initializer list](initializer_list "cpp/language/initializer list") or with a [default member initializer](data_members#Member_initialization "cpp/language/data members"). ### Notes The order of destruction of non-local variables is described in `[std::exit](../utility/program/exit "cpp/utility/program/exit")`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 270](https://cplusplus.github.io/CWG/issues/270.html) | C++98 | the order of initializing static data membersof class templates was unspecified | specified as unordered except forexplicit specializations and definitions | | [CWG 441](https://cplusplus.github.io/CWG/issues/441.html) | C++98 | non-local references with static storage duration werenot always initialized before dynamic initializations | considered as static initialization, alwaysinitialized before dynamic initializations | | [CWG 1415](https://cplusplus.github.io/CWG/issues/1415.html) | C++98 | a block-scope `extern` variabledeclaration could be a definition | prohibited (no initializerallowed in such declarations) | ### See also * [copy elision](copy_elision "cpp/language/copy elision") * [converting constructor](converting_constructor "cpp/language/converting constructor") * [copy constructor](copy_constructor "cpp/language/copy constructor") * [default constructor](default_constructor "cpp/language/default constructor") * [`explicit`](explicit "cpp/language/explicit") * [move constructor](move_constructor "cpp/language/move constructor") * [`new`](new "cpp/language/new") | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/initialization "c/language/initialization") for Initialization |
programming_docs
cpp Declarations Declarations ============ *Declarations* introduce (or re-introduce) names into the C++ program. Each kind of entity is declared differently. [Definitions](definition "cpp/language/definition") are declarations that are sufficient to use the entity identified by the name. A declaration is one of the following: * [Function definition](function#Function_definition "cpp/language/function") * [Template declaration](templates "cpp/language/templates") (including [Partial template specialization](partial_specialization "cpp/language/partial specialization")) * [Explicit template instantiation](class_template#Explicit_instantiation "cpp/language/class template") * [Explicit template specialization](template_specialization "cpp/language/template specialization") * [Namespace definition](namespace "cpp/language/namespace") * [Linkage specification](language_linkage "cpp/language/language linkage") | | | | --- | --- | | * Attribute declaration ([attr](attributes "cpp/language/attributes") `;`) | (since C++11) | * Empty declaration (`;`) * A function declaration without a decl-specifier-seq: | | | | | --- | --- | --- | | attr(optional) declarator `;` | | | | | | | | --- | --- | --- | | attr | - | (since C++11) sequence of any number of [attributes](attributes "cpp/language/attributes") | | declarator | - | a function declarator | This declaration must declare a constructor, destructor, or user-defined type [conversion function](cast_operator "cpp/language/cast operator"). It can only be used as part of a [template declaration](templates "cpp/language/templates"), [explicit specialization](template_specialization "cpp/language/template specialization"), or explicit instantiation. * block-declaration (a declaration that can appear inside a [block](statements#Compound_statement "cpp/language/statements")), which, in turn, can be one of the following: + [asm declaration](asm "cpp/language/asm") | | | | --- | --- | | * [type alias declaration](type_alias "cpp/language/type alias") | (since C++11) | * [namespace alias definition](namespace_alias "cpp/language/namespace alias") * [using-declaration](using_declaration "cpp/language/using declaration") * [using directive](namespace#Using-directives "cpp/language/namespace") | | | | --- | --- | | * [using-enum-declaration](enum#Using-enum-declaration "cpp/language/enum") | (since C++20) | | | | | --- | --- | | * [`static_assert`](static_assert "cpp/language/static assert") declaration * [opaque enum declaration](enum "cpp/language/enum") | (since C++11) | * simple declaration ### Simple declaration A simple declaration is a statement that introduces, creates, and optionally initializes one or several identifiers, typically variables. | | | | | --- | --- | --- | | decl-specifier-seq init-declarator-list(optional) `;` | (1) | | | attr decl-specifier-seq init-declarator-list`;` | (2) | | | | | | | --- | --- | --- | | attr | - | (since C++11) sequence of any number of [attributes](attributes "cpp/language/attributes") | | decl-specifier-seq | - | sequence of *specifiers* (see below) | | init-declarator-list | - | comma-separated list of *declarators* with optional *initializers*. init-declarator-list is optional when declaring a named class/struct/union or a named enumeration | A [structured binding declaration](structured_binding "cpp/language/structured binding") is also a simple declaration. (since C++17). ### Specifiers **Declaration specifiers** (decl-specifier-seq) is a sequence of the following whitespace-separated specifiers, in any order: * the [`typedef`](typedef "cpp/language/typedef") specifier. If present, the entire declaration is a [typedef declaration](typedef "cpp/language/typedef") and each declarator introduces a new type name, not an object or a function. * function specifiers ([`inline`](inline "cpp/language/inline"), [`virtual`](virtual "cpp/language/virtual"), [`explicit`](explicit "cpp/language/explicit")), only allowed in [function declarations](function "cpp/language/function") | | | | --- | --- | | * the [`inline`](inline "cpp/language/inline") specifier is also allowed on variable declarations. | (since C++17) | * the [`friend`](friend "cpp/language/friend") specifier, allowed in class and function declarations. | | | | --- | --- | | * the [`constexpr`](constexpr "cpp/language/constexpr") specifier, only allowed in variable definitions, function and function template declarations, and the declaration of static data members of literal type. | (since C++11) | | | | | --- | --- | | * the [`consteval`](consteval "cpp/language/consteval") specifier, only allowed in function and function template declarations. * the [`constinit`](constinit "cpp/language/constinit") specifier, only allowed in declaration of a variable with static or thread storage duration. At most one of the `constexpr`, `consteval`, and `constinit` specifiers is allowed to appear in a decl-specifier-seq. | (since C++20) | * [storage class specifier](storage_duration "cpp/language/storage duration") ([`register`](../keyword/register "cpp/keyword/register"), (until C++17) [`static`](../keyword/static "cpp/keyword/static"), [`thread_local`](../keyword/thread_local "cpp/keyword/thread local"), (since C++11) [`extern`](../keyword/extern "cpp/keyword/extern"), [`mutable`](../keyword/mutable "cpp/keyword/mutable")). Only one storage class specifier is allowed, except that `thread_local` may appear together with `extern` or `static`. * **Type specifiers** (type-specifier-seq), a sequence of specifiers that names a type. The type of every entity introduced by the declaration is this type, optionally modified by the declarator (see below). This sequence of specifiers is also used by [type-id](type#Type_naming "cpp/language/type"). Only the following specifiers are part of type-specifier-seq, in any order: * [class specifier](class "cpp/language/class") * [enum specifier](enum "cpp/language/enum") * simple type specifier + [`char`](../keyword/char "cpp/keyword/char"), [`char8_t`](../keyword/char8_t "cpp/keyword/char8 t"), (since C++20) [`char16_t`](../keyword/char16_t "cpp/keyword/char16 t"), [`char32_t`](../keyword/char32_t "cpp/keyword/char32 t"), (since C++11) [`wchar_t`](../keyword/wchar_t "cpp/keyword/wchar t"), [`bool`](../keyword/bool "cpp/keyword/bool"), [`short`](../keyword/short "cpp/keyword/short"), [`int`](../keyword/int "cpp/keyword/int"), [`long`](../keyword/long "cpp/keyword/long"), [`signed`](../keyword/signed "cpp/keyword/signed"), [`unsigned`](../keyword/unsigned "cpp/keyword/unsigned"), [`float`](../keyword/float "cpp/keyword/float"), [`double`](../keyword/double "cpp/keyword/double"), [`void`](../keyword/void "cpp/keyword/void") | | | | --- | --- | | * [`auto`](auto "cpp/language/auto") * [decltype specifier](decltype "cpp/language/decltype") | (since C++11) | * previously declared class name (optionally [qualified](identifiers#Qualified_identifiers "cpp/language/identifiers")) * previously declared enum name (optionally [qualified](identifiers#Qualified_identifiers "cpp/language/identifiers")) * previously declared [typedef-name](typedef "cpp/language/typedef") or [type alias](type_alias "cpp/language/type alias") (since C++11) (optionally [qualified](identifiers#Qualified_identifiers "cpp/language/identifiers")) * template name with template arguments (optionally [qualified](identifiers#Qualified_identifiers "cpp/language/identifiers"), optionally using [template disambiguator](dependent_name "cpp/language/dependent name")) | | | | --- | --- | | * template name without template arguments (optionally [qualified](identifiers#Qualified_identifiers "cpp/language/identifiers")): see [class template argument deduction](class_template_argument_deduction "cpp/language/class template argument deduction") | (since C++17) | * [elaborated type specifier](elaborated_type_specifier "cpp/language/elaborated type specifier") + the keyword [`class`](../keyword/class "cpp/keyword/class"), [`struct`](../keyword/struct "cpp/keyword/struct"), or [`union`](../keyword/union "cpp/keyword/union"), followed by the identifier (optionally [qualified](identifiers#Qualified_identifiers "cpp/language/identifiers")), previously defined as the name of a class, struct, or union. + the keyword [`class`](../keyword/class "cpp/keyword/class"), [`struct`](../keyword/struct "cpp/keyword/struct"), or [`union`](../keyword/union "cpp/keyword/union"), followed by template name with template arguments (optionally [qualified](identifiers#Qualified_identifiers "cpp/language/identifiers"), optionally using [template disambiguator](dependent_name "cpp/language/dependent name")), previously defined as the name of a class template. + the keyword [`enum`](../keyword/enum "cpp/keyword/enum") followed by the identifier (optionally [qualified](identifiers#Qualified_identifiers "cpp/language/identifiers")), previously declared as the name of an enumeration. * [typename specifier](dependent_name "cpp/language/dependent name") * [cv qualifier](cv "cpp/language/cv") only one type specifier is allowed in a decl-specifier-seq, with the following exceptions: * `const` can be combined with any type specifier except itself. * `volatile` can be combined with any type specifier except itself. * `signed` or `unsigned` can be combined with `char`, `long`, `short`, or `int`. * `short` or `long` can be combined with `int`. * `long` can be combined with `double`. | | | | --- | --- | | * `long` can be combined with `long`. | (since C++11) | [Attributes](attributes "cpp/language/attributes") may appear in decl-specifier-seq, in which case they apply to the type determined by the preceding specifiers. Repetitions of any specifier in a decl-specifier-seq, such as `const static const`, or `virtual inline virtual` are errors, except that `long` is allowed to appear twice (since C++11). ### Declarators init-declarator-list is a comma-separated sequence of one or more init-declarators, which have the following syntax: | | | | | --- | --- | --- | | declarator initializer(optional) | (1) | | | declarator requires-clause | (2) | (since C++20) | | | | | | --- | --- | --- | | declarator | - | the declarator | | initializer | - | optional initializer (except where required, such as when initializing references or const objects). See [Initialization](initialization "cpp/language/initialization") for details. | | requires-clause | - | [a requires-clause](constraints#Requires_clauses "cpp/language/constraints"), which adds a [constraint](constraints "cpp/language/constraints") to a [function declaration](function "cpp/language/function") | Each init-declarator in a init-declarator sequence `S D1, D2, D3;` is processed as if it were a standalone declaration with the same specifiers: `S D1; S D2; S D3;`. Each declarator introduces exactly one object, reference, function, or (for typedef declarations) type alias, whose type is provided by decl-specifier-seq and optionally modified by operators such as `&` (reference to) or `[]` (array of) or `()` (function returning) in the declarator. These operators can be applied recursively, as shown below. A declarator is one of the following: | | | | | --- | --- | --- | | unqualified-id attr(optional) | (1) | | | qualified-id attr(optional) | (2) | | | `...` identifier attr(optional) | (3) | (since C++11) | | `*` attr(optional) cv(optional) declarator | (4) | | | nested-name-specifier `*` attr(optional) cv(optional) declarator | (5) | | | `&` attr(optional) declarator | (6) | | | `&&` attr(optional) declarator | (7) | (since C++11) | | noptr-declarator `[` constexpr(optional) `]` attr(optional) | (8) | | | noptr-declarator `(` parameter-list `)` cv(optional) ref(optional) except(optional) attr(optional) | (9) | | 1) The [name](name "cpp/language/name") that is declared. 2) A declarator that uses a [qualified identifier](identifiers#Qualified_identifiers "cpp/language/identifiers") (qualified-id) defines or redeclares a previously declared [namespace member](namespace#Namespaces "cpp/language/namespace") or [class member](classes "cpp/language/classes"). 3) [Parameter pack](parameter_pack "cpp/language/parameter pack"), only appears in [parameter declarations](function#Parameter_list "cpp/language/function"). 4) [Pointer declarator](pointer "cpp/language/pointer"): the declaration `S * D;` declares `D` as a pointer to the type determined by decl-specifier-seq `S`. 5) [Pointer to member declaration](pointer "cpp/language/pointer"): the declaration `S C::* D;` declares `D` as a pointer to member of `C` of type determined by decl-specifier-seq `S`. nested-name-specifier is a [sequence of names and scope resolution operators `::`](identifiers#Qualified_identifiers "cpp/language/identifiers") 6) [Lvalue reference declarator](reference "cpp/language/reference"): the declaration `S & D;` declares `D` as an lvalue reference to the type determined by decl-specifier-seq `S`. 7) [Rvalue reference declarator](reference "cpp/language/reference"): the declaration `S && D;` declares `D` as an rvalue reference to the type determined by decl-specifier-seq `S`. 8) [Array declarator](array "cpp/language/array"). noptr-declarator any valid declarator, but if it begins with \*, &, or &&, it has to be surrounded by parentheses. 9) [Function declarator](function "cpp/language/function"). noptr-declarator any valid declarator, but if it begins with \*, &, or &&, it has to be surrounded by parentheses. Note that the outermost function declarator may end with the optional trailing return type. (since C++11) | | | | --- | --- | | In all cases, attr is an optional sequence of [attributes](attributes "cpp/language/attributes"). When appearing immediately after the identifier, it applies to the object being declared. | (since C++11) | cv is a sequence of [const and volatile](cv "cpp/language/cv") qualifiers, where either qualifier may appear at most once in the sequence. ### Notes When a block-declaration appears [inside a block](statements#Compound_statements "cpp/language/statements"), and an identifier introduced by a declaration was previously declared in an outer block, the [outer declaration is hidden](scope "cpp/language/scope") for the remainder of the block. If a declaration introduces a variable with automatic storage duration, it is initialized when its declaration statement is executed. All automatic variables declared in a block are destroyed on exit from the block (regardless how the block is exited: via [exception](exceptions "cpp/language/exceptions"), [goto](goto "cpp/language/goto"), or by reaching its end), in order opposite to their order of initialization. ### Examples Note: this example demonstrates how some complex declarations are parsed in terms of the language grammar. Other popular mnemonics are: [the spiral rule](http://c-faq.com/decl/spiral.anderson.html), reading [inside-out](https://stackoverflow.com/a/34560439/273767), and [declaration mirrors use](https://stackoverflow.com/a/34552915/273767). There is also an automated parser at <http://cdecl.org>. ``` #include <string> class C { std::string member; // decl-specifier-seq is "std::string" // declarator is "member" } obj, *pObj(&obj); // decl-specifier-seq is "class C { std::string member; }" // declarator "obj" defines an object of type C // declarator "*pObj(&obj)" declares and initializes a pointer to C int a = 1, *p = nullptr, f(), (*pf)(double); // decl-specifier-seq is int // declarator a = 1 defines and initializes a variable of type int // declarator *p = nullptr defines and initializes a variable of type int* // declarator (f)() declares (but doesn't define) // a function taking no arguments and returning int // declarator (*pf)(double) defines a pointer to function // taking double and returning int int (*(*foo)(double))[3] = nullptr; // decl-specifier-seq is int // 1. declarator "(*(*foo)(double))[3]" is an array declarator: // the type declared is "/nested declarator/ array of 3 int" // 2. the nested declarator is "(*(*foo)(double))", which is a pointer declarator // the type declared is "/nested declarator/ pointer to array of 3 int" // 3. the nested declarator is "(*foo)(double)", which is a function declarator // the type declared is "/nested declarator/ function taking double and returning // pointer to array of 3 int" // 4. the nested declarator is "(*foo)" which is a (parenthesized, as required by // function declarator syntax) pointer declarator. // the type declared is "/nested declarator/ pointer to function taking double // and returning pointer to array of 3 int" // 5. the nested declarator is "foo", which is an identifier. // The declaration declares the object foo of type "pointer to function taking double // and returning pointer to array of 3 int" // The initializer "= nullptr" provides the initial value of this pointer. ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 482](https://cplusplus.github.io/CWG/issues/482.html) | C++98 | the declarators of redeclarations could not be qualified | qualified declarators allowed | | [CWG 569](https://cplusplus.github.io/CWG/issues/569.html) | C++98 | a single standalone semicolon was not a valid declaration | it is an empty declaration,which has no effect | | [CWG 1830](https://cplusplus.github.io/CWG/issues/1830.html) | C++98 | repetition of a function specifier in a decl-specifier-seq was allowed | repetition is forbidden | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/declarations "c/language/declarations") for Declarations | | | cpp C++ Operator Precedence C++ Operator Precedence ======================= The following table lists the precedence and associativity of C++ operators. Operators are listed top to bottom, in descending precedence. | Precedence | Operator | Description | Associativity | | --- | --- | --- | --- | | 1 | `::` | [Scope resolution](identifiers#Qualified_identifiers "cpp/language/identifiers") | Left-to-right ➔ | | 2 | `a++` `a--` | Suffix/postfix [increment and decrement](operator_incdec "cpp/language/operator incdec") | | `*type*()` `*type*{}` | [Functional cast](explicit_cast "cpp/language/explicit cast") | | `a()` | [Function call](operator_other#Built-in_function_call_operator "cpp/language/operator other") | | `a[]` | [Subscript](operator_member_access#Built-in_subscript_operator "cpp/language/operator member access") | | `.` `->` | [Member access](operator_member_access#Built-in_member_access_operators "cpp/language/operator member access") | | 3 | `++a` `--a` | Prefix [increment and decrement](operator_incdec "cpp/language/operator incdec") | Right-to-left ← | | `+a` `-a` | Unary [plus and minus](operator_arithmetic#Unary_arithmetic_operators "cpp/language/operator arithmetic") | | `!` `~` | [Logical NOT](operator_logical "cpp/language/operator logical") and [bitwise NOT](operator_arithmetic#Bitwise_logic_operators "cpp/language/operator arithmetic") | | `(*type*)` | [C-style cast](explicit_cast "cpp/language/explicit cast") | | `*a` | [Indirection](operator_member_access#Built-in_indirection_operator "cpp/language/operator member access") (dereference) | | `&a` | [Address-of](operator_member_access#Built-in_address-of_operator "cpp/language/operator member access") | | [`sizeof`](sizeof "cpp/language/sizeof") | [Size-of](sizeof "cpp/language/sizeof")[[note 1]](#cite_note-1) | | [`co_await`](../keyword/co_await "cpp/keyword/co await") | [await-expression](coroutines "cpp/language/coroutines") (C++20) | | [`new`](new "cpp/language/new") [`new[]`](new "cpp/language/new") | [Dynamic memory allocation](new "cpp/language/new") | | [`delete`](delete "cpp/language/delete") [`delete[]`](delete "cpp/language/delete") | [Dynamic memory deallocation](delete "cpp/language/delete") | | 4 | `.*` `->*` | [Pointer-to-member](operator_member_access#Built-in_pointer-to-member_access_operators "cpp/language/operator member access") | Left-to-right ➔ | | 5 | `a*b` `a/b` `a%b` | [Multiplication, division, and remainder](operator_arithmetic#Multiplicative_operators "cpp/language/operator arithmetic") | | 6 | `a+b` `a-b` | [Addition and subtraction](operator_arithmetic#Additive_operators "cpp/language/operator arithmetic") | | 7 | `<<` `>>` | Bitwise [left shift and right shift](operator_arithmetic#Bitwise_shift_operators "cpp/language/operator arithmetic") | | 8 | `<=>` | [Three-way comparison operator](operator_comparison#Three-way_comparison "cpp/language/operator comparison") (since C++20) | | 9 | `<` `<=` `>` `>=` | For [relational operators](operator_comparison "cpp/language/operator comparison") < and ≤ and > and ≥ respectively | | 10 | `==` `!=` | For [equality operators](operator_comparison "cpp/language/operator comparison") = and ≠ respectively | | 11 | `a&b` | [Bitwise AND](operator_arithmetic#Bitwise_logic_operators "cpp/language/operator arithmetic") | | 12 | `^` | [Bitwise XOR](operator_arithmetic#Bitwise_logic_operators "cpp/language/operator arithmetic") (exclusive or) | | 13 | `|` | [Bitwise OR](operator_arithmetic#Bitwise_logic_operators "cpp/language/operator arithmetic") (inclusive or) | | 14 | `&&` | [Logical AND](operator_logical "cpp/language/operator logical") | | 15 | `||` | [Logical OR](operator_logical "cpp/language/operator logical") | | 16 | `a?b:c` | [Ternary conditional](operator_other#Conditional_operator "cpp/language/operator other")[[note 2]](#cite_note-2) | Right-to-left ← | | [`throw`](throw "cpp/language/throw") | [throw operator](throw "cpp/language/throw") | | [`co_yield`](../keyword/co_yield "cpp/keyword/co yield") | [yield-expression](coroutines "cpp/language/coroutines") (C++20) | | `=` | [Direct assignment](operator_assignment#Builtin_direct_assignment "cpp/language/operator assignment") (provided by default for C++ classes) | | `+=` `-=` | [Compound assignment](operator_assignment#Builtin_compound_assignment "cpp/language/operator assignment") by sum and difference | | `*=` `/=` `%=` | [Compound assignment](operator_assignment#Builtin_compound_assignment "cpp/language/operator assignment") by product, quotient, and remainder | | `<<=` `>>=` | [Compound assignment](operator_assignment#Builtin_compound_assignment "cpp/language/operator assignment") by bitwise left shift and right shift | | `&=` `^=` `|=` | [Compound assignment](operator_assignment#Builtin_compound_assignment "cpp/language/operator assignment") by bitwise AND, XOR, and OR | | 17 | `,` | [Comma](operator_other#Built-in_comma_operator "cpp/language/operator other") | Left-to-right ➔ | 1. The operand of `sizeof` can't be a C-style type cast: the expression `sizeof (int) * p` is unambiguously interpreted as `(sizeof(int)) * p`, but not `sizeof((int)*p)`. 2. The expression in the middle of the conditional operator (between `?` and `:`) is parsed as if parenthesized: its precedence relative to `?:` is ignored. When parsing an expression, an operator which is listed on some row of the table above with a precedence will be bound tighter (as if by parentheses) to its arguments than any operator that is listed on a row further below it with a lower precedence. For example, the expressions `[std::cout](http://en.cppreference.com/w/cpp/io/cout) << a & b` and `*p++` are parsed as `([std::cout](http://en.cppreference.com/w/cpp/io/cout) << a) & b` and `*(p++)`, and not as `[std::cout](http://en.cppreference.com/w/cpp/io/cout) << (a & b)` or `(*p)++`. Operators that have the same precedence are bound to their arguments in the direction of their associativity. For example, the expression `a = b = c` is parsed as `a = (b = c)`, and not as `(a = b) = c` because of right-to-left associativity of assignment, but `a + b - c` is parsed `(a + b) - c` and not `a + (b - c)` because of left-to-right associativity of addition and subtraction. Associativity specification is redundant for unary operators and is only shown for completeness: unary prefix operators always associate right-to-left (`delete ++*p` is `delete(++(*p))`) and unary postfix operators always associate left-to-right (`a[1][2]++` is `((a[1])[2])++`). Note that the associativity is meaningful for member access operators, even though they are grouped with unary postfix operators: `a.b++` is parsed `(a.b)++` and not `a.(b++)`. Operator precedence is unaffected by [operator overloading](operators "cpp/language/operators"). For example, `[std::cout](http://en.cppreference.com/w/cpp/io/cout) << a ? b : c;` parses as `([std::cout](http://en.cppreference.com/w/cpp/io/cout) << a) ? b : c;` because the precedence of arithmetic left shift is higher than the conditional operator. ### Notes Precedence and associativity are compile-time concepts and are independent from [order of evaluation](eval_order "cpp/language/eval order"), which is a runtime concept. The standard itself doesn't specify precedence levels. They are derived from the grammar. [`const_cast`](const_cast "cpp/language/const cast"), [`static_cast`](static_cast "cpp/language/static cast"), [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast"), [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast"), [`typeid`](typeid "cpp/language/typeid"), [`sizeof...`](sizeof... "cpp/language/sizeof..."), [`noexcept`](noexcept "cpp/language/noexcept") and [`alignof`](alignof "cpp/language/alignof") are not included since they are never ambiguous. Some of the operators have [alternate spellings](operator_alternative "cpp/language/operator alternative") (e.g., `and` for `&&`, `or` for `||`, `not` for `!`, etc.). In C, the ternary conditional operator has higher precedence than assignment operators. Therefore, the expression `e = a < d ? a++ : a = d`, which is parsed in C++ as `e = ((a < d) ? (a++) : (a = d))`, will fail to compile in C due to grammatical or semantic constraints in C. See the corresponding C page for details. ### See also | Common operators | | --- | | [assignment](operator_assignment "cpp/language/operator assignment") | [incrementdecrement](operator_incdec "cpp/language/operator incdec") | [arithmetic](operator_arithmetic "cpp/language/operator arithmetic") | [logical](operator_logical "cpp/language/operator logical") | [comparison](operator_comparison "cpp/language/operator comparison") | [memberaccess](operator_member_access "cpp/language/operator member access") | [other](operator_other "cpp/language/operator other") | | `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b a <=> b`. | `a[b] *a &a a->b a.b a->*b a.*b`. | `a(...) a, b a ? b : c`. | | Special operators | | [`static_cast`](static_cast "cpp/language/static cast") converts one type to another related type [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") converts within inheritance hierarchies [`const_cast`](const_cast "cpp/language/const cast") adds or removes [cv](cv "cpp/language/cv") qualifiers [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") converts type to unrelated type [C-style cast](explicit_cast "cpp/language/explicit cast") converts one type to another by a mix of `static_cast`, `const_cast`, and `reinterpret_cast` [`new`](new "cpp/language/new") creates objects with dynamic storage duration [`delete`](delete "cpp/language/delete") destructs objects previously created by the new expression and releases obtained memory area [`sizeof`](sizeof "cpp/language/sizeof") queries the size of a type [`sizeof...`](sizeof... "cpp/language/sizeof...") queries the size of a [parameter pack](parameter_pack "cpp/language/parameter pack") (since C++11) [`typeid`](typeid "cpp/language/typeid") queries the type information of a type [`noexcept`](noexcept "cpp/language/noexcept") checks if an expression can throw an exception (since C++11) [`alignof`](alignof "cpp/language/alignof") queries alignment requirements of a type (since C++11). | | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/operator_precedence "c/language/operator precedence") for C operator precedence |
programming_docs
cpp Main function Main function ============= A program shall contain a global function named `main`, which is the designated start of the program in hosted environment. It shall have one of the following forms: | | | | | --- | --- | --- | | `int` `main` `()` `{` body `}` | (1) | | | `int` `main` `(``int` argc`,` `char` `*`argv`[]``)` `{` body `}` | (2) | | | `/* another implementation-defined form, with int as return type */` | (3) | | | | | | | --- | --- | --- | | argc | - | Non-negative value representing the number of arguments passed to the program from the environment in which the program is run. | | argv | - | Pointer to the first element of an array of `argc + 1` pointers, of which the last one is null and the previous ones, if any, point to [null-terminated multibyte strings](../string/multibyte "cpp/string/multibyte") that represent the arguments passed to the program from the execution environment. If `argv[0]` is not a null pointer (or, equivalently, if `argc > 0`), it points to a string that represents the name used to invoke the program, or to an empty string. | | body | - | The body of the main function | The names of argc and argv are arbitrary, as well as the representation of the types of the parameters: `int main(int ac, char** av)` is equally valid. A very common implementation-defined form of `main()` has a third argument (in addition to `argc` and `argv`), of type `char**`, pointing at [an array of pointers to the *execution environment variables*](https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html). ### Explanation The `main` function is called at program startup after [initialization](initialization "cpp/language/initialization") of the non-local objects with static [storage duration](storage_duration "cpp/language/storage duration"). It is the designated entry point to a program that is executed in *hosted* environment (that is, with an operating system). The entry points to *freestanding* programs (boot loaders, OS kernels, etc) are implementation-defined. The parameters of the two-parameter form of the main function allow arbitrary multibyte character strings to be passed from the execution environment (these are typically known as *command line arguments*), the pointers `argv[1]` .. `argv[argc - 1]` point at the first characters in each of these strings. `argv[0]` (if non-null) is the pointer to the initial character of a null-terminated multibyte string that represents the name used to invoke the program itself (or an empty string `""` if this is not supported by the execution environment). The strings are modifiable, although these modifications do not propagate back to the execution environment: they can be used, for example, with `[std::strtok](../string/byte/strtok "cpp/string/byte/strtok")`. The size of the array pointed to by `argv` is at least `argc + 1`, and the last element, `argv[argc]`, is guaranteed to be a null pointer. The `main` function has several special properties: 1) It cannot be used anywhere in the program a) in particular, it cannot be called recursively b) its address cannot be taken 2) It cannot be predefined and cannot be overloaded: effectively, the name `main` in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that an entity named `main` cannot be declared with C [language linkage](language_linkage "cpp/language/language linkage") in any namespace. 3) It cannot be defined as deleted or (since C++11) declared with any language linkage, , [`constexpr`](constexpr "cpp/language/constexpr") (since C++11), [`consteval`](consteval "cpp/language/consteval") (since C++20), [`inline`](inline "cpp/language/inline"), or [`static`](static "cpp/language/static"). 4) The body of the main function does not need to contain the [return statement](return "cpp/language/return"): if control reaches the end of `main` without encountering a return statement, the effect is that of executing `return 0;`. 5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling `[std::exit](../utility/program/exit "cpp/utility/program/exit")` with the same argument as the argument of the [return](return "cpp/language/return"). (`[std::exit](../utility/program/exit "cpp/utility/program/exit")` then destroys static objects and terminates the program). | | | | --- | --- | | 6) The return type of the main function cannot be deduced (`auto main() {...` is not allowed). | (since C++14) | | | | | --- | --- | | 7) The main function cannot be a [coroutine](coroutines "cpp/language/coroutines"). | (since C++20) | ### Notes If the main function is defined with a [function-try-block](function-try-block "cpp/language/function-try-block"), the exceptions thrown by the destructors of static objects (which are destroyed by the implied `[std::exit](../utility/program/exit "cpp/utility/program/exit")`) are not caught by it. The manner in which the arguments given at the OS command line are converted into the multibyte character arrays referenced by `argv` may involve implementation-defined processing: * [Parsing C++ Command-Line Arguments](https://docs.microsoft.com/en-us/cpp/cpp/main-function-command-line-args) MSDN * [Shell Introduction](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_01) POSIX ### Example Demonstrates how to inform a program about where to find its input and where to write its results. A possible invocation: `./convert table_in.dat table_out.dat`. ``` #include <iostream> #include <iomanip> #include <cstdlib> int main(int argc, char *argv[]) { std::cout << "argc == " << argc << '\n'; for(int ndx{}; ndx != argc; ++ndx) { std::cout << "argv[" << ndx << "] == " << std::quoted(argv[ndx]) << '\n'; } std::cout << "argv[" << argc << "] == " << static_cast<void*>(argv[argc]) << '\n'; /*...*/ return argc == 3 ? EXIT_SUCCESS : EXIT_FAILURE; // optional return value } ``` Possible output: ``` argc == 3 argv[0] == "./convert" argv[1] == "table_in.dat" argv[2] == "table_out.dat" argv[3] == 0 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1003](https://cplusplus.github.io/CWG/issues/1003.html) | C++98 | for form (2), definitions whose parameter namesthat are not `argc` (1st parameter) and `argv`(2nd parameter) were not required to be supported | need to support allvalid parameter names | | [CWG 1886](https://cplusplus.github.io/CWG/issues/1886.html) | C++98 | the main function could be declared with a language linkage | prohibited | | [CWG 2479](https://cplusplus.github.io/CWG/issues/2479.html) | C++20 | the main function could be declared `consteval` | prohibited | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/main_function "c/language/main function") for `main` function | cpp static_cast conversion `static_cast` conversion ========================= Converts between types using a combination of implicit and user-defined conversions. ### Syntax | | | | | --- | --- | --- | | `static_cast` `<` new-type `>` `(` expression `)` | | | Returns a value of type new-type. ### Explanation Only the following conversions can be done with `static_cast`, except when such conversions would cast away *constness* or *volatility*. 1) If new-type is a reference to some class `D` and expression is an lvalue of its non-virtual base `B`, or new-type is a pointer to some complete class `D` and expression is a prvalue pointer to its non-virtual base `B`, `static_cast` performs a *downcast*. (This downcast is ill-formed if `B` is ambiguous, inaccessible, or virtual base (or a base of a virtual base) of `D`.) Such a downcast makes no runtime checks to ensure that the object's runtime type is actually `D`, and may only be used safely if this precondition is guaranteed by other means, such as when implementing [static polymorphism](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern#Static_polymorphism "enwiki:Curiously recurring template pattern"). Safe downcast may be done with [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast"). If the object expression refers or points to is actually a base class subobject of an object of type `D`, the result refers to the enclosing object of type `D`. Otherwise, the behavior is undefined: ``` struct B {}; struct D : B { B b; }; D d; B& br1 = d; B& br2 = d.b; static_cast<D&>(br1); // OK: lvalue denoting the original d object static_cast<D&>(br2); // UB: the b subobject is not a base class subobject ``` | | | | --- | --- | | 2) If new-type is an rvalue reference type, `static_cast` converts the value of glvalue, class prvalue, or array prvalue (until C++17)any lvalue (since C++17) expression to *xvalue* referring to the same object as the expression, or to its base sub-object (depending on new-type). If the target type is an inaccessible or ambiguous base of the type of the expression, the program is ill-formed. If the expression is a [bit-field](bit_field "cpp/language/bit field") lvalue, it is first converted to prvalue of the underlying type. This type of `static_cast` is used to implement move semantics in `std::move`. | (since C++11) | 3) If there is an [implicit conversion sequence](implicit_conversion "cpp/language/implicit conversion") from expression to new-type, or if overload resolution for a [direct initialization](direct_initialization "cpp/language/direct initialization") of an object or reference of type new-type from expression would find at least one viable function, then `static_cast<new-type>(expression)` returns the imaginary variable `Temp` initialized as if by `new-type Temp(expression);`, which may involve [implicit conversions](implicit_conversion "cpp/language/implicit conversion"), a call to the [constructor](constructor "cpp/language/constructor") of new-type or a call to a [user-defined conversion operator](cast_operator "cpp/language/cast operator"). For non-reference new-type, the result object of the `static_cast` prvalue expression is what's direct-initialized. (since C++17) 4) If new-type is the type `void` (possibly cv-qualified), `static_cast` discards the value of expression after evaluating it. 5) If a [standard conversion](implicit_conversion "cpp/language/implicit conversion") sequence from new-type to the type of expression exists, that does not include lvalue-to-rvalue, array-to-pointer, function-to-pointer, null pointer, null member pointer, function pointer, (since C++17) or boolean conversion, then `static_cast` can perform the inverse of that implicit conversion. 6) If conversion of expression to new-type involves lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversion, it can be performed explicitly by `static_cast`. | | | | | | | | --- | --- | --- | --- | --- | --- | | 7) [Scoped enumeration](enum "cpp/language/enum") type can be converted to an integer or floating-point type. | | | | --- | --- | | When the target type is `bool` (possibly cv-qualified), the result is `false` if the original value is zero and `true` for all other values. For the remaining integral types, the result is the value of the enum if it can be represented by the target type and unspecified otherwise. | (until C++20) | | The result is the same as [implicit conversion](implicit_conversion "cpp/language/implicit conversion") from the enum's underlying type to the destination type. | (since C++20) | | (since C++11) | 8) A value of integer or enumeration type can be converted to any complete [enumeration type](enum "cpp/language/enum"). * If the underlying type is not fixed, the behavior is undefined if the value of expression is out of range (the range is all values possible for the smallest bit field large enough to hold all enumerators of the target enumeration). * If the underlying type is fixed, the result is the same as [converting](implicit_conversion#Integral_conversions "cpp/language/implicit conversion") the original value first to the underlying type of the enumeration and then to the enumeration type. A value of a floating-point type can also be converted to any complete enumeration type. * The result is the same as [converting](implicit_conversion#Floating.E2.80.93integral_conversions "cpp/language/implicit conversion") the original value first to the underlying type of the enumeration, and then to the enumeration type. 9) A pointer to member of some complete class `D` can be upcast to a pointer to member of its unambiguous, accessible base class `B`. This `static_cast` makes no checks to ensure the member actually exists in the runtime type of the pointed-to object. 10) A prvalue of type pointer to `void` (possibly cv-qualified) can be converted to pointer to any object type. If the original [pointer value](pointer#Pointers "cpp/language/pointer") represents an address of a byte in memory that does not satisfy the alignment requirement of the target type, then the resulting pointer value is unspecified. Otherwise, if the original pointer value points to an object *a*, and there is an object *b* of the target type (ignoring cv-qualification) that is *pointer-interconvertible* (as defined below) with *a*, the result is a pointer to *b*. Otherwise the pointer value is unchanged. Conversion of any pointer to pointer to void and back to pointer to the original (or more cv-qualified) type preserves its original value. As with all cast expressions, the result is: | | | | --- | --- | | * an lvalue if new-type is a reference type; * an rvalue otherwise. | (until C++11) | | * an lvalue if new-type is an lvalue reference type or an rvalue reference to function type; * an xvalue if new-type is an rvalue reference to object type; * a prvalue otherwise. | (since C++11) | Two objects *a* and *b* are *pointer-interconvertible* if: * they are the same object, or * one is a union object and the other is a non-static data member of that object, or * one is a [standard-layout](data_members#Standard_layout "cpp/language/data members") class object and the other is the first non-static data member of that object or any base class subobject of that object, or * there exists an object *c* such that *a* and *c* are pointer-interconvertible, and *c* and *b* are pointer-interconvertible. ``` union U { int a; double b; } u; void* x = &u; // x's value is "pointer to u" double* y = static_cast<double*>(x); // y's value is "pointer to u.b" char* z = static_cast<char*>(x); // z's value is "pointer to u" ``` ### Notes `static_cast` may also be used to disambiguate function overloads by performing a function-to-pointer conversion to specific type, as in. ``` std::for_each(files.begin(), files.end(), static_cast<std::ostream&(*)(std::ostream&)>(std::flush)); ``` ### Keywords [`static_cast`](../keyword/static_cast "cpp/keyword/static cast"). ### Example ``` #include <vector> #include <iostream> struct B { int m = 42; const char* hello() const { return "Hello world, this is B!\n"; } }; struct D : B { const char* hello() const { return "Hello world, this is D!\n"; } }; enum class E { ONE = 1, TWO, THREE }; enum EU { ONE = 1, TWO, THREE }; int main() { // 1. static downcast D d; B& br = d; // upcast via implicit conversion std::cout << "1) " << br.hello(); D& another_d = static_cast<D&>(br); // downcast std::cout << "1) " << another_d.hello(); // 2. lvalue to xvalue std::vector<int> v0{1,2,3}; std::vector<int> v2 = static_cast<std::vector<int>&&>(v0); std::cout << "2) after move, v0.size() = " << v0.size() << '\n'; // 3. initializing conversion int n = static_cast<int>(3.14); std::cout << "3) n = " << n << '\n'; std::vector<int> v = static_cast<std::vector<int>>(10); std::cout << "3) v.size() = " << v.size() << '\n'; // 4. discarded-value expression static_cast<void>(v2.size()); // 5. inverse of implicit conversion void* nv = &n; int* ni = static_cast<int*>(nv); std::cout << "4) *ni = " << *ni << '\n'; // 6. array-to-pointer followed by upcast D a[10]; [[maybe_unused]] B* dp = static_cast<B*>(a); // 7. scoped enum to int E e = E::TWO; int two = static_cast<int>(e); std::cout << "7) " << two << '\n'; // 8. int to enum, enum to another enum E e2 = static_cast<E>(two); [[maybe_unused]] EU eu = static_cast<EU>(e2); // 9. pointer to member upcast int D::*pm = &D::m; std::cout << "9) " << br.*static_cast<int B::*>(pm) << '\n'; // 10. void* to any type void* voidp = &e; [[maybe_unused]] std::vector<int>* p = static_cast<std::vector<int>*>(voidp); } ``` Output: ``` 1) Hello world, this is B! 1) Hello world, this is D! 2) after move, v0.size() = 0 3) n = 3 3) v.size() = 10 4) *ni = 3 7) 2 9) 42 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 137](https://cplusplus.github.io/CWG/issues/137.html) | C++98 | the constness and volatility of voidpointers could be casted away | cv-qualifications cannot becasted away in such cases | | [CWG 439](https://cplusplus.github.io/CWG/issues/439.html) | C++98 | when converting a 'pointer to object' to 'pointer tovoid' then back to itself, it could only preserve itsvalue if the result type has the same cv-qualifiction | cv-qualificationmay be different | | [CWG 1094](https://cplusplus.github.io/CWG/issues/1094.html) | C++98 | the conversion from floating-point valuesto enumeration values was unspecified | specified | | [CWG 1320](https://cplusplus.github.io/CWG/issues/1320.html) | C++11 | the conversion from scoped enumerationvalues to bool was unspecified | specified | | [CWG 1447](https://cplusplus.github.io/CWG/issues/1447.html) | C++11 | the conversion from bit-fields to rvalue referenceswas unspecified (cannot bind references to bit-fields) | specified | | [CWG 1766](https://cplusplus.github.io/CWG/issues/1766.html) | C++98 | the conversion from integral or enumeration values to enumerationvalues yielded unspecified result if expression is out of range | the behavior isundefined in this case | | [CWG 1832](https://cplusplus.github.io/CWG/issues/1832.html) | C++98 | the conversion from integral or enumeration values toenumeration values allowed new-type to be incomplete | not allowed | | [CWG 2224](https://cplusplus.github.io/CWG/issues/2224.html) | C++98 | the conversion from a member of base class type toits complete object of derived class type was valid | the behavior isundefined in this case | | [CWG 2254](https://cplusplus.github.io/CWG/issues/2254.html) | C++11 | a standard-layout class object with no data memberswas pointer-interconvertible to its first base class | it is pointer-interconvertibleto any of its base classes | | [CWG 2284](https://cplusplus.github.io/CWG/issues/2284.html) | C++11 | a non-standard-layout union object and a non-static datamember of that object were not pointer-interconvertible | they are | | [CWG 2310](https://cplusplus.github.io/CWG/issues/2310.html) | C++98 | for base-to-derived pointer conversions andderived-to-base pointer-to-member conversions,the derived class type could be incomplete | must be complete | | [CWG 2338](https://cplusplus.github.io/CWG/issues/2338.html) | C++11 | the conversion to enumeration types with fixed underlying typeresulted in undefined behavior if expression is out of range | convert to the underlying typefirst (no undefined behavior) | | [CWG 2499](https://cplusplus.github.io/CWG/issues/2499.html) | C++11 | a standard-layout class might have a non-pointer-interconvertiblebase class, even though all base subobjects have the same address | it does not have | ### See also * [`const_cast`](const_cast "cpp/language/const cast") * [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") * [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") * [explicit cast](explicit_cast "cpp/language/explicit cast") * [implicit conversions](implicit_cast "cpp/language/implicit cast")
programming_docs
cpp Reference initialization Reference initialization ======================== Binds a reference to an object. ### Syntax | | | | | --- | --- | --- | | T `&` ref `=` target `;` T `&` ref `= {` arg1`,` arg2`,` ... `};` T `&` ref `(` target `);` T `&` ref `{` arg1`,` arg2`,` ... `};` | (1) | | | T `&&` ref `=` target `;` T `&&` ref `= {` arg1`,` arg2`,` ... `};` T `&&` ref `(` target `);` T `&&` ref `{` arg1`,` arg2`,` ... `};` | (2) | (since C++11) | | given R fn `(` T `&` arg `);` or R fn `(` T `&&` arg `);` (since C++11) fn `(` target `)`. fn `({` arg1`,` arg2`,` ... `});` | (3) | | | inside T `&` fn `()` or T `&&` fn `()` (since C++11) `return` target `;` | (4) | | | given T `&` ref `;` or T `&&` ref `;` (since C++11) inside the definition of Class Class`::`Class`(`...`) :` ref `(` target `) {` ... `}` | (5) | | ### Explanation A reference to `T` can be initialized with an object of type `T`, a function of type `T`, or an object implicitly convertible to `T`. Once initialized, a reference cannot be changed to refer to another object. References are initialized in the following situations: 1) When a named [lvalue reference](reference#Lvalue_references "cpp/language/reference") variable is declared with an initializer 2) When a named [rvalue reference](reference#Rvalue_references "cpp/language/reference") variable is declared with an initializer 3) In a function call expression, when the function parameter has reference type 4) In the `return` statement, when the function returns a reference type 5) When a [non-static data member](data_members "cpp/language/data members") of reference type is initialized using a [member initializer](initializer_list "cpp/language/initializer list") The effects of reference initialization are: * If the initializer is a braced-init-list ( `{` arg1`,` arg2`,` ... `}` ), rules of [list initialization](list_initialization "cpp/language/list initialization") are followed. * Otherwise, if the reference is an lvalue reference: + If target is an lvalue expression, and its type is `T` or derived from `T`, and is equally or less cv-qualified, then the reference is bound to the object identified by the lvalue or to its base class subobject. ``` double d = 2.0; double& rd = d; // rd refers to d const double& rcd = d; // rcd refers to d struct A {}; struct B : A {} b; A& ra = b; // ra refers to A subobject in b const A& rca = b; // rca refers to A subobject in b ``` * Otherwise, if the type of target is not same or derived from `T`, and target has conversion function to an lvalue whose type is either `T` or derived from `T`, equally or less cv-qualified, then the reference is bound to the object identified by the lvalue returned by the conversion function (or to its base class subobject). ``` struct A {}; struct B : A { operator int&(); }; int& ir = B(); // ir refers to the result of B::operator int& ``` * Otherwise, if the reference is lvalue reference to a non-volatile const-qualified type or rvalue reference (since C++11): + If target is a non-bit-field rvalue or a function lvalue, and its type is either `T` or derived from `T`, equally or less cv-qualified, then the reference is bound to the value of the initializer expression or to its base subobject (after [materializing a temporary](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion") if necessary) (since C++17). ``` struct A {}; struct B : A {}; extern B f(); const A& rca2 = f(); // bound to the A subobject of the B rvalue. A&& rra = f(); // same as above int i2 = 42; int&& rri = static_cast<int&&>(i2); // bound directly to i2 ``` * Otherwise, if the type of target is not same or derived from `T`, and target has conversion function to a rvalue or a function lvalue whose type is either `T` or derived from `T`, equally or less cv-qualified, then the reference is bound to the result of the conversion function or to its base class subobject (after [materializing a temporary](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion") if necessary) (since C++17). ``` struct A {}; struct B : A {}; struct X { operator B(); } x; const A& r = x; // bound to the A subobject of the result of the conversion B&& rrb = x; // bound directly to the result of the conversion ``` * Otherwise, target is implicitly converted to `T`. The reference is bound to the result of the conversion (after [materializing a temporary](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion"), and the cv-qualification of `T` is preserved even if it is a scalar type) (since C++17). If the target (or, if the conversion is done by user-defined conversion, the result of the conversion function) is of type `T` or derived from `T`, it must be equally or less cv-qualified than `T`, and, if the reference is an rvalue reference, must not be an lvalue (since C++11). ``` const std::string& rs = "abc"; // rs refers to temporary copy-initialized from char array const double& rcd2 = 2; // rcd2 refers to temporary with value 2.0 int i3 = 2; double&& rrd3 = i3; // rrd3 refers to temporary with value 2.0 ``` ### Lifetime of a temporary Whenever a reference is bound to a temporary object or to a subobject thereof, the lifetime of the temporary object is extended to match the lifetime of the reference (check [temporary object lifetime exceptions](lifetime#Temporary_object_lifetime "cpp/language/lifetime")), where the temporary object or its subobject is denoted by one of following expression: | | | | --- | --- | | * a [prvalue](value_category#prvalue "cpp/language/value category") expression of an object type, | (until C++17) | | * a [temporary materialization conversion](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion"), | (since C++17) | * a parenthesized expression `(e)`, where `e` is one of these expressions, * a [built-in subscript expression](operator_member_access#Built-in_subscript_operator "cpp/language/operator member access") of form `a[n]` or `n[a]`, where `a` is an array and is one of these expressions, * a [class member access expression](operator_member_access#Built-in_member_access_operators "cpp/language/operator member access") of form `e.m`, where `e` is one of these expressions and `m` designates a non-static data member of object type, * a [pointer-to-member operation](operator_member_access#Built-in_pointer-to-member_access_operators "cpp/language/operator member access") of form `e.*mp`, where `e` is one of these expressions and `mp` is a pointer to data member, * a [`const_cast`](const_cast "cpp/language/const cast"), [`static_cast`](static_cast "cpp/language/static cast"), [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast"), or [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") conversion without a user-defined conversion that converts one of these expressions to the glvalue refers to the object designated by the operand, or to its complete object or a subobject thereof (an [explicit cast](explicit_cast "cpp/language/explicit cast") expression is interpreted as a sequence of these casts), * a [conditional expression](operator_other#Conditional_operator "cpp/language/operator other") of form `cond ? e1 : e2` that is a glvalue, where `e1` or `e2` is one of these expressions, or * a [built-in comma expression](operator_other#Built-in_comma_operator "cpp/language/operator other") of form `x, e` that is a glvalue, where `e` is one of these expressions. There are following exceptions to this lifetime rule: * a temporary bound to a return value of a function in a `return` statement is not extended: it is destroyed immediately at the end of the return expression. Such `return` statement always returns a dangling reference. * a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference. | | | | --- | --- | | * a temporary bound to a reference in the initializer used in a new-expression exists until the end of the full expression containing that new-expression, not as long as the initialized object. If the initialized object outlives the full expression, its reference member becomes a dangling reference. | (since C++11) | | | | | --- | --- | | * a temporary bound to a reference in a reference element of an aggregate initialized using [direct-initialization](direct_initialization "cpp/language/direct initialization") syntax **(**parentheses**)** exists until the end of the full expression containing the initializer, as opposed to [list-initialization](list_initialization "cpp/language/list initialization") syntax **{**braces**}**. ``` struct A { int&& r; }; A a1{7}; // OK, lifetime is extended A a2(7); // well-formed, but dangling reference ``` | (since C++20) | In general, the lifetime of a temporary cannot be further extended by "passing it on": a second reference, initialized from the reference variable or data member to which the temporary was bound, does not affect its lifetime. ### Notes References appear without initializers only in function parameter declaration, in function return type declaration, in the declaration of a class member, and with the [`extern`](storage_duration "cpp/language/storage duration") specifier. Until the resolution of [CWG issue 1696](https://cplusplus.github.io/CWG/issues/1696.html), a temporary is permitted to bound to a reference member in a constructor [initializer list](initializer_list "cpp/language/initializer list"), and it persists only until the constructor exits, not as long as the object exists. Such initialization is ill-formed since [CWG 1696](https://cplusplus.github.io/CWG/issues/1696.html), although many compilers still support it (a notable exception is clang). ### Example ``` #include <utility> #include <sstream> struct S { int mi; const std::pair<int, int>& mp; // reference member }; void foo(int) {} struct A {}; struct B : A { int n; operator int&() { return n; } }; B bar() { return B(); } //int& bad_r; // error: no initializer extern int& ext_r; // OK int main() { // Lvalues int n = 1; int& r1 = n; // lvalue reference to the object n const int& cr(n); // reference can be more cv-qualified volatile int& cv{n}; // any initializer syntax can be used int& r2 = r1; // another lvalue reference to the object n // int& bad = cr; // error: less cv-qualified int& r3 = const_cast<int&>(cr); // const_cast is needed void (&rf)(int) = foo; // lvalue reference to function int ar[3]; int (&ra)[3] = ar; // lvalue reference to array B b; A& base_ref = b; // reference to base subobject int& converted_ref = b; // reference to the result of a conversion // Rvalues // int& bad = 1; // error: cannot bind lvalue ref to rvalue const int& cref = 1; // bound to rvalue int&& rref = 1; // bound to rvalue const A& cref2 = bar(); // reference to A subobject of B temporary A&& rref2 = bar(); // same int&& xref = static_cast<int&&>(n); // bind directly to n // int&& copy_ref = n; // error: can't bind to an lvalue double&& copy_ref = n; // bind to an rvalue temporary with value 1.0 // Restrictions on temporary lifetimes std::ostream& buf_ref = std::ostringstream() << 'a'; // the ostringstream temporary // was bound to the left operand of operator<< // but its lifetime ended at the semicolon // so buf_ref is a dangling reference S a {1, {2, 3}}; // temporary pair {2, 3} bound to the reference member // a.mp and its lifetime is extended to match // the lifetime of object a S* p = new S{1, {2, 3}}; // temporary pair {2, 3} bound to the reference // member p->mp, but its lifetime ended at the semicolon // p->mp is a dangling reference delete p; } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 391](https://cplusplus.github.io/CWG/issues/391.html) | C++98 | initialize a reference to const-qualified type with a class typervalue might create a temporary, and a constructor of that classwas required in order to copy the rvalue into that temporary | no temporary iscreated, constructoris not required | | [CWG 450](https://cplusplus.github.io/CWG/issues/450.html) | C++98 | a reference to const-qualified array could not beinitialized with a reference-compatible array rvalue | allowed | | [CWG 656](https://cplusplus.github.io/CWG/issues/656.html) | C++98 | a reference to const-qualified type initialized with a type which is notreference-compatible but has a conversion function to a reference-compatible type was bound to a temporary copied from the returnvalue (or its base class subobject) of the conversion function | bound to the returnvalue (or its base classsubobject) directly | | [CWG 1299](https://cplusplus.github.io/CWG/issues/1299.html) | C++98 | the definition of temporary was unclear | made clear | ### See also * [constructor](constructor "cpp/language/constructor") * [converting constructor](converting_constructor "cpp/language/converting constructor") * [copy assignment](copy_assignment "cpp/language/copy assignment") * [copy constructor](copy_constructor "cpp/language/copy constructor") * [`explicit`](explicit "cpp/language/explicit") * [initialization](initialization "cpp/language/initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [copy initialization](copy_initialization "cpp/language/copy initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [list initialization](list_initialization "cpp/language/list initialization") * [move assignment](move_assignment "cpp/language/move assignment") * [move constructor](move_constructor "cpp/language/move constructor") * [`new`](new "cpp/language/new") cpp Range-based for loop (since C++11) Range-based for loop (since C++11) ================================== Executes a for loop over a range. Used as a more readable equivalent to the traditional [for loop](for "cpp/language/for") operating over a range of values, such as all elements in a container. ### Syntax | | | | | --- | --- | --- | | attr(optional) `for (` init-statement(optional) range-declaration `:` range-expression `)` loop-statement. | | | | | | | | --- | --- | --- | | attr | - | any number of [attributes](attributes "cpp/language/attributes") | | init-statement | - | (since C++20) either * an [expression statement](statements "cpp/language/statements") (which may be a *null statement* "`;`") * a [simple declaration](declarations "cpp/language/declarations"), typically a declaration of a variable with initializer, but it may declare arbitrarily many variables or be a [structured binding declaration](structured_binding "cpp/language/structured binding") | | | | --- | --- | | * an [alias declaration](type_alias "cpp/language/type alias") | (since C++23) | Note that any init-statement must end with a semicolon `;`, which is why it is often described informally as an expression or a declaration followed by a semicolon. | | range-declaration | - | a [declaration](declarations "cpp/language/declarations") of a named variable, whose type is the type of the element of the sequence represented by range-expression, or a reference to that type. Often uses the [auto specifier](auto "cpp/language/auto") for automatic type deduction | | range-expression | - | any [expression](expressions "cpp/language/expressions") that represents a suitable sequence (either an array or an object for which `begin` and `end` member functions or free functions are defined, see below) or a [braced-init-list](list_initialization "cpp/language/list initialization"). | | loop-statement | - | any [statement](statements "cpp/language/statements"), typically a compound statement, which is the body of the loop | | | | | --- | --- | | range-declaration may be a [structured binding declaration](structured_binding "cpp/language/structured binding"): ``` for (auto&& [first,second] : mymap) { // use first and second } ``` | (since C++17) | ### Explanation The above syntax produces code equivalent to the following (**`__range`**, **`__begin`** and **`__end`** are for exposition only): | | | | --- | --- | | `{` `auto && __range =` range-expression `;` `for (auto __begin =` *begin-expr*`,` `__end =` *end-expr*`;` `__begin != __end; ++__begin)` `{` range-declaration `= *__begin;` loop-statement `}` `}` | (until C++17) | | `{` `auto && __range =` range-expression `;` `auto __begin =` *begin-expr* `;` `auto __end =` *end-expr* `;` `for ( ; __begin != __end; ++__begin)` `{` range-declaration `= *__begin;` loop-statement `}` `}` | (since C++17)(until C++20) | | `{` init-statement `auto && __range =` range-expression `;` `auto __begin =` *begin-expr* `;` `auto __end =` *end-expr* `;` `for ( ; __begin != __end; ++__begin)` `{` range-declaration `= *__begin;` loop-statement `}` `}` | (since C++20) | range-expression is evaluated to determine the sequence or range to iterate. Each element of the sequence, in turn, is dereferenced and is used to initialize the variable with the type and name given in range-declaration. *`begin-expr`* and *`end-expr`* are defined as follows: * If range-expression is an expression of array type, then *`begin-expr`* is `__range` and *`end-expr`* is `(__range + __bound)`, where `__bound` is the number of elements in the array (if the array has unknown size or is of an incomplete type, the program is ill-formed) * If range-expression is an expression of a class type `C` that has both a member named `begin` and a member named `end` (regardless of the type or accessibility of such member), then *`begin-expr`* is `__range.begin()` and *`end-expr`* is `__range.end()`; * Otherwise, *`begin-expr`* is `begin(__range)` and *`end-expr`* is `end(__range)`, which are found via [argument-dependent lookup](adl "cpp/language/adl") (non-ADL lookup is not performed). Just as with a traditional loop, a [break statement](break "cpp/language/break") can be used to exit the loop early and a [continue statement](continue "cpp/language/continue") can be used to restart the loop with the next element. If a name introduced in init-statement is redeclared in the outermost block of loop-statement, the program is ill-formed: ``` for (int i : { 1, 2, 3 }) int i = 1; // error: redeclaration ``` ### Temporary range expression If range-expression returns a temporary, its lifetime is extended until the end of the loop, as indicated by binding to the forwarding reference **`__range`**, but beware that the lifetime of any temporary within range-expression is *not* extended. ``` for (auto& x : foo().items()) { /* .. */ } // undefined behavior if foo() returns by value ``` | | | | --- | --- | | This problem may be worked around using init-statement: ``` for (T thing = foo(); auto& x : thing.items()) { /* ... */ } // OK ``` | (since C++20) | ### Notes If the initializer (range-expression) is a braced-init-list, \_\_range is deduced to be `std::initializer_list<>&&` It is safe, and in fact, preferable in generic code, to use deduction to forwarding reference, `for (auto&& var : sequence)`. The member interpretation is used if the range type has a member named `begin` and a member named `end`. This is done regardless of whether the member is a type, data member, function, or enumerator, and regardless of its accessibility. Thus a class like `class meow { enum { begin = 1, end = 2}; /* rest of class */ };` cannot be used with the range-based for loop even if the namespace-scope begin/end functions are present. While the variable declared in the range-declaration is usually used in the loop-statement, doing so is not required. | | | | --- | --- | | As of C++17, the types of the *`begin-expr`* and the *`end-expr`* do not have to be the same, and in fact the type of the *`end-expr`* does not have to be an iterator: it just needs to be able to be compared for inequality with one. This makes it possible to delimit a range by a predicate (e.g. "the iterator points at a null character"). | (since C++17) | When used with a (non-const) object that has copy-on-write semantics, the range-based for loop may trigger a deep copy by (implicitly) calling the non-const `begin()` member function. | | | | --- | --- | | If that is undesirable (for instance because the loop is not actually modifying the object), it can be avoided by using `[std::as\_const](../utility/as_const "cpp/utility/as const")`: ``` struct cow_string { /* ... */ }; // a copy-on-write string cow_string str = /* ... */; // for (auto x : str) { /* ... */ } // may cause deep copy for (auto x : std::as_const(str)) { /* ... */ } ``` | (since C++17) | ### Keywords [`for`](../keyword/for "cpp/keyword/for"). ### Example ``` #include <iostream> #include <vector> int main() { std::vector<int> v = {0, 1, 2, 3, 4, 5}; for (const int& i : v) // access by const reference std::cout << i << ' '; std::cout << '\n'; for (auto i : v) // access by value, the type of i is int std::cout << i << ' '; std::cout << '\n'; for (auto&& i : v) // access by forwarding reference, the type of i is int& std::cout << i << ' '; std::cout << '\n'; const auto& cv = v; for (auto&& i : cv) // access by f-d reference, the type of i is const int& std::cout << i << ' '; std::cout << '\n'; for (int n : {0, 1, 2, 3, 4, 5}) // the initializer may be a braced-init-list std::cout << n << ' '; std::cout << '\n'; int a[] = {0, 1, 2, 3, 4, 5}; for (int n : a) // the initializer may be an array std::cout << n << ' '; std::cout << '\n'; for ([[maybe_unused]] int n : a) std::cout << 1 << ' '; // the loop variable need not be used std::cout << '\n'; for (auto n = v.size(); auto i : v) // the init-statement (C++20) std::cout << --n + i << ' '; std::cout << '\n'; for (typedef decltype(v)::value_type elem_t; elem_t i : v) // typedef declaration as init-statement (C++20) std::cout << i << ' '; std::cout << '\n'; for (using elem_t = decltype(v)::value_type; elem_t i : v) // alias declaration as init-statement (C++23) std::cout << i << ' '; std::cout << '\n'; } ``` Output: ``` 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 1 1 1 1 1 1 5 5 5 5 5 5 0 1 2 3 4 5 0 1 2 3 4 5 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1442](https://cplusplus.github.io/CWG/issues/1442.html) | C++11 | it was unspecified whether the lookup of non-member`begin` and `end` includes usual unqualified lookup | no usual unqualified lookup | | [CWG 2220](https://cplusplus.github.io/CWG/issues/2220.html) | C++11 | the names introduced in init-statement could be redeclared | the program is ill-formed in this case | | [P0962R1](https://wg21.link/P0962R1) | C++11 | member interpretation was used ifeither member `begin` and `end` is present | only used if both are present | ### See also | | | | --- | --- | | [for\_each](../algorithm/for_each "cpp/algorithm/for each") | applies a function to a range of elements (function template) |
programming_docs
cpp alignof operator (since C++11) alignof operator (since C++11) ============================== Queries alignment requirements of a type. ### Syntax | | | | | --- | --- | --- | | `alignof(` type-id `)` | | | Returns a value of type `[std::size\_t](../types/size_t "cpp/types/size t")`. ### Explanation Returns [the alignment](object#Alignment "cpp/language/object"), in bytes, required for any instance of the type indicated by [type-id](type#Type_naming "cpp/language/type"), which is either [complete](type#Incomplete_type "cpp/language/type") object type, an array type whose element type is complete, or a reference type to one of those types. If the type is reference type, the operator returns the alignment of referenced type; if the type is array type, alignment requirement of the element type is returned. ### Keywords [`alignof`](../keyword/alignof "cpp/keyword/alignof"). ### Notes See [alignment](object#Alignment "cpp/language/object") for the meaning and properties of the value returned by `alignof`. ### Example ``` #include <iostream> struct Foo { int i; float f; char c; }; // Note: `alignas(alignof(long double))` below can be simplified to simply // `alignas(long double)` if desired. struct alignas(alignof(long double)) Foo2 { // put your definition here }; struct Empty {}; struct alignas(64) Empty64 {}; int main() { std::cout << "Alignment of" "\n" "- char : " << alignof(char) << "\n" "- pointer : " << alignof(int*) << "\n" "- class Foo : " << alignof(Foo) << "\n" "- class Foo2 : " << alignof(Foo2) << "\n" "- empty class : " << alignof(Empty) << "\n" "- empty class\n" " with alignas(64): " << alignof(Empty64) << "\n"; } ``` Possible output: ``` Alignment of - char : 1 - pointer : 8 - class Foo : 4 - class Foo2 : 16 - empty class : 1 - empty class with alignas(64): 64 ``` ### References * C++11 standard (ISO/IEC 14882:2011): + 5.3.6 Alignof [expr.alignof] * C++14 standard (ISO/IEC 14882:2014): + 5.3.6 Alignof [expr.alignof] * C++17 standard (ISO/IEC 14882:2017): + 8.3.6 Alignof [expr.alignof] * C++20 standard (ISO/IEC 14882:2020): + 7.6.2.5 Alignof [expr.alignof] * C++23 standard (ISO/IEC 14882:2023): + 7.6.2.6 Alignof [expr.alignof] ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1305](https://cplusplus.github.io/CWG/issues/1305.html) | C++11 | type-id could not represent a reference to an arraywith an unknown bound but a complete element type | allowed | ### See also | | | | --- | --- | | [alignment requirement](object#Alignment "cpp/language/object") | restricts the addresses at which an object may be allocated | | [`alignas` specifier](alignas "cpp/language/alignas")(C++11) | specifies that the storage for the variable should be aligned by specific amount | | [alignment\_of](../types/alignment_of "cpp/types/alignment of") (C++11) | obtains the type's alignment requirements (class template) | | [C documentation](https://en.cppreference.com/w/c/language/_Alignof "c/language/ Alignof") for `_Alignof` | cpp Character sets and encodings Character sets and encodings ============================ ### Current character sets (since C++23) #### Translation character set The *translation character set* consists of the following elements: * each character named by [ISO/IEC 10646](https://www.iso.org/standard/76835.html), as identified by its unique UCS scalar value, and * a distinct character for each UCS scalar value where no named character is assigned. #### Basic character set The *basic character set* is a subset of the translation character set, consisting of the following 96 characters: | `Code unit` | `Character` | `Glyph` | | --- | --- | --- | | U+0009 | Character tabulation | | | U+000B | Line tabulation | | | U+000C | Form feed (FF) | | | U+0020 | Space | | | U+000A | Line feed (LF) | new-line | | U+0021 | Exclamation mark | `!` | | U+0022 | Quotation mark | `"` | | U+0023 | Number sign | `#` | | U+0025 | Percent sign | `%` | | U+0026 | Ampersand | `&` | | U+0027 | Apostrophe | `'` | | U+0028 | Left parenthesis | `(` | | U+0029 | Right parenthesis | `)` | | U+002A | Asterisk | `*` | | U+002B | Plus sign | `+` | | U+002C | Comma | `,` | | U+002D | Hyphen-minus | `-` | | U+002E | Full stop | `.` | | U+002F | Solidus | `/` | | U+0030 .. U+0039 | Digit zero .. nine | `0 1 2 3 4 5 6 7 8 9` | | U+003A | Colon | `:` | | U+003B | Semicolon | `;` | | U+003C | Less-than sign | `<` | | U+003D | Equals sign | `=` | | U+003E | Greater-than sign | `>` | | U+003F | Question mark | `?` | | U+0041 .. U+005A | Latin capital letter A .. Z | `A B C D E F G H I J K L M **N O P Q R S T U V W X Y Z**.` | | U+005B | Left square bracket | `[` | | U+005C | Reverse solidus | `\` | | U+005D | Right square bracket | `]` | | U+005E | Circumflex accent | `^` | | U+005F | Low line | `_` | | U+0061 .. U+007A | Latin small letter a .. z | `a b c d e f g h i j k l m **n o p q r s t u v w x y z**.` | | U+007B | Left curly bracket | `{` | | U+007C | Vertical line | `|` | | U+007D | Right curly bracket | `}` | | U+007E | Tilde | `~` | #### Basic literal character set The *basic literal character set* consists of all characters of the basic character set, plus the following control characters: | `Code unit` | `Character` | | --- | --- | | U+0000 | Null | | U+0007 | Bell | | U+0008 | Backspace | | U+000D | Carriage return (CR) | #### Execution character set The execution character set and the execution wide-character set are supersets of the basic literal character set. The encodings of the execution character sets and the sets of additional elements (if any) are locale-specific. Each element of execution wide-character set must be representable as a distinct `wchar_t` code unit. #### Code unit and literal encoding A *code unit* is an integer value of character type. Characters in a [character literal](character_literal "cpp/language/character literal") other than a multicharacter or non-encodable character literal or in a [string literal](string_literal "cpp/language/string literal") are encoded as a sequence of one or more code units, as determined by the encoding prefix; this is termed the respective *literal encoding*. A literal encoding or a locale-specific encoding of one of the execution character sets encodes each element of the basic literal character set as a single code unit with non-negative value, distinct from the code unit for any other such element. A character not in the basic literal character set can be encoded with more than one code unit; the value of such a code unit can be the same as that of a code unit for an element of the basic literal character set. The encodings of the execution character sets can be unrelated to any literal encoding. The ordinary literal encoding is the encoding applied to an ordinary character or string literal. The wide literal encoding is the encoding applied to a wide character or string literal. The U+0000 NULL character is encoded as the value 0. No other element of the translation character set is encoded with a code unit of value 0. The code unit value of each decimal digit character after the digit 0 (U+0030) shall be one greater than the value of the previous. The ordinary and wide literal encodings are otherwise implementation-defined. For a UTF-8, UTF-16, or UTF-32 literal, the UCS scalar value corresponding to each character of the translation character set is encoded as specified in ISO/IEC 10646 for the respective UCS encoding form. ### Pre-C++23 character sets (until C++23) #### Basic source character set The *basic source character set* consists of 96 characters: * the space character, * the control characters representing + horizontal tab, + vertical tab, + form feed, + and new-line, * plus the following 91 graphical characters: | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `a` | `b` | `c` | `d` | `e` | `f` | `g` | `h` | `i` | `j` | `k` | `l` | `m` | `n` | `o` | `p` | `q` | `r` | `s` | `t` | `u` | `v` | `w` | `x` | `y` | `z` | | `A` | `B` | `C` | `D` | `E` | `F` | `G` | `H` | `I` | `J` | `K` | `L` | `M` | `N` | `O` | `P` | `Q` | `R` | `S` | `T` | `U` | `V` | `W` | `X` | `Y` | `Z` | | `0` | `1` | `2` | `3` | `4` | `5` | `6` | `7` | `8` | `9` | | `_` | `{` | } | `[` | `]` | `#` | `(` | `)` | `<` | `>` | `%` | `:` | `;` | `.` | `?` | `*` | `+` | `-` | `/` | `^` | `&` | `|` | `~` | `!` | `=` | `,` | `\` | `"` | `’` | The glyphs for the members of the basic source character set are intended to identify characters from the subset of ISO/IEC 10646 which corresponds to the ASCII character set. However, because the mapping from source file characters to the source character set (described in [translation phase 1](translation_phases#Phase1 "cpp/language/translation phases")) is specified as implementation-defined, an implementation is required to document how the basic source characters are represented in source files. #### Basic execution character set The *basic execution character set* and the *basic execution wide-character set* shall each contain all the members of the basic source character set, plus control characters representing alert, backspace, and carriage return, plus a null character (respectively, null wide character), whose value is 0. For each basic execution character set, the values of the members shall be non-negative and distinct from one another. In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous. #### Execution character set (Old definition) The execution character set and the execution wide-character set are implementation-defined supersets of the basic execution character set and the basic execution wide-character set, respectively. The values of the members of the execution character sets and the sets of additional members are locale-specific. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 788](https://cplusplus.github.io/CWG/issues/788.html) | C++98 | the values of the members of the execution character setswere implementation-defined, but were not locale-specific | they are locale-specific | | [CWG 1796](https://cplusplus.github.io/CWG/issues/1796.html) | C++98 | the representation of the null (wide) character inbasic execution (wide-)character set had all zero bits | only required value to be zero | ### See also | | | --- | | [ASCII chart](ascii "cpp/language/ascii") | | [C documentation](https://en.cppreference.com/w/c/language/charset "c/language/charset") for Character sets | cpp Namespaces Namespaces ========== Namespaces provide a method for preventing name conflicts in large projects. Symbols declared inside a namespace block are placed in a named scope that prevents them from being mistaken for identically-named symbols in other scopes. Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope. ### Syntax | | | | | --- | --- | --- | | `namespace` ns-name `{` declarations `}` | (1) | | | `inline` `namespace` ns-name `{` declarations `}` | (2) | (since C++11) | | `namespace` `{` declarations `}` | (3) | | | ns-name `::` member-name | (4) | | | `using` `namespace` ns-name `;` | (5) | | | `using` ns-name `::` member-name `;` | (6) | | | `namespace` name `=` qualified-namespace `;` | (7) | | | `namespace` ns-name `::` member-name `{` declarations `}` | (8) | (since C++17) | | `namespace` ns-name `::` `inline` member-name `{` declarations `}` | (9) | (since C++20) | 1) [Named namespace definition](#Namespaces) for the namespace ns-name. 2) [Inline namespace definition](#Inline_namespaces) for the namespace ns-name. Declarations inside ns-name will be visible in its enclosing namespace. 3) [Unnamed namespace definition](#Unnamed_namespaces). Its members have potential scope from their point of declaration to the end of the translation unit, and have [internal linkage](storage_duration "cpp/language/storage duration"). 4) Namespace names (along with class names) can appear on the left hand side of the scope resolution operator, as part of [qualified name lookup](lookup "cpp/language/lookup"). 5) [using-directive](#Using-directives): From the point of view of unqualified [name lookup](lookup "cpp/language/lookup") of any name after a using-directive and until the end of the scope in which it appears, every name from ns-name is visible as if it were declared in the nearest enclosing namespace which contains both the using-directive and ns-name. 6) [using-declaration](#Using-declarations): makes the symbol member-name from the namespace ns-name accessible for [unqualified lookup](lookup "cpp/language/lookup") as if declared in the same class scope, block scope, or namespace as where this using-declaration appears. 7) namespace-alias-definition: makes name a synonym for another namespace: see [namespace alias](namespace_alias "cpp/language/namespace alias") 8) nested namespace definition: `namespace A::B::C { ... }` is equivalent to `namespace A { namespace B { namespace C { ... } } }`. 9) nested inline namespace definition: `namespace A::B::inline C { ... }` is equivalent to `namespace A::B { inline namespace C { ... } }`. `inline` may appear in front of every namespace name except the first: `namespace A::inline B::C {}` is equivalent to `namespace A { inline namespace B { namespace C {} } }`. ### Explanation #### Namespaces | | | | | --- | --- | --- | | `inline`(optional) `namespace` attr(optional) identifier `{` namespace-body `}` | | | | | | | | --- | --- | --- | | `inline` | - | (since C++11) if present, makes this an inline namespace (see below). Cannot appear on the *extension-namespace-definition* if the *original-namespace-definition* did not use `inline` | | attr | - | (since C++17) optional sequence of any number of [attributes](attributes "cpp/language/attributes") | | identifier | - | either * a previously unused identifier, in which case this is *original-namespace-definition*; * the name of a namespace, in which case this is *extension-namespace-definition*; | | | | --- | --- | | * a sequence of enclosing namespace specifiers separated by `::`, ending with identifier, in which case this is a *nested-namespace-definition* | (since C++17) | | | namespace-body | - | possibly empty sequence of [declarations](declarations "cpp/language/declarations") of any kind (including class and function definitions as well as nested namespaces) | Namespace definitions are only allowed at namespace scope, including the global scope. To reopen an existing namespace (formally, to be an *extension-namespace-definition*), the lookup for the identifier used in the namespace definition must resolve to a namespace name (not a namespace alias), that was declared as a member of the enclosing namespace or of an inline namespace within an enclosing namespace. The namespace-body defines a [namespace scope](scope "cpp/language/scope"), which affects [name lookup](lookup "cpp/language/lookup"). All names introduced by the declarations that appear within namespace-body (including nested namespace definitions) become members of the namespace identifier, whether this namespace definition is the original namespace definition (which introduced identifier), or an extension namespace definition (which "reopened" the already defined namespace). A namespace member that was declared within a namespace body may be defined or redeclared outside of it using explicit qualification. ``` namespace Q { namespace V // V is a member of Q, and is fully defined within Q { // namespace Q::V { // C++17 alternative to the lines above class C { void m(); }; // C is a member of V and is fully defined within V // C::m is only declared void f(); // f is a member of V, but is only declared here } void V::f() // definition of V's member f outside of V // f's enclosing namespaces are still the global namespace, Q, and Q::V { extern void h(); // This declares ::Q::V::h } void V::C::m() // definition of V::C::m outside of the namespace (and the class body) // enclosing namespaces are the global namespace, Q, and Q::V {} } ``` Out-of-namespace definitions and redeclarations are only allowed. * after the point of declaration, * at namespace scope, and * in namespaces that enclose the original namespace (including the global namespace). | | | | --- | --- | | Also, they must use qualified-id syntax. | (since C++14) | ``` namespace Q { namespace V // original-namespace-definition for V { void f(); // declaration of Q::V::f } void V::f() {} // OK void V::g() {} // Error: g() is not yet a member of V namespace V // extension-namespace-definition for V { void g(); // declaration of Q::V::g } } namespace R // not an enclosing namespace for Q { void Q::V::g() {} // Error: cannot define Q::V::g inside R } void Q::V::g() {} // OK: global namespace encloses Q ``` Names introduced by [friend](friend "cpp/language/friend") declarations within a non-local class X become members of the innermost enclosing namespace of X, but they do not become visible to ordinary [name lookup](lookup "cpp/language/lookup") (neither [unqualified](unqualified_lookup "cpp/language/unqualified lookup") nor [qualified](qualified_lookup "cpp/language/qualified lookup")) unless a matching declaration is provided at namespace scope, either before or after the class definition. Such name may be found through [ADL](adl "cpp/language/adl") which considers both namespaces and classes. Only the innermost enclosing namespace is considered by such friend declaration when deciding whether the name would conflict with a previously declared name. ``` void h(int); namespace A { class X { friend void f(X); // A::f is a friend class Y { friend void g(); // A::g is a friend friend void h(int); // A::h is a friend, no conflict with ::h }; }; // A::f, A::g and A::h are not visible at namespace scope // even though they are members of the namespace A X x; void g() // definition of A::g { f(x); // A::X::f is found through ADL } void f(X) {} // definition of A::f void h(int) {} // definition of A::h // A::f, A::g and A::h are now visible at namespace scope // and they are also friends of A::X and A::X::Y } ``` | | | | --- | --- | | Inline namespaces An inline namespace is a namespace that uses the optional keyword `inline` in its *original-namespace-definition*. Members of an inline namespace are treated as if they are members of the enclosing namespace in many situations (listed below). This property is transitive: if a namespace N contains an inline namespace M, which in turn contains an inline namespace O, then the members of O can be used as though they were members of M or N.* A *using-directive* that names the inline namespace is implicitly inserted in the enclosing namespace (similar to the implicit using-directive for the unnamed namespace) * In [argument-dependent lookup](adl "cpp/language/adl"), when a namespace is added to the set of associated namespaces, its inline namespaces are added as well, and if an inline namespace is added to the list of associated namespaces, its enclosing namespace is added as well. * Each member of an inline namespace can be partially specialized, explicitly instantiated, or explicitly specialized as if it were a member of the enclosing namespace. * Qualified [name lookup](lookup "cpp/language/lookup") that examines the enclosing namespace will include the names from the inline namespaces even if the same name is present in the enclosing namespace. ``` // in C++14, std::literals and its member namespaces are inline { using namespace std::string_literals; // makes visible operator""s // from std::literals::string_literals auto str = "abc"s; } { using namespace std::literals; // makes visible both // std::literals::string_literals::operator""s // and std::literals::chrono_literals::operator""s auto str = "abc"s; auto min = 60s; } { using std::operator""s; // makes both std::literals::string_literals::operator""s // and std::literals::chrono_literals::operator""s visible auto str = "abc"s; auto min = 60s; } ``` Note: the rule about specializations allows library versioning: different implementations of a library template may be defined in different inline namespaces, while still allowing the user to extend the parent namespace with an explicit specialization of the primary template: ``` namespace Lib { inline namespace Lib_1 { template <typename T> class A; } template <typename T> void g(T) { /* ... */ } } /* ... */ struct MyClass { /* ... */ }; namespace Lib { template<> class A<MyClass> { /* ... */ }; } int main() { Lib::A<MyClass> a; g(a); // ok, Lib is an associated namespace of A } ``` | (since C++11) | #### Unnamed namespaces The *unnamed-namespace-definition* is a namespace definition of the form. | | | | | --- | --- | --- | | `inline`(optional) `namespace` attr(optional) `{` namespace-body `}` | | | | | | | | --- | --- | --- | | `inline` | - | (since C++11) if present, makes this an inline namespace | | attr | - | (since C++17) optional sequence of any number of [attributes](attributes "cpp/language/attributes") | This definition is treated as a definition of a namespace with unique name and a *using-directive* in the current scope that nominates this unnamed namespace (Note: implicitly added using directive makes namespace available for the [qualified name lookup](qualified_lookup "cpp/language/qualified lookup") and [unqualified name lookup](unqualified_lookup "cpp/language/unqualified lookup"), but not for the [argument-dependent lookup](adl "cpp/language/adl")). The unique name is unique over the entire program, but within a translation unit each unnamed namespace definition maps to the same unique name: multiple unnamed namespace definitions in the same scope denote the same unnamed namespace. ``` namespace { int i; // defines ::(unique)::i } void f() { i++; // increments ::(unique)::i } namespace A { namespace { int i; // A::(unique)::i int j; // A::(unique)::j } void g() { i++; } // A::(unique)::i++ } using namespace A; // introduces all names from A into global namespace void h() { i++; // error: ::(unique)::i and ::A::(unique)::i are both in scope A::i++; // ok, increments ::A::(unique)::i j++; // ok, increments ::A::(unique)::j } ``` | | | | --- | --- | | Even though names in an unnamed namespace may be declared with external linkage, they are never accessible from other translation units because their namespace name is unique. | (until C++11) | | Unnamed namespaces as well as all namespaces declared directly or indirectly within an unnamed namespace have [internal linkage](storage_duration#Linkage "cpp/language/storage duration"), which means that any name that is declared within an unnamed namespace has internal linkage. | (since C++11) | #### Using-declarations Introduces a name that is defined elsewhere into the declarative region where this using-declaration appears. | | | | | --- | --- | --- | | `using` `typename`(optional) nested-name-specifier unqualified-id `;` | | (until C++17) | | `using` declarator-list `;` | | (since C++17) | | | | | | --- | --- | --- | | `typename` | - | the keyword `typename` may be used as necessary to resolve [dependent names](dependent_name "cpp/language/dependent name"), when the using-declaration introduces a member type from a base class into a class template | | nested-name-specifier | - | a sequence of names and scope resolution operators `::`, ending with a scope resolution operator. A single `::` refers to the global namespace. | | unqualified-id | - | an [id-expression](identifiers "cpp/language/identifiers") | | declarator-list | - | comma-separated list of one or more declarators of the form `typename`(optional) nested-name-specifier unqualified-id. A declarator may be followed by an ellipsis to indicate [pack expansion](parameter_pack "cpp/language/parameter pack"), although that form is only meaningful in [derived class definitions](using_declaration "cpp/language/using declaration") | Using-declarations can be used to introduce namespace members into other namespaces and block scopes, or to introduce base class members into derived class definitions, or to introduce [enumerators](enum "cpp/language/enum") into namespaces, block, and class scopes (since C++20). | | | | --- | --- | | A using-declaration with more than one using-declarator is equivalent to a corresponding sequence of using-declarations with one using-declarator. | (since C++17) | For the use in derived class definitions, see [using declaration](using_declaration "cpp/language/using declaration"). Names introduced into a namespace scope by a using-declaration can be used just like any other names, including qualified lookup from other scopes: ``` void f(); namespace A { void g(); } namespace X { using ::f; // global f is now visible as ::X::f using A::g; // A::g is now visible as ::X::g using A::g, A::g; // (C++17) OK: double declaration allowed at namespace scope } void h() { X::f(); // calls ::f X::g(); // calls A::g } ``` If, after the using-declaration was used to take a member from a namespace, the namespace is extended and additional declarations for the same name are introduced, those additional declarations do not become visible through the using-declaration (in contrast with using-directive). One exception is when a using-declaration names a class template: partial specializations introduced later are effectively visible, because their [lookup](lookup "cpp/language/lookup") proceeds through the primary template. ``` namespace A { void f(int); } using A::f; // ::f is now a synonym for A::f(int) namespace A // namespace extension { void f(char); // does not change what ::f means } void foo() { f('a'); // calls f(int), even though f(char) exists. } void bar() { using A::f; // this f is a synonym for both A::f(int) and A::f(char) f('a'); // calls f(char) } ``` Using-declarations cannot name [template-id](templates#template-id "cpp/language/templates"), or namespace, or a scoped enumerator (until C++20). Each declarator in a using-declaration introduces one and only one name, for example using-declaration for an [enumeration](enum "cpp/language/enum") does not introduce any of its enumerators. All restrictions on regular declarations of the same names, hiding, and overloading rules apply to using-declarations: ``` namespace A { int x; } namespace B { int i; struct g {}; struct x {}; void f(int); void f(double); void g(char); // OK: function name g hides struct g } void func() { int i; using B::i; // error: i declared twice void f(char); using B::f; // OK: f(char), f(int), f(double) are overloads f(3.5); // calls B::f(double) using B::g; g('a'); // calls B::g(char) struct g g1; // declares g1 to have type struct B::g using B::x; using A::x; // OK: hides struct B::x x = 99; // assigns to A::x struct x x1; // declares x1 to have type struct B::x } ``` If a function was introduced by a using-declaration, declaring a function with the same name and parameter list is ill-formed (unless the declaration is for the same function). If a function template was introduced by a using-declaration, declaring a function template with the same name, parameter type list, return type, and template parameter list is ill-formed. Two using-declarations can introduce functions with the same name and parameter list, but if a call to that function is attempted, the program is ill-formed. ``` namespace B { void f(int); void f(double); } namespace C { void f(int); void f(double); void f(char); } void h() { using B::f; // introduces B::f(int), B::f(double) using C::f; // introduces C::f(int), C::f(double), and C::f(char) f('h'); // calls C::f(char) f(1); // error: B::f(int) or C::f(int)? void f(int); // error: f(int) conflicts with C::f(int) and B::f(int) } ``` If an entity is declared, but not defined in some inner namespace, and then declared through using-declaration in the outer namespace, and then a definition appears in the outer namespace with the same unqualified name, that definition is a member of the outer namespace and conflicts with the using-declration: ``` namespace X { namespace M { void g(); // declares, but doesn't define X::M::g() } using M::g; void g(); // Error: attempt to declare X::g which conflicts with X::M::g() } ``` More generally, a declaration that appears in any namespace scope and introduces a name using an unqualified identifier always introduces a member into the namespace it's in and not to any other namespace. The exceptions are explicit instantiations and explicit specializations of a primary template that is defined in an inline namespace: because they do not introduce a new name, they may use unqualified-id in an enclosing namespace. #### Using-directives A *using-directive* is a [block-declaration](declarations "cpp/language/declarations") with the following syntax: | | | | | --- | --- | --- | | attr(optional) `using` `namespace` nested-name-specifier(optional) namespace-name `;` | (1) | | | | | | | --- | --- | --- | | attr | - | (since C++11) any number of [attributes](attributes "cpp/language/attributes") that apply to this using-directive | | nested-name-specifier | - | a sequence of names and scope resolution operators `::`, ending with a scope resolution operator. A single `::` refers to the global namespace. When looking up the names in this sequence, [lookup](lookup "cpp/language/lookup") considers namespace declarations only | | namespace-name | - | a name of a namespace. When looking up this name, [lookup](lookup "cpp/language/lookup") considers namespace declarations only | Using-directives are allowed only in namespace [scope](scope "cpp/language/scope") and in block scope. From the point of view of [unqualified name lookup](unqualified_lookup "cpp/language/unqualified lookup") of any name after a using-directive and until the end of the scope in which it appears, every name from namespace-name is visible as if it were declared in the nearest enclosing namespace which contains both the using-directive and namespace-name. Using-directive does not add any names to the declarative region in which it appears (unlike the using-declaration), and thus does not prevent identical names from being declared. Using-directives are transitive for the purposes of [unqualified lookup](unqualified_lookup "cpp/language/unqualified lookup"): if a scope contains a using-directive that nominates a namespace-name, which itself contains using-directive for some namespace-name-2, the effect is as if the using directives from the second namespace appear within the first. The order in which these transitive namespaces occur does not influence name lookup. ``` namespace A { int i; } namespace B { int i; int j; namespace C { namespace D { using namespace A; // all names from A injected into global namespace int j; int k; int a = i; // i is B::i, because A::i is hidden by B::i } using namespace D; // names from D are injected into C // names from A are injected into global namespace int k = 89; // OK to declare name identical to one introduced by a using int l = k; // ambiguous: C::k or D::k int m = i; // ok: B::i hides A::i int n = j; // ok: D::j hides B::j } } ``` If, after a using-directive was used to nominate some namespace, the namespace is extended and additional members and/or using-directives are added to it, those additional members and the additional namespaces are visible through the using-directive (in contrast with using-declaration). ``` namespace D { int d1; void f(char); } using namespace D; // introduces D::d1, D::f, D::d2, D::f, // E::e, and E::f into global namespace! int d1; // OK: no conflict with D::d1 when declaring namespace E { int e; void f(int); } namespace D // namespace extension { int d2; using namespace E; // transitive using-directive void f(int); } void f() { d1++; // error: ambiguous ::d1 or D::d1? ::d1++; // OK D::d1++; // OK d2++; // OK, d2 is D::d2 e++; // OK: e is E::e due to transitive using f(1); // error: ambiguous: D::f(int) or E::f(int)? f('a'); // OK: the only f(char) is D::f(char) } ``` ### Notes The using-directive `using namespace std;` at any namespace scope introduces every name from the namespace `std` into the global namespace (since the global namespace is the nearest namespace that contains both `std` and any user-declared namespace), which may lead to undesirable name collisions. This, and other using directives are generally considered bad practice at file scope of a header file ([SF.7: Don’t write using namespace at global scope in a header file](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rs-using-directive)). ### Example This example shows how to use a namespace to create a class that already has been named in the `std` namespace. ``` #include <vector> namespace vec { template<typename T> class vector { // ... }; } // of vec int main() { std::vector<int> v1; // Standard vector. vec::vector<int> v2; // User defined vector. v1 = v2; // Error: v1 and v2 are different object's type. { using namespace std; vector<int> v3; // Same as std::vector v1 = v3; // OK } { using vec::vector; vector<int> v4; // Same as vec::vector v2 = v4; // OK } } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 101](https://cplusplus.github.io/CWG/issues/101.html) | C++98 | the program is ill-formed if a function declaration in namespacescope or block scope and a function introduced by ausing-declaration declare the same function (no ambiguity) | allowed | | [CWG 373](https://cplusplus.github.io/CWG/issues/373.html) | C++98 | lookup only considered namespace declarations only forthe last name in the operand of a using-directive (which issub-optimal, becuase classes cannot contain namespaces) | the lookup restrictionapplies to all names in theoperands of using-directives | | [CWG 460](https://cplusplus.github.io/CWG/issues/460.html) | C++98 | a using-declaration could name a namespace | prohibited | | [CWG 565](https://cplusplus.github.io/CWG/issues/565.html) | C++98 | a using-declaration cannot introduce a functionidentical to another function in the same scope, butthe restriction was not applied to function templates | apply the same restrictionto function templates as well | | [CWG 986](https://cplusplus.github.io/CWG/issues/986.html) | C++98 | using-directive was transitive for qualified lookup | only transitive for unqualified lookup | | [CWG 987](https://cplusplus.github.io/CWG/issues/987.html) | C++98 | entities declared in a nested namespace wasalso members of the enclosing namespace | nested scopes excluded | | [CWG 1021](https://cplusplus.github.io/CWG/issues/1021.html) | C++98 | it was unclear whether an entity whose definitionis introduced to a namespace via using-declarationis considered to be defined in that namespace | not defined in that namespace | | [CWG 1838](https://cplusplus.github.io/CWG/issues/1838.html) | C++98 | unqualified definition in an outer namespacecould define an entity declared, but not defined inanother namespace and pulled in by a using | unqualified definitionalways refers toits namespace | | [CWG 2155](https://cplusplus.github.io/CWG/issues/2155.html) | C++98 | the resolution of [CWG issue 1838](https://cplusplus.github.io/CWG/issues/1838.html) was notapplied to class and enumeration declarations | applied | ### See also | | | | --- | --- | | [namespace alias](namespace_alias "cpp/language/namespace alias") | creates an alias of an existing namespace |
programming_docs
cpp Constructors and member initializer lists Constructors and member initializer lists ========================================= Constructor is a special non-static [member function](member_functions "cpp/language/member functions") of a class that is used to initialize objects of its class type. In the definition of a constructor of a class, *member initializer list* specifies the initializers for direct and virtual bases and non-static data members. (Not to be confused with `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")`.). | | | | --- | --- | | A constructor must not be a [coroutine](coroutines "cpp/language/coroutines"). | (since C++20) | ### Syntax Constructors are declared using member [function declarators](function "cpp/language/function") of the following form: | | | | | --- | --- | --- | | class-name `(` parameter-list(optional) `)` except-spec(optional) attr(optional) | (1) | | Where class-name must name the current class (or current instantiation of a class template), or, when declared at namespace scope or in a friend declaration, it must be a qualified class name. The only specifiers allowed in the decl-specifier-seq of a constructor declaration are [`friend`](friend "cpp/language/friend"), [`inline`](inline "cpp/language/inline"), [`constexpr`](constexpr "cpp/language/constexpr") (since C++11), [`consteval`](consteval "cpp/language/consteval") (since C++20), and [`explicit`](explicit "cpp/language/explicit") (in particular, no return type is allowed). Note that [cv- and ref-qualifiers](member_functions "cpp/language/member functions") are not allowed either: const and volatile semantics of an object under construction don't kick in until the most-derived constructor completes. The body of a [function definition](function "cpp/language/function") of any constructor, before the opening brace of the compound statement, may include the *member initializer list*, whose syntax is the colon character `:`, followed by the comma-separated list of one or more member-initializers, each of which has the following syntax: | | | | | --- | --- | --- | | class-or-identifier `(` expression-list(optional) `)` | (1) | | | class-or-identifier braced-init-list | (2) | (since C++11) | | parameter-pack `...` | (3) | (since C++11) | 1) Initializes the base or member named by class-or-identifier using [direct-initialization](direct_initialization "cpp/language/direct initialization") or, if expression-list is empty, [value-initialization](value_initialization "cpp/language/value initialization") 2) Initializes the base or member named by class-or-identifier using [list-initialization](list_initialization "cpp/language/list initialization") (which becomes [value-initialization](value_initialization "cpp/language/value initialization") if the list is empty and [aggregate-initialization](aggregate_initialization "cpp/language/aggregate initialization") when initializing an aggregate) 3) Initializes multiple bases using a [pack expansion](parameter_pack#Base_specifiers_and_member_initializer_lists "cpp/language/parameter pack") | | | | | --- | --- | --- | | class-or-identifier | - | any identifier that names a non-static data member or any type name which names either the class itself (for delegating constructors) or a direct or virtual base. | | expression-list | - | possibly empty, comma-separated list of the arguments to pass to the constructor of the base or member | | braced-init-list | - | brace-enclosed list of comma-separated initializers and nested braced-init-lists | | parameter-pack | - | name of a variadic template [parameter pack](parameter_pack#Base_specifiers_and_member_initializer_lists "cpp/language/parameter pack") | ``` struct S { int n; S(int); // constructor declaration S() : n(7) {} // constructor definition: // ": n(7)" is the initializer list // ": n(7) {}" is the function body }; S::S(int x) : n{x} {} // constructor definition: ": n{x}" is the initializer list int main() { S s; // calls S::S() S s2(10); // calls S::S(int) } ``` ### Explanation Constructors have no names and cannot be called directly. They are invoked when [initialization](initialization "cpp/language/initialization") takes place, and they are selected according to the rules of initialization. The constructors without `explicit` specifier are [converting constructors](converting_constructor "cpp/language/converting constructor"). The constructors with a `constexpr` specifier make their type a [LiteralType](../named_req/literaltype "cpp/named req/LiteralType"). Constructors that may be called without any argument are [default constructors](default_constructor "cpp/language/default constructor"). Constructors that take another object of the same type as the argument are [copy constructors](copy_constructor "cpp/language/copy constructor") and [move constructors](move_constructor "cpp/language/move constructor"). Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. Member initializer list is the place where non-default initialization of these objects can be specified. For bases and non-static data members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified. No initialization is performed for [anonymous unions](union#Anonymous_unions "cpp/language/union") or [variant members](union#Union-like_class "cpp/language/union") that do not have a member initializer. The initializers where class-or-identifier names a [virtual base class](derived_class "cpp/language/derived class") are ignored during construction of any class that is not the most derived class of the object that's being constructed. Names that appear in expression-list or brace-init-list are evaluated in scope of the constructor: ``` class X { int a, b, i, j; public: const int& r; X(int i) : r(a) // initializes X::r to refer to X::a , b{i} // initializes X::b to the value of the parameter i , i(i) // initializes X::i to the value of the parameter i , j(this->i) // initializes X::j to the value of X::i {} }; ``` Exceptions that are thrown from member initializers may be handled by [function-try-block](function-try-block "cpp/language/function-try-block"). Member functions (including virtual member functions) can be called from member initializers, but the behavior is undefined if not all direct bases are initialized at that point. For virtual calls (if the direct bases are initialized at that point), the same rules apply as the rules for the virtual calls from constructors and destructors: virtual member functions behave as if the dynamic type of `*this` is the static type of the class that's being constructed (dynamic dispatch does not propagate down the inheritance hierarchy) and virtual calls (but not static calls) to [pure virtual](abstract_class "cpp/language/abstract class") member functions are undefined behavior. | | | | --- | --- | | If a non-static data member has a [default member initializer](data_members#Member_initialization "cpp/language/data members") and also appears in a member initializer list, then the member initializer is used and the default member initializer is ignored: ``` struct S { int n = 42; // default member initializer S() : n(7) {} // will set n to 7, not 42 }; ``` | (since C++11) | Reference members cannot be bound to temporaries in a member initializer list: ``` struct A { A() : v(42) {} // Error const int& v; }; ``` Note: same applies to [default member initializer](data_members#Member_initialization "cpp/language/data members"). | | | | --- | --- | | Delegating constructor If the name of the class itself appears as class-or-identifier in the member initializer list, then the list must consist of that one member initializer only; such a constructor is known as the *delegating constructor*, and the constructor selected by the only member of the initializer list is the *target constructor*. In this case, the target constructor is selected by overload resolution and executed first, then the control returns to the delegating constructor and its body is executed. Delegating constructors cannot be recursive. ``` class Foo { public: Foo(char x, int y) {} Foo(int y) : Foo('a', y) {} // Foo(int) delegates to Foo(char, int) }; ``` Inheriting constructors See [using declaration](using_declaration "cpp/language/using declaration"). | (since C++11) | #### Initialization order The order of member initializers in the list is irrelevant: the actual order of initialization is as follows: 1) If the constructor is for the most-derived class, virtual bases are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists) 2) Then, direct bases are initialized in left-to-right order as they appear in this class's base-specifier list 3) Then, non-static data member are initialized in order of declaration in the class definition. 4) Finally, the body of the constructor is executed (Note: if initialization order was controlled by the appearance in the member initializer lists of different constructors, then the [destructor](destructor "cpp/language/destructor") wouldn't be able to ensure that the order of destruction is the reverse of the order of construction). ### Example ``` #include <fstream> #include <string> #include <mutex> struct Base { int n; }; struct Class : public Base { unsigned char x; unsigned char y; std::mutex m; std::lock_guard<std::mutex> lg; std::fstream f; std::string s; Class(int x) : Base{123}, // initialize base class x(x), // x (member) is initialized with x (parameter) y{0}, // y initialized to 0 f{"test.cc", std::ios::app}, // this takes place after m and lg are initialized s(__func__), // __func__ is available because init-list is a part of constructor lg(m), // lg uses m, which is already initialized m{} // m is initialized before lg even though it appears last here {} // empty compound statement Class(double a) : y(a + 1), x(y), // x will be initialized before y, its value here is indeterminate lg(m) {} // base class initializer does not appear in the list, it is // default-initialized (not the same as if Base() were used, which is value-init) Class() try // function-try block begins before the function body, which includes init list : Class(0.0) // delegate constructor { // ... } catch (...) { // exception occurred on initialization } }; int main() { Class c; Class c1(1); Class c2(0.1); } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 194](https://cplusplus.github.io/CWG/issues/194.html) | C++98 | the declarator syntax of constructor only allowedat most one function specifier (e.g. a constructorcannot be declared `inline explicit`) | multiple functionspecifiers allowed | | [CWG 257](https://cplusplus.github.io/CWG/issues/257.html) | C++98 | it was unspecified whether an abstract class shouldprovide member initializers for its virtual base classes | specified as not requiredand such member initializersare ignored during execution | | [CWG 263](https://cplusplus.github.io/CWG/issues/263.html) | C++98 | the declarator syntax of constructorprohibited constructors from being friends | allowed constructorsto be friends | | [CWG 1345](https://cplusplus.github.io/CWG/issues/1345.html) | C++98 | anonymous union members without defaultmember initializers were default-initialized | they are not initialized | | [CWG 1435](https://cplusplus.github.io/CWG/issues/1435.html) | C++98 | the meaning of 'class name' in thedeclarator syntax of constructor was unclear | changed the syntax to a specializedfunction declarator syntax | | [CWG 1696](https://cplusplus.github.io/CWG/issues/1696.html) | C++98 | reference members could be initialized to temporaries(whose lifetime would end at the end of constructor) | such initializationis ill-formed | ### References * C++20 standard (ISO/IEC 14882:2020): + 11.4.4 Constructors [class.ctor] + 11.10.2 Initializing bases and members [class.base.init] * C++17 standard (ISO/IEC 14882:2017): + 15.1 Constructors [class.ctor] + 15.6.2 Initializing bases and members [class.base.init] * C++14 standard (ISO/IEC 14882:2014): + 12.1 Constructors [class.ctor] + 12.6.2 Initializing bases and members [class.base.init] * C++11 standard (ISO/IEC 14882:2011): + 12.1 Constructors [class.ctor] + 12.6.2 Initializing bases and members [class.base.init] * C++98 standard (ISO/IEC 14882:1998): + 12.1 Constructors [class.ctor] + 12.6.2 Initializing bases and members [class.base.init] ### See also * [copy elision](copy_elision "cpp/language/copy elision") * [converting constructor](converting_constructor "cpp/language/converting constructor") * [copy assignment](copy_assignment "cpp/language/copy assignment") * [copy constructor](copy_constructor "cpp/language/copy constructor") * [default constructor](default_constructor "cpp/language/default constructor") * [destructor](destructor "cpp/language/destructor") * [`explicit`](explicit "cpp/language/explicit") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [copy initialization](copy_initialization "cpp/language/copy initialization") + [default initialization](default_initialization "cpp/language/default initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [list initialization](list_initialization "cpp/language/list initialization") + [reference initialization](reference_initialization "cpp/language/reference initialization") + [value initialization](value_initialization "cpp/language/value initialization") + [zero initialization](zero_initialization "cpp/language/zero initialization") * [move assignment](move_assignment "cpp/language/move assignment") * [move constructor](move_constructor "cpp/language/move constructor") * [`new`](new "cpp/language/new") cpp reinterpret_cast conversion `reinterpret_cast` conversion ============================== Converts between types by reinterpreting the underlying bit pattern. ### Syntax | | | | | --- | --- | --- | | `reinterpret_cast <` new-type `> (` expression `)` | | | Returns a value of type new-type. ### Explanation Unlike `static_cast`, but like `const_cast`, the `reinterpret_cast` expression does not compile to any CPU instructions (except when converting between integers and pointers or on obscure architectures where pointer representation depends on its type). It is purely a compile-time directive which instructs the compiler to treat expression as if it had the type new-type. Only the following conversions can be done with `reinterpret_cast`, except when such conversions would cast away *constness* or *volatility*. 1) An expression of integral, enumeration, pointer, or pointer-to-member type can be converted to its own type. The resulting value is the same as the value of expression. 2) A pointer can be converted to any integral type large enough to hold all values of its type (e.g. to `[std::uintptr\_t](../types/integer "cpp/types/integer")`) 3) A value of any integral or enumeration type can be converted to a pointer type. A pointer converted to an integer of sufficient size and back to the same pointer type is guaranteed to have its original value, otherwise the resulting pointer cannot be dereferenced safely (the round-trip conversion in the opposite direction is not guaranteed; the same pointer may have multiple integer representations) The null pointer constant `[NULL](../types/null "cpp/types/NULL")` or integer zero is not guaranteed to yield the null pointer value of the target type; [`static_cast`](static_cast "cpp/language/static cast") or [implicit conversion](implicit_cast "cpp/language/implicit cast") should be used for this purpose. | | | | --- | --- | | 4) Any value of type `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")`, including `nullptr` can be converted to any integral type as if it were `(void*)0`, but no value, not even `nullptr` can be converted to `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")`: `static_cast` should be used for that purpose. | (since C++11) | 5) Any object pointer type `T1*` can be converted to another object pointer type `*cv* T2*`. This is exactly equivalent to `static_cast<cv T2*>(static_cast<cv void*>(expression))` (which implies that if `T2`'s alignment requirement is not stricter than `T1`'s, the value of the pointer does not change and conversion of the resulting pointer back to its original type yields the original value). In any case, the resulting pointer may only be dereferenced safely if allowed by the *type aliasing* rules (see below) 6) An [lvalue](value_category#lvalue "cpp/language/value category") (until C++11)[glvalue](value_category#glvalue "cpp/language/value category") (since C++11) expression of type `T1` can be converted to reference to another type `T2`. The result is that of `*reinterpret_cast<T2*>(p)`, where `p` is a pointer of type “pointer to `T1`” to the object designated by expression. No temporary is created, no copy is made, no constructors or conversion functions are called. The resulting reference can only be accessed safely if allowed by the *type aliasing* rules (see below) 7) Any pointer to function can be converted to a pointer to a different function type. Calling the function through a pointer to a different function type is undefined, but converting such pointer back to pointer to the original function type yields the pointer to the original function. 8) On some implementations (in particular, on any POSIX compatible system as required by [`dlsym`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/dlsym.html)), a function pointer can be converted to `void*` or any other object pointer, or vice versa. If the implementation supports conversion in both directions, conversion to the original type yields the original value, otherwise the resulting pointer cannot be dereferenced or called safely. 9) The null pointer value of any pointer type can be converted to any other pointer type, resulting in the null pointer value of that type. Note that the null pointer constant `nullptr` or any other value of type `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` cannot be converted to a pointer with `reinterpret_cast`: implicit conversion or `static_cast` should be used for this purpose. 10) A pointer to member function can be converted to pointer to a different member function of a different type. Conversion back to the original type yields the original value, otherwise the resulting pointer cannot be used safely. 11) A pointer to member object of some class `T1` can be converted to a pointer to another member object of another class `T2`. If `T2`'s alignment is not stricter than `T1`'s, conversion back to the original type `T1` yields the original value, otherwise the resulting pointer cannot be used safely. As with all cast expressions, the result is: | | | | --- | --- | | * an lvalue if new-type is a reference type; * an rvalue otherwise. | (until C++11) | | * an lvalue if new-type is an lvalue reference type or an rvalue reference to function type; * an xvalue if new-type is an rvalue reference to object type; * a prvalue otherwise. | (since C++11) | ### Keywords [`reinterpret_cast`](../keyword/reinterpret_cast "cpp/keyword/reinterpret cast"). ### Type aliasing Whenever an attempt is made to read or modify the stored value of an object of type `DynamicType` through a glvalue of type `AliasedType`, the behavior is undefined unless one of the following is true: * `AliasedType` and `DynamicType` are *similar*. * `AliasedType` is the (possibly [cv](cv "cpp/language/cv")-qualified) signed or unsigned variant of `DynamicType`. * `AliasedType` is [`std::byte`](../types/byte "cpp/types/byte"), (since C++17) `char`, or `unsigned char`: this permits examination of the [object representation](object#Object_representation_and_value_representation "cpp/language/object") of any object as an array of bytes. Informally, two types are *similar* if, ignoring top-level cv-qualification: * they are the same type; or * they are both pointers, and the pointed-to types are similar; or * they are both pointers to member of the same class, and the types of the pointed-to members are similar; or | | | | --- | --- | | * they are both arrays of the same size or both arrays of unknown bound, and the array element types are similar. | (until C++20) | | * they are both arrays of the same size or at least one of them is array of unknown bound, and the array element types are similar. | (since C++20) | For example: * `const int * volatile *` and `int * * const` are similar; * `const int (* volatile S::* const)[20]` and `int (* const S::* volatile)[20]` are similar; * `int (* const *)(int *)` and `int (* volatile *)(int *)` are similar; * `int (S::*)() const` and `int (S::*)()` are *not* similar; * `int (*)(int *)` and `int (*)(const int *)` are *not* similar; * `const int (*)(int *)` and `int (*)(int *)` are *not* similar; * `int (*)(int * const)` and `int (*)(int *)` are similar (they are the same type); * `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<int, int>` and `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const int, int>` are *not* similar. This rule enables type-based alias analysis, in which a compiler assumes that the value read through a glvalue of one type is not modified by a write to a glvalue of a different type (subject to the exceptions noted above). Note that many C++ compilers relax this rule, as a non-standard language extension, to allow wrong-type access through the inactive member of a [union](union "cpp/language/union") (such access is not undefined in C). ### Notes Assuming that alignment requirements are met, a `reinterpret_cast` does not change the [value of a pointer](pointer#Pointers "cpp/language/pointer") outside of a few limited cases dealing with [*pointer-interconvertible*](static_cast#pointer-interconvertible "cpp/language/static cast") objects: ``` struct S1 { int a; } s1; struct S2 { int a; private: int b; } s2; // not standard-layout union U { int a; double b; } u = {0}; int arr[2]; int* p1 = reinterpret_cast<int*>(&s1); // value of p1 is "pointer to s1.a" because // s1.a and s1 are pointer-interconvertible int* p2 = reinterpret_cast<int*>(&s2); // value of p2 is unchanged by reinterpret_cast // and is "pointer to s2". int* p3 = reinterpret_cast<int*>(&u); // value of p3 is "pointer to u.a": // u.a and u are pointer-interconvertible double* p4 = reinterpret_cast<double*>(p3); // value of p4 is "pointer to u.b": u.a and // u.b are pointer-interconvertible because // both are pointer-interconvertible with u int* p5 = reinterpret_cast<int*>(&arr); // value of p5 is unchanged by reinterpret_cast // and is "pointer to arr" ``` Performing a class member access that designates a non-static data member or a non-static member function on a glvalue that does not actually designate an object of the appropriate type - such as one obtained through a `reinterpret_cast` - results in undefined behavior: ``` struct S { int x; }; struct T { int x; int f(); }; struct S1 : S {}; // standard-layout struct ST : S, T {}; // not standard-layout S s = {}; auto p = reinterpret_cast<T*>(&s); // value of p is "pointer to s" auto i = p->x; // class member access expression is undefined behavior; // s is not a T object p->x = 1; // undefined behavior p->f(); // undefined behavior S1 s1 = {}; auto p1 = reinterpret_cast<S*>(&s1); // value of p1 is "pointer to the S subobject of s1" auto i = p1->x; // OK p1->x = 1; // OK ST st = {}; auto p2 = reinterpret_cast<S*>(&st); // value of p2 is "pointer to st" auto i = p2->x; // undefined behavior p2->x = 1; // undefined behavior ``` Many compilers issue "strict aliasing" warnings in such cases, even though technically such constructs run afoul of something other than the paragraph commonly known as the "strict aliasing rule". The purpose of strict aliasing and related rules is to enable type-based alias analysis, which would be decimated if a program can validly create a situation where two pointers to unrelated types (e.g., an `int*` and a `float*`) could simultaneously exist and both can be used to load or store the same memory (see [this email on SG12 reflector](http://www.open-std.org/pipermail/ub/2016-February/000565.html)). Thus, any technique that is seemingly capable of creating such a situation necessarily invokes undefined behavior. When it is needed to interpret the bytes of an object as a value of a different type, `[std::memcpy](../string/byte/memcpy "cpp/string/byte/memcpy")` or [`std::bit_cast`](../numeric/bit_cast "cpp/numeric/bit cast") (since C++20)can be used: ``` double d = 0.1; std::int64_t n; static_assert(sizeof n == sizeof d); // n = *reinterpret_cast<std::int64_t*>(&d); // Undefined behavior std::memcpy(&n, &d, sizeof d); // OK n = std::bit_cast<std::int64_t>(d); // also OK ``` | | | | --- | --- | | If the implementation provides `[std::intptr\_t](../types/integer "cpp/types/integer")` and/or `[std::uintptr\_t](../types/integer "cpp/types/integer")`, then a cast from a pointer to an object type or *cv* `void` to these types is always well-defined. However, this is not guaranteed for a function pointer. | (since C++11) | The paragraph defining the strict aliasing rule in the standard used to contain two additional bullets partially inherited from C: * `AliasedType` is an [aggregate type](aggregate_initialization "cpp/language/aggregate initialization") or a [union](union "cpp/language/union") type which holds one of the aforementioned types as an element or non-static member (including, recursively, elements of subaggregates and non-static data members of the contained unions). * `AliasedType` is a (possibly [cv](cv "cpp/language/cv")-qualified) [base class](derived_class "cpp/language/derived class") of `DynamicType`. These bullets describe situations that cannot arise in C++ and therefore are omitted from the discussion above. In C, aggregate copy and assignment access the aggregate object as a whole. But in C++ such actions are always performed through a member function call, which accesses the individual subobjects rather than the entire object (or, in the case of unions, copies the object representation, i.e., via `unsigned char`). These bullets were eventually removed via [CWG2051](https://cplusplus.github.io/CWG/issues/2051.html). ### Example Demonstrates some uses of `reinterpret_cast`: ``` #include <cstdint> #include <cassert> #include <iostream> int f() { return 42; } int main() { int i = 7; // pointer to integer and back std::uintptr_t v1 = reinterpret_cast<std::uintptr_t>(&i); // static_cast is an error std::cout << "The value of &i is " << std::showbase << std::hex << v1 << '\n'; int* p1 = reinterpret_cast<int*>(v1); assert(p1 == &i); // pointer to function to another and back void(*fp1)() = reinterpret_cast<void(*)()>(f); // fp1(); undefined behavior int(*fp2)() = reinterpret_cast<int(*)()>(fp1); std::cout << std::dec << fp2() << '\n'; // safe // type aliasing through pointer char* p2 = reinterpret_cast<char*>(&i); std::cout << (p2[0] == '\x7' ? "This system is little-endian\n" : "This system is big-endian\n"); // type aliasing through reference reinterpret_cast<unsigned int&>(i) = 42; std::cout << i << '\n'; [[maybe_unused]] const int &const_iref = i; // int &iref = reinterpret_cast<int&>( // const_iref); // compiler error - can't get rid of const // Must use const_cast instead: int &iref = const_cast<int&>(const_iref); } ``` Possible output: ``` The value of &i is 0x7fff352c3580 42 This system is little-endian 42 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 195](https://cplusplus.github.io/CWG/issues/195.html) | C++98 | conversion between function pointersand object pointers not allowed | made conditionally-supported | | [CWG 658](https://cplusplus.github.io/CWG/issues/658.html) | C++98 | the result of pointer conversions was unspecified(except for conversions back to the original type) | specification provided for pointerswhose pointed-to types satisfythe alignment requirements | | [CWG 799](https://cplusplus.github.io/CWG/issues/799.html) | C++98 | it was unclear which identity conversioncan be done by `reinterpret_cast` | made clear | | [CWG 1268](https://cplusplus.github.io/CWG/issues/1268.html) | C++11 | `reinterpret_cast` could only cast lvalues to reference types | xvalues also allowed | ### See also | | | | --- | --- | | [`const_cast` conversion](const_cast "cpp/language/const cast") | adds or removes const | | [`static_cast` conversion](static_cast "cpp/language/static cast") | performs basic conversions | | [`dynamic_cast` conversion](dynamic_cast "cpp/language/dynamic cast") | performs checked polymorphic conversions | | [explicit casts](explicit_cast "cpp/language/explicit cast") | permissive conversions between types | | [standard conversions](implicit_cast "cpp/language/implicit cast") | implicit conversions from one type to another | | [bit\_cast](../numeric/bit_cast "cpp/numeric/bit cast") (C++20) | reinterpret the object representation of one type as that of another (function template) |
programming_docs
cpp Placeholder type specifiers (since C++11) Placeholder type specifiers (since C++11) ========================================= For variables, specifies that the type of the variable that is being declared will be automatically deduced from its initializer. | | | | --- | --- | | For functions, specifies that the return type will be deduced from its return statements. | (since C++14) | | | | | --- | --- | | For non-type template parameters, specifies that the type will be deduced from the argument. | (since C++17) | ### Syntax | | | | | --- | --- | --- | | type-constraint(optional) `auto` | (1) | (since C++11) | | type-constraint(optional) `decltype(auto)` | (2) | (since C++14) | | | | | | --- | --- | --- | | type-constraint | - | (since C++20) a [concept](constraints#Concepts "cpp/language/constraints") name, optionally qualified, optionally followed by a template argument list enclosed in `<>` | 1) type is deduced using the rules for [template argument deduction](template_argument_deduction#Other_contexts "cpp/language/template argument deduction"). 2) type is [`decltype(expr)`](decltype "cpp/language/decltype"), where `expr` is the initializer. The placeholder `auto` may be accompanied by modifiers, such as `const` or `&`, which will participate in the type deduction. The placeholder `decltype(auto)` must be the sole constituent of the declared type. (since C++14). ### Explanation A placeholder type specifier may appear in the following contexts: * in the type specifier sequence of a variable: `auto x = expr;` as a type specifier. The type is deduced from the initializer. If the placeholder type specifier is `auto` or type-constraint `auto` (since C++20), the variable type is deduced from the initializer using the rules for [template argument deduction](template_argument_deduction "cpp/language/template argument deduction") from a function call (see [template argument deduction — other contexts](template_argument_deduction#Other_contexts "cpp/language/template argument deduction") for details). For example, given `const auto& i = expr;`, the type of `i` is exactly the type of the argument `u` in an imaginary template `template<class U> void f(const U& u)` if the function call `f(expr)` was compiled. Therefore, `auto&&` may be deduced either as an lvalue reference or rvalue reference according to the initializer, which is used in range-based for loop. | | | | --- | --- | | If the placeholder type specifier is `decltype(auto)` or type-constraint `decltype(auto)` (since C++20), the deduced type is `decltype(expr)`, where `expr` is the initializer. | (since C++14) | If the placeholder type specifier is used to declare multiple variables, the deduced types must match. For example, the declaration `auto i = 0, d = 0.0;` is ill-formed, while the declaration `auto i = 0, *p = &i;` is well-formed and the `auto` is deduced as `int`. * in the type-id of a [new expression](new "cpp/language/new"). The type is deduced from the initializer. For `new *T* *init*` (where `*T*` contains a placeholder type, *init* is either a parenthesized initializer or a brace-enclosed initializer list), the type of `*T*` is deduced as if for variable `*x*` in the invented declaration `T x init;`. * (since C++14) in the return type of a [function](function "cpp/language/function") or lambda expression: `auto& f();`. The return type is deduced from the operand of its non-[discarded](if#Constexpr_If "cpp/language/if") (since C++17) [return statement](return "cpp/language/return"). See [function — return type deduction](function#Return_type_deduction "cpp/language/function"). * (since C++17) in the parameter declaration of a [non-type template parameter](template_parameters#Non-type_template_parameter "cpp/language/template parameters"): `template<auto I> struct A;`. Its type is deduced from the corresponding argument. | | | | --- | --- | | The `auto` specifier may also appear in the simple type specifier of an [explicit type conversion](explicit_cast "cpp/language/explicit cast"): `auto(expr)` and `auto{expr}`. Its type is deduced from the expression. | (since C++23) | | | | | --- | --- | | Furthermore, `auto` and type-constraint `auto` (since C++20) can appear in:* the parameter declaration of a [lambda expression](lambda "cpp/language/lambda"): `[](auto&&){}`. Such lambda expression is a *generic lambda*. * (since C++20) a [function parameter declaration](function#Parameter_list "cpp/language/function"): `void f(auto);`. The function declaration introduces an [abbreviated function template](function_template#Abbreviated_function_template "cpp/language/function template"). | (since C++14) | | | | | --- | --- | | Type constraint If type-constraint is present, let `T` be the type deduced for the placeholder, the type-constraint introduces a [constraint expression](constraints "cpp/language/constraints") as follows:* If type-constraint is `Concept<A1, ..., An>`, then the constraint expression is `Concept<T, A1, ..., An>`; * otherwise (type-constraint is `Concept` without an argument list), the constraint expression is `Concept<T>`. Deduction fails if the constraint expression is invalid or returns `false`. | (since C++20) | ### Notes Until C++11, `auto` had the semantic of a [storage duration specifier](storage_duration "cpp/language/storage duration"). Mixing `auto` variables and functions in one declaration, as in `auto f() -> int, i = 0;` is not allowed. The `auto` specifier may also be used with a function declarator that is followed by a trailing return type, in which case the declared return type is that trailing return type (which may again be a placeholder type). ``` auto (*p)() -> int; // declares p as pointer to function returning int auto (*q)() -> auto = p; // declares q as pointer to function returning T // where T is deduced from the type of p ``` | | | | --- | --- | | The `auto` specifier may also be used in a [structured binding](structured_binding "cpp/language/structured binding") declaration. | (since C++17) | | | | | --- | --- | | The `auto` keyword may also be used in a nested-name-specifier. A nested-name-specifier of the form `auto::` is a placeholder that is replaced by a class or enumeration type following the rules for [constrained type](https://en.cppreference.com/w/cpp/experimental/constraints "cpp/experimental/constraints") placeholder deduction. | (concepts TS) | ### Example ``` #include <iostream> #include <utility> template<class T, class U> auto add(T t, U u) { return t + u; } // the return type is the type of operator+(T, U) // perfect forwarding of a function call must use decltype(auto) // in case the function it calls returns by reference template<class F, class... Args> decltype(auto) PerfectForward(F fun, Args&&... args) { return fun(std::forward<Args>(args)...); } template<auto n> // C++17 auto parameter declaration auto f() -> std::pair<decltype(n), decltype(n)> // auto can't deduce from brace-init-list { return {n, n}; } int main() { auto a = 1 + 2; // type of a is int auto b = add(1, 1.2); // type of b is double static_assert(std::is_same_v<decltype(a), int>); static_assert(std::is_same_v<decltype(b), double>); auto c0 = a; // type of c0 is int, holding a copy of a decltype(auto) c1 = a; // type of c1 is int, holding a copy of a decltype(auto) c2 = (a); // type of c2 is int&, an alias of a std::cout << "before modification through c2, a = " << a << '\n'; ++c2; std::cout << " after modification through c2, a = " << a << '\n'; auto [v, w] = f<0>(); //structured binding declaration auto d = {1, 2}; // OK: type of d is std::initializer_list<int> auto n = {5}; // OK: type of n is std::initializer_list<int> // auto e{1, 2}; // Error as of DR n3922, std::initializer_list<int> before auto m{5}; // OK: type of m is int as of DR n3922, initializer_list<int> before // decltype(auto) z = { 1, 2 } // Error: {1, 2} is not an expression // auto is commonly used for unnamed types such as the types of lambda expressions auto lambda = [](int x) { return x + 3; }; // auto int x; // valid C++98, error as of C++11 // auto x; // valid C, error in C++ [](...){}(c0, c1, v, w, d, n, m, lambda); // suppresses "unused variable" warnings } ``` Possible output: ``` before modification through c2, a = 3 after modification through c2, a = 4 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1265](https://cplusplus.github.io/CWG/issues/1265.html) | C++11 | the `auto` specifier could be used to declare a function with a trailingreturn type and define a variable in one declaration statement | prohibited | | [CWG 1346](https://cplusplus.github.io/CWG/issues/1346.html) | C++11 | a parenthesized expression list could not be assigned to an auto variable | allowed | | [CWG 1347](https://cplusplus.github.io/CWG/issues/1347.html) | C++11 | an declaration with the `auto` specifier could define two variableswith types `T` and `std::initializer_list<T>` respectively | prohibited | | [CWG 1852](https://cplusplus.github.io/CWG/issues/1852.html) | C++14 | the `auto` specifier in `decltype(auto)` was also a placeholder | not a placeholder in this case | cpp Default constructors Default constructors ==================== A default constructor is a [constructor](constructor "cpp/language/constructor") which can be called with no arguments (either defined with an empty parameter list, or with default arguments provided for every parameter). A type with a public default constructor is [DefaultConstructible](../named_req/defaultconstructible "cpp/named req/DefaultConstructible"). ### Syntax | | | | | --- | --- | --- | | class\_name `(` `)` `;` | (1) | | | class\_name `::` class\_name `(` `)` body | (2) | | | class\_name`()` `=` `delete` `;` | (3) | (since C++11) | | class\_name`()` `=` `default` `;` | (4) | (since C++11) | | class\_name `::` class\_name `(` `)` `=` `default` `;` | (5) | (since C++11) | Where class\_name must name the current class (or current instantiation of a class template), or, when declared at namespace scope or in a friend declaration, it must be a qualified class name. ### Explanation 1) Declaration of a default constructor inside of class definition. 2) Definition of the constructor outside of class definition (the class must contain a declaration (1)). See [constructors and member initializer lists](initializer_list "cpp/language/initializer list") for details on the constructor body. 3) Deleted default constructor: if it is selected by [overload resolution](overload_resolution "cpp/language/overload resolution"), the program fails to compile. 4) Defaulted default constructor: the compiler will define the implicit default constructor even if other constructors are present. 5) Defaulted default constructor outside of class definition (the class must contain a declaration (1)). Such constructor is treated as *user-provided* (see below and [value initialization](value_initialization "cpp/language/value initialization")). Default constructors are called during [default initializations](default_initialization "cpp/language/default initialization") and [value initializations](value_initialization "cpp/language/value initialization"). ### Implicitly-declared default constructor If no user-declared constructors of any kind are provided for a class type (`struct`, `class`, or `union`), the compiler will always declare a default constructor as an `inline public` member of its class. | | | | --- | --- | | If some user-declared constructors are present, the user may still force the automatic generation of a default constructor by the compiler that would be implicitly-declared otherwise with the keyword `default`. | (since C++11) | The implicitly-declared (or defaulted on its first declaration) default constructor has an exception specification as described in [dynamic exception specification](except_spec "cpp/language/except spec") (until C++17)[exception specification](noexcept_spec "cpp/language/noexcept spec") (since C++17). ### Implicitly-defined default constructor If the implicitly-declared default constructor is not defined as deleted, it is defined (that is, a function body is generated and compiled) by the compiler if [odr-used](definition#ODR-use "cpp/language/definition") or [needed for constant evaluation](constant_expression#Functions_and_variables_needed_for_constant_evaluation "cpp/language/constant expression") (since C++11), and it has the same effect as a user-defined constructor with empty body and empty initializer list. That is, it calls the default constructors of the bases and of the non-static members of this class. If this satisfies the requirements of a [constexpr constructor](constexpr "cpp/language/constexpr"), the generated constructor is `constexpr`. (since C++11) Class types with an empty user-provided constructor may get treated differently than those with an implicitly-defined or defaulted default constructor during [value initialization](value_initialization "cpp/language/value initialization"). | | | | --- | --- | | If some user-defined constructors are present, the user may still force the automatic generation of a default constructor by the compiler that would be implicitly-declared otherwise with the keyword `default`. | (since C++11) | ### Deleted implicitly-declared default constructor The implicitly-declared or defaulted (since C++11) default constructor for class `T` is undefined (until C++11)defined as deleted (since C++11) if any of the following is true: * `T` has a member of reference type without a default initializer (since C++11). * `T` has a non-[const-default-constructible](default_initialization#Default_initialization_of_a_const_object "cpp/language/default initialization") `const` member without a default member initializer (since C++11). * `T` has a member (without a default member initializer) (since C++11) which has a deleted default constructor, or its default constructor is ambiguous or inaccessible from this constructor. * `T` has a direct or virtual base which has a deleted default constructor, or it is ambiguous or inaccessible from this constructor. * `T` has a direct or virtual base or a non-static data member which has a deleted destructor, or a destructor that is inaccessible from this constructor. | | | | --- | --- | | * `T` is a [union](union "cpp/language/union") with at least one variant member with non-trivial default constructor, and no variant member of `T` has a default member initializer. * `T` is a [non-union class](union#Union-like_classes "cpp/language/union") with a variant member `M` with a non-trivial default constructor, and no variant member of the anonymous union containing `M` has a default member initializer. | (since C++11) | * `T` is a [union](union "cpp/language/union") and all of its variant members are `const`. | | | | --- | --- | | If no user-defined constructors are present and the implicitly-declared default constructor is not trivial, the user may still inhibit the automatic generation of an implicitly-defined default constructor by the compiler with the keyword `delete`. | (since C++11) | ### Trivial default constructor The default constructor for class `T` is trivial (i.e. performs no action) if all of the following is true: * The constructor is not user-provided (i.e., is implicitly-defined or defaulted on its first declaration) * `T` has no virtual member functions * `T` has no virtual base classes | | | | --- | --- | | * `T` has no non-static members with [default initializers](data_members#Member_initialization "cpp/language/data members"). | (since C++11) | * Every direct base of `T` has a trivial default constructor * Every non-static member of class type (or array thereof) has a trivial default constructor A trivial default constructor is a constructor that performs no action. All data types compatible with the C language (POD types) are trivially default-constructible. ### Eligible default constructor | | | | --- | --- | | A default constructor is eligible if it is either user-declared or both implicitly-declared and definable. | (until C++11) | | A default constructor is eligible if it is not deleted. | (since C++11)(until C++20) | | A default constructor is eligible if.* it is not deleted, and * its [associated constraints](constraints "cpp/language/constraints"), if any, are satisfied, and * no default constructor is [more constrained](constraints#Partial_ordering_of_constraints "cpp/language/constraints") than it. | (since C++20) | Triviality of eligible default constructors determines whether the class is an [implicit-lifetime type](lifetime#Implicit-lifetime_types "cpp/language/lifetime"), and whether the class is a [trivial type](../named_req/trivialtype "cpp/named req/TrivialType"). ### Example ``` struct A { int x; A(int x = 1): x(x) {} // user-defined default constructor }; struct B: A { // B::B() is implicitly-defined, calls A::A() }; struct C { A a; // C::C() is implicitly-defined, calls A::A() }; struct D: A { D(int y): A(y) {} // D::D() is not declared because another constructor exists }; struct E: A { E(int y): A(y) {} E() = default; // explicitly defaulted, calls A::A() }; struct F { int& ref; // reference member const int c; // const member // F::F() is implicitly defined as deleted }; // user declared copy constructor (either user-provided, deleted or defaulted) // prevents the implicit generation of a default constructor struct G { G(const G&) {} // G::G() is implicitly defined as deleted }; struct H { H(const H&) = delete; // H::H() is implicitly defined as deleted }; struct I { I(const I&) = default; // I::I() is implicitly defined as deleted }; int main() { A a; B b; C c; // D d; // compile error E e; // F f; // compile error // G g; // compile error // H h; // compile error // I i; // compile error } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 2084](https://cplusplus.github.io/CWG/issues/2084.html) | C++11 | default member initializers have no effect on whether a defaulted default constructor of a union is deleted | they prevent the defaulted default constructor from being defined as deleted | ### See also * [constructor](constructor "cpp/language/constructor") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [copy initialization](copy_initialization "cpp/language/copy initialization") + [default initialization](default_initialization "cpp/language/default initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [list initialization](list_initialization "cpp/language/list initialization") + [reference initialization](reference_initialization "cpp/language/reference initialization") + [value initialization](value_initialization "cpp/language/value initialization") + [zero initialization](zero_initialization "cpp/language/zero initialization") * [`new`](new "cpp/language/new") cpp Elaborated type specifier Elaborated type specifier ========================= Elaborated type specifiers may be used to refer to a previously-declared class name (class, struct, or union) or to a previously-declared enum name even if the name was [hidden by a non-type declaration](lookup "cpp/language/lookup"). They may also be used to declare new class names. ### Syntax | | | | | --- | --- | --- | | class-key class-name | (1) | | | `enum` enum-name | (2) | | | class-key attr(optional) identifier `;` | (3) | | | | | | | --- | --- | --- | | class-key | - | one of [class](../keyword/class "cpp/keyword/class"), [struct](../keyword/struct "cpp/keyword/struct"), [union](../keyword/union "cpp/keyword/union") | | class-name | - | the name of a previously-declared class type, optionally [qualified](identifiers#Qualified_identifiers "cpp/language/identifiers"), or an identifier not previously declared as a type name | | enum-name | - | the name of a previously-declared enumeration type, optionally [qualified](identifiers#Qualified_identifiers "cpp/language/identifiers") | 1) elaborated type specifier for a class type 2) elaborated type specifier for a enumeration type 3) A declaration that consists solely of an elaborated type specifier always declares a class type named by identifier in the [scope](scope "cpp/language/scope") that contains the declaration. [Opaque enum declaration](enum "cpp/language/enum") resembles form (3), but the enum type is a complete type after an opaque enum declaration. ### Explanation Form (3) is a special case of elaborated type specifier, usually referred to as *forward declaration* of classes, for the description of form (3), see [Forward declaration](class#Forward_declaration "cpp/language/class"). The following only apply to form (1) and (2). The class-name or enum-name in the elaborated type specifier may either be a simple identifier or be a [qualified-id](identifiers#Qualified_identifiers "cpp/language/identifiers"). The name is looked up using [unqualified name lookup](unqualified_lookup "cpp/language/unqualified lookup") or [qualified name lookup](qualified_lookup "cpp/language/qualified lookup"), depending on their appearance. But in either case, non-type names are not considered. ``` class T { public: class U; private: int U; }; int main() { int T; T t; // error: the local variable T is found class T t; // OK: finds ::T, the local variable T is ignored T::U* u; // error: lookup of T::U finds the private data member class T::U* u; // OK: the data member is ignored } ``` If the name lookup does not find a previously declared type name, the elaborated-type-specifier is introduced by `class`, `struct`, or `union` (i.e. not by `enum`), and class-name is an unqualified identifier, then the elaborated-type-specifier is a class declaration of the class-name. ``` template <typename T> struct Node { struct Node* Next; // OK: lookup of Node finds the injected-class-name struct Data* Data; // OK: declares type Data at global scope // and also declares the data member Data friend class ::List; // error: cannot introduce a qualified name enum Kind* kind; // error: cannot introduce an enum }; Data* p; // OK: struct Data has been declared ``` If the name refers to a [typedef name](typedef "cpp/language/typedef"), a [type alias](type_alias "cpp/language/type alias"), a [template type parameter](template_parameters#Type_template_parameter "cpp/language/template parameters"), or an [alias template specialization](type_alias "cpp/language/type alias"), the program is ill-formed, otherwise the elaborated type specifier introduces the name into the declaration the same way a [simple type specifier](declarations#Specifiers "cpp/language/declarations") introduces its type-name. ``` template <typename T> class Node { friend class T; // error: type parameter cannot appear in an elaborated type specifier }; class A {}; enum b { f, t }; int main() { class A a; // OK: equivalent to 'A a;' enum b flag; // OK: equivalent to 'b flag;' } ``` The class-key or `enum` keyword present in the elaborated-type-specifier must agree in kind with the declaration to which the name in the elaborated-type-specifier refers. * the `enum` keyword must be used to refer to an [enumeration type](enum "cpp/language/enum") (whether scoped or unscoped) * the `union` class-key must be used to refer to a [union](union "cpp/language/union") * either the `class` or `struct` class-key must be used to refer to a non-union class type (the keywords `class` and `struct` are interchangeable here). ``` enum class E { a, b }; enum E x = E::a; // OK enum class E y = E::b; // error: 'enum class' cannot introduce a elaborated type specifier struct A {}; class A a; // OK ``` When used as a [template argument](template_parameters#Template_arguments "cpp/language/template parameters"), `class T` is a type template parameter named `T`, not an unnamed non-type parameter whose type `T` is introduced by elaborated type specifier. ### References * C++20 standard (ISO/IEC 14882:2020): + 6.5.4 Elaborated type specifiers [basic.lookup.elab] + 9.2.8.3 Elaborated type specifiers [dcl.type.elab] * C++17 standard (ISO/IEC 14882:2017): + 6.4.4 Elaborated type specifiers [basic.lookup.elab] + 10.1.7.3 Elaborated type specifiers [dcl.type.elab] * C++14 standard (ISO/IEC 14882:2014): + 3.4.4 Elaborated type specifiers [basic.lookup.elab] + 7.1.6.3 Elaborated type specifiers [dcl.type.elab] * C++11 standard (ISO/IEC 14882:2011): + 3.4.4 Elaborated type specifiers [basic.lookup.elab] + 7.1.6.3 Elaborated type specifiers [dcl.type.elab] * C++98 standard (ISO/IEC 14882:1998): + 3.4.4 Elaborated type specifiers [basic.lookup.elab] + 7.1.5.3 Elaborated type specifiers [dcl.type.elab]
programming_docs
cpp Access specifiers Access specifiers ================= In a member-specification of a [class/struct](class "cpp/language/class") or [union](union "cpp/language/union"), define the accessibility of subsequent members. In a base-specifier of a [derived class](derived_class "cpp/language/derived class") declaration, define the accessibility of inherited members of the subsequent base class. ### Syntax | | | | | --- | --- | --- | | `public` `:` member-declarations | (1) | | | `protected` `:` member-declarations | (2) | | | `private` `:` member-declarations | (3) | | | `public` base-class | (4) | | | `protected` base-class | (5) | | | `private` base-class | (6) | | 1) The members declared after the access specifier have public member access 2) The members declared after the access specifier have protected member access 3) The members declared after the access specifier have private member access 4) [Public inheritance](derived_class#Public_inheritance "cpp/language/derived class"): the public and protected members of the [base class](derived_class "cpp/language/derived class") listed after the access specifier keep their member access in the derived class while the private members of the base class are inaccessible to the derived class 5) [Protected inheritance](derived_class#Protected_inheritance "cpp/language/derived class"): the public and protected members of the [base class](derived_class "cpp/language/derived class") listed after the access specifier are protected members of the derived class while the private members of the base class are inaccessible to the derived class 6) [Private inheritance](derived_class#Private_inheritance "cpp/language/derived class"): the public and protected members of the [base class](derived_class "cpp/language/derived class") listed after the access specifier are private members of the derived class while the private members of the base class are inaccessible to the derived class ### Explanation The name of every [class](class "cpp/language/class") member (static, non-static, function, type, etc) has an associated "member access". When a name of the member is used anywhere a program, its access is checked, and if it does not satisfy the access rules, the program does not compile: ``` #include <iostream> class Example { public: // all declarations after this point are public void add(int x) // member "add" has public access { n += x; // OK: private Example::n can be accessed from Example::add } private: // all declarations after this point are private int n = 0; // member "n" has private access }; int main() { Example e; e.add(1); // OK: public Example::add can be accessed from main // e.n = 7; // error: private Example::n cannot be accessed from main } ``` Access specifiers give the author of the class the ability to decide which class members are accessible to the users of the class (that is, the *interface*) and which members are for internal use of the class (the *implementation*). ### In detail All members of a class (bodies of [member functions](member_functions "cpp/language/member functions"), initializers of member objects, and the entire [nested class definitions](nested_types "cpp/language/nested types")) have access to all names the class can access. A local class within a member function has access to all names the member function can access. A class defined with the keyword `class` has private access for its members and its base classes by default. A class defined with the keyword `struct` has public access for its members and its base classes by default. A [union](union "cpp/language/union") has public access for its members by default. To grant access to additional functions or classes to protected or private members, a [friendship declaration](friend "cpp/language/friend") may be used. Accessibility applies to all names with no regard to their origin, so a name introduced by a [typedef](typedef "cpp/language/typedef") or [using declarations](using_declaration "cpp/language/using declaration") (except inheriting constructors) is checked, not the name it refers to: ``` class A : X { class B {}; // B is private in A public: typedef B BB; // BB is public }; void f() { A::B y; // error: A::B is private A::BB x; // OK: A::BB is public } ``` Member access does not affect visibility: names of private and privately-inherited members are visible and considered by overload resolution, implicit conversions to inaccessible base classes are still considered, etc. Member access check is the last step after any given language construct is interpreted. The intent of this rule is that replacing any `private` with `public` never alters the behavior of the program. Access checking for the names used in [default function arguments](default_arguments "cpp/language/default arguments") as well as in the default [template parameters](template_parameters#Default_template_arguments "cpp/language/template parameters") is performed at the point of declaration, not at the point of use. Access rules for the names of [virtual functions](virtual "cpp/language/virtual") are checked at the call point using the type of the expression used to denote the object for which the member function is called. The access of the final overrider is ignored: ``` struct B { virtual int f(); }; // f is public in B class D : public B { private: int f(); }; // f is private in D void f() { D d; B& b = d; b.f(); // OK: B::f is public, D::f is invoked even though it's private d.f(); // error: D::f is private } ``` A name that is private according to unqualified [name lookup](lookup "cpp/language/lookup"), may be accessible through qualified name lookup: ``` class A {}; class B : private A {}; class C : public B { A* p; // error: unqualified name lookup finds A as the private base of B ::A* q; // OK: qualified name lookup finds the namespace-level declaration }; ``` A name that is accessible through multiple paths in the inheritance graph has the access of the path with the most access: ``` class W { public: void f(); }; class A : private virtual W {}; class B : public virtual W {}; class C : public A, public B { void f() { W::f(); } // OK: W is accessible to C through B }; ``` Any number of access specifiers may appear within a class, in any order. Member access specifiers may affect class layout: the addresses of non-static [data members](data_members#Layout "cpp/language/data members") are only guaranteed to increase in order of declaration for the members not separated by an access specifier (until C++11)with the same access (since C++11). | | | | --- | --- | | For [standard-layout types](../named_req/standardlayouttype "cpp/named req/StandardLayoutType"), all non-static data members must have the same access. | (since C++11) | When a member is redeclared within the same class, it must do so under the same member access: ``` struct S { class A; // S::A is public private: class A {}; // error: cannot change access }; ``` ### Public member access Public members form a part of the public interface of a class (other parts of the public interface are the non-member functions found by [ADL](adl "cpp/language/adl")). A public member of a class is accessible anywhere: ``` class S { public: // n, E, A, B, C, U, f are public members int n; enum E {A, B, C}; struct U {}; static void f() {} }; int main() { S::f(); // S::f is accessible in main S s; s.n = S::B; // S::n and S::B are accessible in main S::U x; // S::U is accessible in main } ``` ### Protected member access Protected members form the interface of a class to its derived classes (which is distinct from the public interface of the class). A protected member of a class is only accessible. 1) to the members and friends of that class; 2) to the members of any derived class of that class, but only when the class of the object through which the protected member is accessed is that derived class or a derived class of that derived class: ``` struct Base { protected: int i; private: void g(Base& b, struct Derived& d); }; struct Derived : Base { void f(Base& b, Derived& d) // member function of a derived class { ++d.i; // OK: the type of d is Derived ++i; // OK: the type of the implied '*this' is Derived // ++b.i; // error: can't access a protected member through // Base (otherwise it would be possible to change // other derived classes, like a hypothetical // Derived2, base implementation) } }; void Base::g(Base& b, Derived& d) // member function of Base { ++i; // OK ++b.i; // OK ++d.i; // OK } void x(Base& b, Derived& d) // non-member non-friend { // ++b.i; // error: no access from non-member // ++d.i; // error: no access from non-member } ``` When a pointer to a protected member is formed, it must use a derived class in its declaration: ``` struct Base { protected: int i; }; struct Derived : Base { void f() { // int Base::* ptr = &Base::i; // error: must name using Derived int Base::* ptr = &Derived::i; // OK } }; ``` ### Private member access Private members form the implementation of a class, as well as the private interface for the other members of the class. A private member of a class is only accessible to the members and friends of that class, regardless of whether the members are on the same or different instances: ``` class S { private: int n; // S::n is private public: S() : n(10) {} // this->n is accessible in S::S S(const S& other) : n(other.n) {} // other.n is accessible in S::S }; ``` The [explicit cast](explicit_cast "cpp/language/explicit cast") (C-style and function-style) allows casting from a derived lvalue to reference to its private base, or from a pointer to derived to a pointer to its private base. ### Inheritance See [derived classes](derived_class "cpp/language/derived class") for the meaning of public, protected, and private inheritance. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1873](https://cplusplus.github.io/CWG/issues/1873.html) | C++98 | protected members were accessible to friends of derived classes | made inaccessible | cpp Phases of translation Phases of translation ===================== The C++ source file is processed by the compiler as if the following phases take place, in this exact order: ### Phase 1 1) The individual bytes of the source code file are mapped (in implementation-defined manner) to the characters of the [basic source character set](charset#Basic_source_character_set "cpp/language/charset") (until C++23)[translation character set](charset#Translation_character_set "cpp/language/charset") (since C++23). In particular, OS-dependent end-of-line indicators are replaced by newline characters. 2) The set of source file characters accepted is implementation-defined (since C++11). Any source file character that cannot be mapped to a character in the [basic source character set](charset#Basic_source_character_set "cpp/language/charset") is replaced by its [universal character name](escape "cpp/language/escape") (escaped with `\u` or `\U`) or by some implementation-defined form that is handled equivalently. (until C++23) | | | | --- | --- | | 3) [Trigraph sequences](operator_alternative "cpp/language/operator alternative") are replaced by corresponding single-character representations. | (until C++17) | ### Phase 2 1) Whenever backslash appears at the end of a line (immediately followed by zero or more whitespace characters other than new-line followed by (since C++23) the newline character), these characters are deleted, combining two physical source lines into one logical source line. This is a single-pass operation; a line ending in two backslashes followed by an empty line does not combine three lines into one. If a [universal character name](escape "cpp/language/escape") is formed outside [raw string literals](string_literal "cpp/language/string literal") (since C++11) in this phase, the behavior is undefined. 2) If a non-empty source file does not end with a newline character after this step (whether it had no newline originally, or it ended with a newline immediately preceded by a backslash), a terminating newline character is added. ### Phase 3 1) The source file is decomposed into [comments](../comment "cpp/comment"), sequences of whitespace characters (space, horizontal tab, new-line, vertical tab, and form-feed), and *preprocessing tokens*, which are the following: a) header names such as `<iostream>` or `"myfile.h"` b) [identifiers](identifiers "cpp/language/identifiers") c) preprocessing numbers d) [character](character_literal "cpp/language/character literal") and [string](string_literal "cpp/language/string literal") literals , including [user-defined](user_literal "cpp/language/user literal") (since C++11) e) operators and punctuators (including [alternative tokens](operator_alternative "cpp/language/operator alternative")), such as `+`, `<<=`, `<%`, `##`, or `and` f) individual non-whitespace characters that do not fit in any other category | | | | --- | --- | | 2) Any transformations performed during phases 1 and 2 between the initial and the final double quote of any [raw string literal](string_literal "cpp/language/string literal") are reverted. | (since C++11)(until C++23) | | | | | --- | --- | | 2) Any transformations performed during phase 2 (line splicing) between the initial and the final double quote of any [raw string literal](string_literal "cpp/language/string literal") are reverted. | (since C++23) | 3) Each comment is replaced by one space character. Newlines are kept, and it's unspecified whether non-newline whitespace sequences may be collapsed into single space characters. | | | | --- | --- | | As characters from the source file are consumed to form the next preprocessing token (i.e., not being consumed as part of a comment or other forms of whitespace), universal character names are recognized and replaced by the designated element of the [translation character set](charset#Translation_character_set "cpp/language/charset"), except when matching a character sequence in: a) a [character literal](character_literal "cpp/language/character literal") (c-char-sequence) b) a [string literal](string_literal "cpp/language/string literal") (s-char-sequence and r-char-sequence), excluding delimiters (d-char-sequence) c) a [file name for inclusion](../preprocessor/include "cpp/preprocessor/include") (h-char-sequence and q-char-sequence) | (since C++23) | If the input has been parsed into preprocessing tokens up to a given character, the next preprocessing token is generally taken to be the longest sequence of characters that could constitute a preprocessing token, even if that would cause subsequent analysis to fail. This is commonly known as *maximal munch*. ``` int foo = 1; int bar = 0xE+foo; // error, invalid preprocessing number 0xE+foo int baz = 0xE + foo; // OK int quux = bar+++++baz; // error: bar++ ++ +baz, not bar++ + ++baz. ``` The sole exceptions to the maximal munch rule are: | | | | --- | --- | | * If the next character begins a sequence of characters that could be the prefix and initial double quote of a [raw string literal](string_literal "cpp/language/string literal"), the next preprocessing token shall be a raw string literal. The literal consists of the shortest sequence of characters that matches the raw-string pattern. ``` #define R "x" const char* s = R"y"; // ill-formed raw string literal, not "x" "y" const char* s2 = R"(a)" "b)"; // a raw string literal followed by a normal string literal ``` * If the next three characters are `<::` and the subsequent character is neither `:` nor `>`, the `<` is treated as a preprocessing token by itself (and not as the first character of the [alternative token](operator_alternative "cpp/language/operator alternative") `<:`). ``` struct Foo { static const int v = 1; }; std::vector<::Foo> x; // OK, <: not taken as the alternative token for [ extern int y<::>; // OK, same as extern int y[]. int z<:::Foo::value:>; // OK, int z[::Foo::value]; ``` | (since C++11) | * Header name preprocessing tokens are only formed within a `#include` directive. ``` std::vector<int> x; // OK, <int> not a header-name ``` ### Phase 4 1) The [preprocessor](../preprocessor "cpp/preprocessor") is executed. If a [universal character name](escape "cpp/language/escape") is formed by [token concatenation](../preprocessor/replace#.23_and_.23.23_operators "cpp/preprocessor/replace"), the behavior is undefined. (until C++23) 2) Each file introduced with the [#include](../preprocessor/include "cpp/preprocessor/include") directive goes through phases 1 through 4, recursively. 3) At the end of this phase, all preprocessor directives are removed from the source. ### Phase 5 | | | | --- | --- | | 1) All characters in [character literals](character_literal "cpp/language/character literal") and [string literals](string_literal "cpp/language/string literal") are converted from the source character set to the *execution character set* (which may be a multibyte character set such as UTF-8, as long as the 96 characters of the [basic source character set](charset#Basic_source_character_set "cpp/language/charset") have single-byte representations). 2) [Escape sequences](escape "cpp/language/escape") and universal character names in character literals and non-raw string literals are expanded and converted to the *execution character set*. If the character specified by a universal character name isn't a member of the execution character set, the result is implementation-defined, but is guaranteed not to be a null (wide) character. Note: the conversion performed at this stage can be controlled by command line options in some implementations: gcc and clang use `-finput-charset` to specify the encoding of the source character set, `-fexec-charset` and `-fwide-exec-charset` to specify the encodings of the execution character set in the string and character literals that don't have an encoding prefix (since C++11), while Visual Studio 2015 Update 2 and later uses `/source-charset` and `/execution-charset` to specify the source character set and execution character set respectively. | (until C++23) | | For a sequence of two or more adjacent [string literal](string_literal "cpp/language/string literal") tokens, a common encoding prefix is determined as specified [here](string_literal#concatenation "cpp/language/string literal"). Each such string literal token is then considered to have that common encoding prefix. (Character conversion is moved to phase 3). | (since C++23) | ### Phase 6 Adjacent [string literals](string_literal "cpp/language/string literal") are concatenated. ### Phase 7 Compilation takes place: each preprocessing token is converted to a token. The tokens are syntactically and semantically analyzed and translated as a translation unit. ### Phase 8 Each translation unit is examined to produce a list of required template instantiations, including the ones requested by [explicit instantiations](class_template "cpp/language/class template"). The definitions of the templates are located, and the required instantiations are performed to produce *instantiation units*. ### Phase 9 Translation units, instantiation units, and library components needed to satisfy external references are collected into a program image which contains information needed for execution in its execution environment. ### Notes Some compilers don't implement instantiation units (also known as [template repositories](http://docs.oracle.com/cd/E18659_01/html/821-1383/bkagr.html#scrolltoc) or [template registries](http://www-01.ibm.com/support/knowledgecenter/SSXVZZ_12.1.0/com.ibm.xlcpp121.linux.doc/compiler_ref/fcat_template.html?lang=en)) and simply compile each template instantiation at phase 7, storing the code in the object file where it is implicitly or explicitly requested, and then the linker collapses these compiled instantiations into one at phase 9. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 787](https://cplusplus.github.io/CWG/issues/787.html) | C++98 | the behavior was undefined if a non-empty source file doesnot end with a newline character at the end of phase 2 | add a terminating newlinecharacter in this case | | [CWG 1775](https://cplusplus.github.io/CWG/issues/1775.html) | C++11 | forming a universal character name inside a rawstring literal in phase 2 resulted in undefined behavior | made well-defined | ### References * C++20 standard (ISO/IEC 14882:2020): + 5.2 Phases of translation [lex.phases] * C++17 standard (ISO/IEC 14882:2017): + 5.2 Phases of translation [lex.phases] * C++14 standard (ISO/IEC 14882:2014): + 2.2 Phases of translation [lex.phases] * C++11 standard (ISO/IEC 14882:2011): + 2.2 Phases of translation [lex.phases] * C++03 standard (ISO/IEC 14882:2003): + 2.1 Phases of translation [lex.phases] * C++98 standard (ISO/IEC 14882:1998): + 2.1 Phases of translation [lex.phases] ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/translation_phases "c/language/translation phases") for Phases of translation |
programming_docs
cpp Member access operators Member access operators ======================= Accesses a member of its operand. | Operator name | Syntax | [Over​load​able](operators "cpp/language/operators") | Prototype examples (for `class T`) | | --- | --- | --- | --- | | Inside class definition | Outside class definition | | subscript | `a[b]` | Yes | `R& T::operator[](S b);` | | | | --- | --- | | `R& T::operator[](S1 s1, ...);` | (since C++23) | | N/A | | indirection | `*a` | Yes | `R& T::operator*();` | `R& operator*(T a);` | | address-of | `&a` | Yes | `R* T::operator&();` | `R* operator&(T a);` | | member of object | `a.b` | No | N/A | N/A | | member of pointer | `a->b` | Yes | `R* T::operator->();` | N/A | | pointer to member of object | `a.*b` | No | N/A | N/A | | pointer to member of pointer | `a->*b` | Yes | `R& T::operator->*(S b);` | `R& operator->*(T a, S b);` | | **Notes*** As with most user-defined overloads, return types should match return types provided by the built-in operators so that [the user-defined operators](operators "cpp/language/operators") can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including `void`). One exception is `operator->`, which must return a pointer or another class with overloaded `operator->` to be realistically usable. | ### Explanation Built-in *subscript* operator provides access to an object pointed-to by the [pointer](pointer "cpp/language/pointer") or [array](array "cpp/language/array") operand. Built-in *indirection* operator provides access to an object or function pointed-to by the pointer operand. Built-in *address-of* operator creates a pointer pointing to the object or function operand. *Member of object* and *pointer to member of object* operators provide access to a data member or member function of the object operand. Built-in *member of pointer* and *pointer to member of pointer* operators provide access to a data member or member function of the class pointed-to by the pointer operand. #### Built-in subscript operator The subscript operator expressions have the form. | | | | | --- | --- | --- | | expr1 `[` expr2 `]` | (1) | | | expr1 `[` `{` expr, ... `}` `]` | (2) | (C++11) | | expr1 `[` expr2 `,` expr, ... `]` | (3) | (C++23) | 1) For the built-in operator, one of the expressions (either expr1 or expr2) must be a glvalue of type “array of T” or a prvalue of type “pointer to T”, while the other expression (expr2 or expr1, respectively) must be a prvalue of unscoped enumeration or integral type. The result of this expression has the type `T`. expr2 cannot be a unparenthesized [comma expression](operator_other#Built-in_comma_operator "cpp/language/operator other"). (since C++23) 2) The form with brace-enclosed list inside the square brackets is only used to call an overloaded `operator[]`. 3) The form with comma-separated expression list inside the square brackets is only used to call an overloaded `operator[]`. The built-in subscript expression `E1[E2]` is exactly identical to the expression `*(E1 + E2)` except for its value category(see below) and [evaluation order](eval_order "cpp/language/eval order") (since C++17): the pointer operand (which may be a result of array-to-pointer conversion, and which must point to an element of some array or one past the end) is adjusted to point to another element of the same array, following the rules of [pointer arithmetics](operator_arithmetic "cpp/language/operator arithmetic"), and is then dereferenced. When applied to an array, the subscript expression is an [lvalue](value_category "cpp/language/value category") if the array is an lvalue, and an [xvalue](value_category "cpp/language/value category") if it isn't (since C++11). When applied to a pointer, the subscript expression is always an lvalue. The type `T` is not allowed to be an [incomplete type](incomplete_type "cpp/language/incomplete type"), even if the size or internal structure of `T` is never used, as in `&x[0]`. | | | | --- | --- | | Using an unparenthesized [comma expression](operator_other#Built-in_comma_operator "cpp/language/operator other") as second (right) argument of a subscript operator is deprecated. For example, `a[b, c]` is deprecated and `a[(b, c)]` is not. | (since C++20)(until C++23) | | An unparenthesized [comma expression](operator_other#Built-in_comma_operator "cpp/language/operator other") cannot be second (right) argument of a subscript operator. For example, `a[b, c]` is either ill-formed or equivalent to `a.operator[](b, c)`. Parentheses are needed to for using a comma expression as the subscript, e.g., `a[(b, c)]`. | (since C++23) | In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for every object type `T` (possibly cv-qualified), the following function signature participates in overload resolution: | | | | | --- | --- | --- | | ``` T& operator[](T*, std::ptrdiff_t); ``` | | | | ``` T& operator[](std::ptrdiff_t, T*); ``` | | | ``` #include <iostream> #include <string> #include <map> int main() { int a[4] = {1, 2, 3, 4}; int* p = &a[2]; std::cout << p[1] << p[-1] << 1[p] << (-1)[p] << '\n'; std::map<std::pair<int, int>, std::string> m; m[{1, 2}] = "abc"; // uses the [{...}] version } ``` Output: ``` 4242 ``` #### Built-in indirection operator The indirection operator expressions have the form. | | | | | --- | --- | --- | | `*` expr | | | The operand of the built-in indirection operator must be pointer to object or a pointer to function, and the result is the lvalue referring to the object or function to which expr points. A pointer to (possibly [cv](cv "cpp/language/cv")-qualified) `void` cannot be dereferenced. Pointers to other incomplete types can be dereferenced, but the resulting lvalue can only be used in contexts that allow an lvalue of incomplete type, e.g. when initializing a reference. In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for every type `T` that is either object type (possibly cv-qualified) or function type (not const- or ref-qualified), the following function signature participates in overload resolution: | | | | | --- | --- | --- | | ``` T& operator*(T*); ``` | | | ``` #include <iostream> int f() { return 42; } int main() { int n = 1; int* pn = &n; int& r = *pn; // lvalue can be bound to a reference int m = *pn; // indirection + lvalue-to-rvalue conversion int (*fp)() = &f; int (&fr)() = *fp; // function lvalue can be bound to a reference } ``` #### Built-in address-of operator The address-of operator expressions have the form. | | | | | --- | --- | --- | | `&` expr | (1) | | | `&` class `::` member | (2) | | 1) If the operand is an lvalue expression of some object or function type `T`, `operator&` creates and returns a prvalue of type `T*`, with the same cv qualification, that is pointing to the object or function designated by the operand. If the operand has incomplete type, the pointer can be formed, but if that incomplete type happens to be a class that defines its own `operator&`, it is unspecified whether the built-in or the overload is used. For the operands of type with user-defined `operator&`, `[std::addressof](../memory/addressof "cpp/memory/addressof")` may be used to obtain the true pointer. Note that, unlike C99 and later C versions, there's no special case for the unary `operator&` applied to the result of the unary `operator*`. If the operand is the name of an overloaded function, the address may be taken only if the overload can be resolved due to context. See [Address of an overloaded function](overloaded_address "cpp/language/overloaded address") for details. 2) If the operand is a qualified name of a non-static or [variant](union#Union-like_classes "cpp/language/union") member, e.g. `&C::member`, the result is a prvalue [pointer to member function](pointer#Pointers_to_member_functions "cpp/language/pointer") or [pointer to data member](pointer#Pointers_to_data_members "cpp/language/pointer") of type `T` in class `C`. Note that neither `&member` nor `C::member` nor even `&(C::member)` may be used to initialize a pointer to member. In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), this operator does not introduce any additional function signatures: built-in address-of operator does not apply if there exists an overloaded `operator&` that is a [viable function](overload_resolution#Viable_functions "cpp/language/overload resolution"). ``` void f(int) {} void f(double) {} struct A { int i; }; struct B { void f(); }; int main() { int n = 1; int* pn = &n; // pointer int* pn2 = &*pn; // pn2 == pn int A::* mp = &A::i; // pointer to data member void (B::*mpf)() = &B::f; // pointer to member function void (*pf)(int) = &f; // overload resolution due to initialization context // auto pf2 = &f; // error: ambiguous overloaded function type auto pf2 = static_cast<void (*)(int)>(&f); // overload resolution due to cast } ``` #### Built-in member access operators The member access operator expressions have the form. | | | | | --- | --- | --- | | expr `.` `template`(optional) id-expr | (1) | | | expr `->` `template`(optional) id-expr | (2) | | | expr `.` pseudo-destructor | (3) | | | expr `->` pseudo-destructor | (4) | | 1) The first operand must be an expression of [complete class type](incomplete_type "cpp/language/incomplete type") `T`. 2) The first operand must be an expression of pointer to complete class type `T*`. 3,4) The first operand must be an expression of scalar type (see below) The first operand of both operators is evaluated even if it is not necessary (e.g. when the second operand names a static member). The second operand of both operators is a name of (formally, an [id-expression](identifiers#In_expressions "cpp/language/identifiers") that names) a data member or member function of `T` or of an unambiguous and accessible base class `B` of `T` (e.g. `E1.E2` or `E1->E2`), optionally [qualified](identifiers#Qualified_identifiers "cpp/language/identifiers") (e.g. `E1.B::E2` or `E1->B::E2`), optionally using [`template` disambiguator](dependent_name#template_disambiguator "cpp/language/dependent name") (e.g. `E1.template E2` or `E1->template E2`). If a user-defined `operator->` is provided, the `operator->` is called again on the value that it returns, recursively, until an `operator->` is reached that returns a plain pointer. After that, built-in semantics are applied to that pointer. The expression `E1->E2` is exactly equivalent to `(*E1).E2` for built-in types; that is why the following rules address only `E1.E2`. In the expression `E1.E2`: 1) if `E2` is a [static data member](static "cpp/language/static"): * if `E2` is of reference type `T&` or `T&&`, the result is an lvalue of type `T` designating the object or function to which `E2` refers, * otherwise, the result is an lvalue designating that static data member. Essentially, `E1` is evaluated and discarded in both cases; 2) if `E2` is a [non-static data member](data_members "cpp/language/data members"): * if `E2` is of reference type `T&` or `T&&`, the result is an lvalue of type `T` designating the object or function to which `E2` refers, * otherwise, if `E1` is an lvalue, the result is an lvalue designating that non-static data member of `E1`, * otherwise (if `E1` is an rvalue (until C++17)xvalue (which may be [materialized](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion") from prvalue) (since C++17)), the result is an rvalue (until C++11)xvalue (since C++11) designating that non-static data member of `E1`. If `E2` is not a mutable member, the [cv-qualification](cv "cpp/language/cv") of the result is the union of the cv-qualifications of `E1` and `E2`, otherwise (if `E2` is a mutable member), it is the union of the volatile-qualifications of `E1` and `E2`; 3) if `E2` is a [static member function](static "cpp/language/static"), the result is an lvalue designating that static member function. Essentially, `E1` is evaluated and discarded in this case; 4) if `E2` is a [non-static member function](member_functions "cpp/language/member functions") including a [destructor](destructor "cpp/language/destructor"), the result is a special kind of prvalue designating that non-static member function of `E1` that can only be used as the left-hand operand of a member function call operator, and for no other purpose; 5) if `E2` is a member enumerator, the result is a prvalue equal to that member enumerator of `E1`; 6) if `E2` is a [nested type](nested_classes "cpp/language/nested classes"), the program is ill-formed (won't compile); 7) if `E1` has a [scalar type](type "cpp/language/type") and `E2` is a `~` followed by the [type name](type#Type_naming "cpp/language/type") or [decltype specifier](decltype "cpp/language/decltype") designating the same type (minus cv-qualifications), optionally [qualified](identifiers#Qualified_identifiers "cpp/language/identifiers"), the result is a special kind of prvalue that can only be used as the left-hand operand of a function call operator, and for no other purpose. The resulting function call expression is called *pseudo destructor call*. It takes no arguments, returns void, evaluates `E1`, and ends the lifetime of its result object. This is the only case where the left-hand operand of `operator.` has non-class type. Allowing pseudo destructor call makes it possible to write code without having to know if a destructor exists for a given type. `operator.` cannot be overloaded, and for `operator->`, in [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), the built-in operator does not introduce any additional function signatures: built-in `operator->` does not apply if there exists an overloaded `operator->` that is a [viable function](overload_resolution#Viable_functions "cpp/language/overload resolution"). ``` #include <iostream> struct P { template<typename T> static T* ptr() { return new T; } }; template<typename T> struct A { A(int n): n(n) {} int n; static int sn; int f() { return 10 + n; } static int sf() { return 4; } class B {}; enum E {RED = 1, BLUE = 2}; void g() { typedef int U; // keyword template needed for a dependent template member int* p = T().template ptr<U>(); p->~U(); // U is int, calls int's pseudo destructor delete p; } }; template<> int A<P>::sn = 2; int main() { A<P> a(1); std::cout << a.n << ' ' << a.sn << ' ' // A::sn also works << a.f() << ' ' << a.sf() << ' ' // A::sf() also works // << a.B << ' ' // error: nested type not allowed << a.RED << ' '; // enumerator } ``` Output: ``` 1 2 11 4 1 ``` #### Built-in pointer-to-member access operators The member access operator expressions through pointers to members have the form. | | | | | --- | --- | --- | | lhs `.*` rhs | (1) | | | lhs `->*` rhs | (2) | | 1) lhs must be an expression of class type `T`. 2) lhs must be an expression of type pointer to class type `T*`. The second operand of both operators is an expression of type pointer to member ( [data](pointer#Pointers_to_data_members "cpp/language/pointer") or [function](pointer#Pointers_to_member_functions "cpp/language/pointer")) of `T` or pointer to member of an unambiguous and accessible base class `B` of `T`. The expression `E1->*E2` is exactly equivalent to `(*E1).*E2` for built-in types; that is why the following rules address only `E1.*E2`. In the expression `E1.*E2`: 1) if `E2` is a pointer to data member, * if `E1` is an lvalue, the result is an lvalue designating that data member, * otherwise (if `E1` is an rvalue (until C++17)xvalue (which may be [materialized](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion") from prvalue) (since C++17)), the result is an rvalue (until C++11)xvalue (since C++11) designating that data member; 2) if `E2` is a pointer to member function, the result is a special kind of prvalue designating that member function that can only be used as the left-hand operand of a member function call operator, and for no other purpose; 3) cv-qualification rules are the same as for member of object operator, with one additional rule: a pointer to member that refers to a mutable member cannot be used to modify that member in a const object; 4) if `E2` is a null pointer-to-member value, the behavior is undefined; 5) if the [dynamic type](type#Dynamic_type "cpp/language/type") of `E1` does not contain the member to which `E2` refers, the behavior is undefined; 6) if `E1` is an rvalue and `E2` points to a member function with ref-qualifier &, the program is ill-formed unless the member function has the cv-qualifier `const` but not `volatile` (since C++20); 7) if `E1` is an lvalue and `E2` points to a member function with ref-qualifier &&, the program is ill-formed. In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for every combination of types `D`, `B`, `R`, where class type `B` is either the same class as `D` or an unambiguous and accessible base class of `D`, and `R` is either an object or function type, the following function signature participates in overload resolution: | | | | | --- | --- | --- | | ``` R& operator->*(D*, R B::*); ``` | | | where both operands may be cv-qualified, in which case the return type's cv-qualification is the union of the cv-qualification of the operands. ``` #include <iostream> struct S { S(int n): mi(n) {} mutable int mi; int f(int n) { return mi + n; } }; struct D: public S { D(int n): S(n) {} }; int main() { int S::* pmi = &S::mi; int (S::* pf)(int) = &S::f; const S s(7); // s.*pmi = 10; // error: cannot modify through mutable std::cout << s.*pmi << '\n'; D d(7); // base pointers work with derived object D* pd = &d; std::cout << (d.*pf)(7) << ' ' << (pd->*pf)(8) << '\n'; } ``` Output: ``` 7 14 15 ``` ### Standard library Subscript operator is overloaded by many standard container classes. | | | | --- | --- | | [operator[]](../utility/bitset/operator_at "cpp/utility/bitset/operator at") | accesses specific bit (public member function of `std::bitset<N>`) | | [operator[]](../memory/unique_ptr/operator_at "cpp/memory/unique ptr/operator at") | provides indexed access to the managed array (public member function of `std::unique_ptr<T,Deleter>`) | | [operator[]](../string/basic_string/operator_at "cpp/string/basic string/operator at") | accesses the specified character (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [operator[]](../container/array/operator_at "cpp/container/array/operator at") (C++11) | access specified element (public member function of `std::array<T,N>`) | | [operator[]](../container/deque/operator_at "cpp/container/deque/operator at") | access specified element (public member function of `std::deque<T,Allocator>`) | | [operator[]](../container/vector/operator_at "cpp/container/vector/operator at") | access specified element (public member function of `std::vector<T,Allocator>`) | | [operator[]](../container/map/operator_at "cpp/container/map/operator at") | access or insert specified element (public member function of `std::map<Key,T,Compare,Allocator>`) | | [operator[]](../container/unordered_map/operator_at "cpp/container/unordered map/operator at") (C++11) | access or insert specified element (public member function of `std::unordered_map<Key,T,Hash,KeyEqual,Allocator>`) | | [operator[]](../iterator/reverse_iterator/operator_at "cpp/iterator/reverse iterator/operator at") | accesses an element by index (public member function of `std::reverse_iterator<Iter>`) | | [operator[]](../iterator/move_iterator/operator_at "cpp/iterator/move iterator/operator at") (C++11) | accesses an element by index (public member function of `std::move_iterator<Iter>`) | | [operator[]](../numeric/valarray/operator_at "cpp/numeric/valarray/operator at") | get/set valarray element, slice, or mask (public member function of `std::valarray<T>`) | | [operator[]](../regex/match_results/operator_at "cpp/regex/match results/operator at") | returns specified sub-match (public member function of `std::match_results<BidirIt,Alloc>`) | The indirection and member operators are overloaded by many iterators and smart pointer classes. | | | | --- | --- | | [operator\*operator->](../memory/unique_ptr/operator* "cpp/memory/unique ptr/operator*") | dereferences pointer to the managed object (public member function of `std::unique_ptr<T,Deleter>`) | | [operator\*operator->](../memory/shared_ptr/operator* "cpp/memory/shared ptr/operator*") | dereferences the stored pointer (public member function of `std::shared_ptr<T>`) | | [operator\*operator->](../memory/auto_ptr/operator* "cpp/memory/auto ptr/operator*") | accesses the managed object (public member function of `std::auto_ptr<T>`) | | [operator\*](../memory/raw_storage_iterator/operator* "cpp/memory/raw storage iterator/operator*") | dereferences the iterator (public member function of `std::raw_storage_iterator<OutputIt,T>`) | | [operator\*operator->](../iterator/reverse_iterator/operator* "cpp/iterator/reverse iterator/operator*") | dereferences the decremented underlying iterator (public member function of `std::reverse_iterator<Iter>`) | | [operator\*](../iterator/back_insert_iterator/operator* "cpp/iterator/back insert iterator/operator*") | no-op (public member function of `std::back_insert_iterator<Container>`) | | [operator\*](../iterator/front_insert_iterator/operator* "cpp/iterator/front insert iterator/operator*") | no-op (public member function of `std::front_insert_iterator<Container>`) | | [operator\*](../iterator/insert_iterator/operator* "cpp/iterator/insert iterator/operator*") | no-op (public member function of `std::insert_iterator<Container>`) | | [operator\*operator->](../iterator/move_iterator/operator* "cpp/iterator/move iterator/operator*") (C++11)(C++11)(deprecated in C++20) | accesses the pointed-to element (public member function of `std::move_iterator<Iter>`) | | [operator\*operator->](../iterator/istream_iterator/operator* "cpp/iterator/istream iterator/operator*") | returns the current element (public member function of `std::istream_iterator<T,CharT,Traits,Distance>`) | | [operator\*](../iterator/ostream_iterator/operator* "cpp/iterator/ostream iterator/operator*") | no-op (public member function of `std::ostream_iterator<T,CharT,Traits>`) | | [operator\*operator->](../iterator/istreambuf_iterator/operator* "cpp/iterator/istreambuf iterator/operator*") (since C++11)(until C++17) | obtains a copy of the current characteraccesses a member of the current character, if `CharT` has members (public member function of `std::istreambuf_iterator<CharT,Traits>`) | | [operator\*](../iterator/ostreambuf_iterator/operator* "cpp/iterator/ostreambuf iterator/operator*") | no-op (public member function of `std::ostreambuf_iterator<CharT,Traits>`) | | [operator\*operator->](../regex/regex_iterator/operator* "cpp/regex/regex iterator/operator*") | accesses the current match (public member function of `std::regex_iterator<BidirIt,CharT,Traits>`) | | [operator\*operator->](../regex/regex_token_iterator/operator* "cpp/regex/regex token iterator/operator*") | accesses current submatch (public member function of `std::regex_token_iterator<BidirIt,CharT,Traits>`) | No standard library classes overload `operator&`. The best known example of overloaded `operator&` is the Microsoft COM class [`CComPtr`](http://msdn.microsoft.com/en-us/library/31k6d0k7(v=vs.100).aspx), although it can also appear in EDSLs such as [boost.spirit](http://www.boost.org/doc/libs/release/libs/spirit/doc/html/spirit/qi/reference/operator/and_predicate.html). No standard library classes overload `operator->*`. It was suggested that it could be part of [smart pointer interface](http://www.aristeia.com/Papers/DDJ_Oct_1999.pdf), and in fact is used in that capacity by actors in [boost.phoenix](http://www.boost.org/doc/libs/release/libs/phoenix/doc/html/phoenix/modules/operator.html#phoenix.modules.operator.member_pointer_operator), but is more common in EDSLs such as [cpp.react](https://github.com/schlangster/cpp.react/blob/master/include/react/Signal.h#L557). ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1213](https://cplusplus.github.io/CWG/issues/1213.html) | C++11 | subscripting an array rvalue resulted in lvalue | reclassified as xvalue | | [CWG 1458](https://cplusplus.github.io/CWG/issues/1458.html) | C++98 | applying `&` to an lvalue of incomplete class type whichdeclares `operator&` resulted in undefined behavior | it is unspecifiedwhich `&` is used | | [CWG 1800](https://cplusplus.github.io/CWG/issues/1800.html) | C++98 | when applying `&` to a non-static data member of amember anonymous union, it was unclear whetherthe anonymous union take a part in the result type | the anonymous unionis not included inthe result type | ### See also [Operator precedence](operator_precedence "cpp/language/operator precedence"). [Operator overloading](operators "cpp/language/operators"). | Common operators | | --- | | [assignment](operator_assignment "cpp/language/operator assignment") | [incrementdecrement](operator_incdec "cpp/language/operator incdec") | [arithmetic](operator_arithmetic "cpp/language/operator arithmetic") | [logical](operator_logical "cpp/language/operator logical") | [comparison](operator_comparison "cpp/language/operator comparison") | **memberaccess** | [other](operator_other "cpp/language/operator other") | | `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b a <=> b`. | `a[b] *a &a a->b a.b a->*b a.*b`. | `a(...) a, b a ? b : c`. | | Special operators | | [`static_cast`](static_cast "cpp/language/static cast") converts one type to another related type [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") converts within inheritance hierarchies [`const_cast`](const_cast "cpp/language/const cast") adds or removes [cv](cv "cpp/language/cv") qualifiers [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") converts type to unrelated type [C-style cast](explicit_cast "cpp/language/explicit cast") converts one type to another by a mix of `static_cast`, `const_cast`, and `reinterpret_cast` [`new`](new "cpp/language/new") creates objects with dynamic storage duration [`delete`](delete "cpp/language/delete") destructs objects previously created by the new expression and releases obtained memory area [`sizeof`](sizeof "cpp/language/sizeof") queries the size of a type [`sizeof...`](sizeof... "cpp/language/sizeof...") queries the size of a [parameter pack](parameter_pack "cpp/language/parameter pack") (since C++11) [`typeid`](typeid "cpp/language/typeid") queries the type information of a type [`noexcept`](noexcept "cpp/language/noexcept") checks if an expression can throw an exception (since C++11) [`alignof`](alignof "cpp/language/alignof") queries alignment requirements of a type (since C++11). | | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/operator_member_access "c/language/operator member access") for Member access operators |
programming_docs
cpp Template Metaprogramming Template Metaprogramming ======================== Template metaprogramming is a family of techniques to create new types and compute values at compile time. C++ templates are Turing complete if there are no limits to the amount of recursive instantiations and the number of allowed state variables. Erwin Unruh was the first to demonstrate template metaprogramming at a committee meeting by instructing the compiler to print out prime numbers in error messages. The standard recommends an implementation support at least 1024 levels of recursive instantiation, and infinite recursion in template instantiations is undefined behavior. ### External links * David Vandevoorde, Nicolai M. Josuttis, Douglas Gregor (2017), [*C++ Templates - The Complete Guide, 2nd Edition.*](http://tmplbook.com/) * Wikibook: [Template Meta-Programming.](https://en.wikibooks.org/wiki/C++_Programming/Templates/Template_Meta-Programming) * Wikipedia: [Template Meta-Programming.](https://en.wikipedia.org/wiki/Template_metaprogramming "enwiki:Template metaprogramming") cpp Integer literal Integer literal =============== Allows values of integer type to be used in expressions directly. ### Syntax An integer literal has the form. | | | | | --- | --- | --- | | decimal-literal integer-suffix(optional) | (1) | | | octal-literal integer-suffix(optional) | (2) | | | hex-literal integer-suffix(optional) | (3) | | | binary-literal integer-suffix(optional) | (4) | (since C++14) | where. * decimal-literal is a non-zero decimal digit (`1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`), followed by zero or more decimal digits (`0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`) * octal-literal is the digit zero (`0`) followed by zero or more octal digits (`0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`) * hex-literal is the character sequence `0x` or the character sequence `0X` followed by one or more hexadecimal digits (`0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `a`, `A`, `b`, `B`, `c`, `C`, `d`, `D`, `e`, `E`, `f`, `F`) * binary-literal is the character sequence `0b` or the character sequence `0B` followed by one or more binary digits (`0`, `1`) * integer-suffix, if provided, may contain one or both of the following (if both are provided, they may appear in any order: * unsigned-suffix (the character `u` or the character `U`) * one of + long-suffix (the character `l` or the character `L`) | | | | --- | --- | | * long-long-suffix (the character sequence `ll` or the character sequence `LL`) | (since C++11) | | | | | --- | --- | | * size-suffix (the character `z` or the character `Z`) | (since C++23) | | | | | --- | --- | | Optional single quotes (`'`) may be inserted between the digits as a separator. They are ignored by the compiler. | (since C++14) | An integer literal (as any literal) is a [primary expression](expressions#Primary_expressions "cpp/language/expressions"). ### Explanation 1) Decimal integer literal (base 10) 2) Octal integer literal (base 8) 3) Hexadecimal integer literal (base 16, the letters 'a' through 'f' represent values (decimal) 10 through 15) 4) Binary integer literal (base 2) The first digit of an integer literal is the most significant. Example. The following variables are initialized to the same value: ``` int d = 42; int o = 052; int x = 0x2a; int X = 0X2A; int b = 0b101010; // C++14 ``` Example. The following variables are also initialized to the same value: ``` unsigned long long l1 = 18446744073709550592ull; // C++11 unsigned long long l2 = 18'446'744'073'709'550'592llu; // C++14 unsigned long long l3 = 1844'6744'0737'0955'0592uLL; // C++14 unsigned long long l4 = 184467'440737'0'95505'92LLU; // C++14 ``` ### The type of the literal The type of the integer literal is the first type in which the value can fit, from the list of types which depends on which numeric base and which integer-suffix was used: | Suffix | Decimal bases | Binary, octal, or hexadecimal bases | | --- | --- | --- | | (no suffix) | * `int` * `long int` * `long long int` (since C++11) | * `int` * `unsigned int` * `long int` * `unsigned long int` * `long long int` (since C++11) * `unsigned long long int` (since C++11) | | `u` or `U` | * `unsigned int` * `unsigned long int` * `unsigned long long int` (since C++11) | * `unsigned int` * `unsigned long int` * `unsigned long long int` (since C++11) | | `l` or `L` | * `long int` * `unsigned long int` (until C++11) * `long long int` (since C++11) | * `long int` * `unsigned long int` * `long long int` (since C++11) * `unsigned long long int` (since C++11) | | both `l`/`L`and `u`/`U` | * `unsigned long int` * `unsigned long long int` (since C++11) | * `unsigned long int` * `unsigned long long int` (since C++11) | | `ll` or `LL` | * `long long int` (since C++11) | * `long long int` (since C++11) * `unsigned long long int` (since C++11) | | both `ll`/`LL`and `u`/`U` | * `unsigned long long int` (since C++11) | * `unsigned long long int` (since C++11) | | `z` or `Z` | * the signed version of `[std::size\_t](../types/size_t "cpp/types/size t")` (since C++23) | * the signed version of `[std::size\_t](../types/size_t "cpp/types/size t")` (since C++23) * `[std::size\_t](../types/size_t "cpp/types/size t")` (since C++23) | | both `z`/`Z`and `u`/`U` | * `[std::size\_t](../types/size_t "cpp/types/size t")` (since C++23) | * `[std::size\_t](../types/size_t "cpp/types/size t")` (since C++23) | If the value of the integer literal is too big to fit in any of the types allowed by suffix/base combination and the compiler supports extended integer types (such as `__int128`) the literal may be given the extended integer type — otherwise the program is ill-formed. ### Notes Letters in the integer literals are case-insensitive: `0xDeAdBeEfU` and `0XdeadBEEFu` represent the same number (one exception is the long-long-suffix, which is either `ll` or `LL`, never `lL` or `Ll`) (since C++11). There are no negative integer literals. Expressions such as `-1` apply the [unary minus operator](operator_arithmetic "cpp/language/operator arithmetic") to the value represented by the literal, which may involve implicit type conversions. In C prior to C99 (but not in C++), unsuffixed decimal values that do not fit in `long int` are allowed to have the type `unsigned long int`. | | | | --- | --- | | When used in a controlling expression of [#if](../preprocessor/conditional "cpp/preprocessor/conditional") or [#elif](https://en.cppreference.com/w/c/preprocessor/conditional "c/preprocessor/conditional"), all signed integer constants act as if they have type `[std::intmax\_t](../types/integer "cpp/types/integer")` and all unsigned integer constants act as if they have type `[std::uintmax\_t](../types/integer "cpp/types/integer")`. | (since C++11) | Due to [maximal munch](translation_phases#maximal_munch "cpp/language/translation phases"), hexadecimal integer literals ending in `e` and `E`, when followed by the operators `+` or `-`, must be separated from the operator with whitespace or parentheses in the source: ``` auto x = 0xE+2.0; // error auto y = 0xa+2.0; // OK auto z = 0xE +2.0; // OK auto q = (0xE)+2.0; // OK ``` Otherwise, a single invalid preprocessing number token is formed, which causes further analysis to fail. ### Example ``` #include <cstddef> #include <iostream> #include <type_traits> int main() { std::cout << 123 << '\n' << 0123 << '\n' << 0x123 << '\n' << 0b10 << '\n' << 12345678901234567890ull << '\n' << 12345678901234567890u << '\n'; // the type is unsigned long long even // without a long long suffix // std::cout << -9223372036854775808 << '\n'; // error: the value // 9223372036854775808 cannot fit in signed long long, which is the // biggest type allowed for unsuffixed decimal integer literal std::cout << -9223372036854775808u << '\n'; // unary minus applied to unsigned // value subtracts it from 2^64, this gives 9223372036854775808 std::cout << -9223372036854775807 - 1 << '\n'; // correct way to calculate // the value -9223372036854775808 #if __cpp_size_t_suffix >= 202011L // C++23 static_assert(std::is_same_v<decltype(0UZ), std::size_t>); static_assert(std::is_same_v<decltype(0Z), std::make_signed_t<std::size_t>>); #endif } ``` Output: ``` 123 83 291 2 12345678901234567890 12345678901234567890 9223372036854775808 -9223372036854775808 ``` ### See also | | | | --- | --- | | [user-defined literals](user_literal "cpp/language/user literal")(C++11) | literals with user-defined suffix | | [C documentation](https://en.cppreference.com/w/c/language/integer_constant "c/language/integer constant") for integer constant | cpp List-initialization (since C++11) List-initialization (since C++11) ================================= Initializes an object from braced-init-list. ### Syntax #### Direct-list-initialization | | | | | --- | --- | --- | | T object `{` arg1, arg2, ... `};` | (1) | | | T `{` arg1, arg2, ... `}` | (2) | | | `new` T `{` arg1, arg2, ... `}` | (3) | | | Class `{` T member `{` arg1, arg2, ... `}; };` | (4) | | | Class`::`Class`() :` member `{` arg1, arg2, ... `} {...` | (5) | | #### Copy-list-initialization | | | | | --- | --- | --- | | T object `= {` arg1, arg2, ... `};` | (6) | | | function `({` arg1, arg2, ... `})` | (7) | | | `return {` arg1, arg2, ... `};` | (8) | | | object `[{` arg1, arg2, ... `}]` | (9) | | | object `= {` arg1, arg2, ... `}` | (10) | | | U `({` arg1, arg2, ... `})` | (11) | | | Class `{` T member `= {` arg1, arg2, ... `}; };` | (12) | | List initialization is performed in the following situations: * direct-list-initialization (both explicit and non-explicit constructors are considered) 1) initialization of a named variable with a braced-init-list (that is, a possibly empty brace-enclosed list of expressions or nested braced-init-lists) 2) initialization of an unnamed temporary with a braced-init-list 3) initialization of an object with dynamic storage duration with a [new-expression](new "cpp/language/new"), where the initializer is a braced-init-list 4) in a non-static [data member initializer](data_members#Member_initialization "cpp/language/data members") that does not use the equals sign 5) in a [member initializer list](initializer_list "cpp/language/initializer list") of a constructor if braced-init-list is used * copy-list-initialization (both explicit and non-explicit constructors are considered, but only non-explicit constructors may be called) 6) initialization of a named variable with a braced-init-list after an equals sign 7) in a function call expression, with braced-init-list used as an argument and list-initialization initializes the function parameter 8) in a `return` statement with braced-init-list used as the return expression and list-initialization initializes the returned object 9) in a [subscript expression](operator_member_access#Built-in_subscript_operator "cpp/language/operator member access") with a user-defined `operator[]`, where list-initialization initializes the parameter of the overloaded operator 10) in an [assignment expression](operator_assignment "cpp/language/operator assignment"), where list-initialization initializes the parameter of the overloaded operator 11) [functional cast expression](explicit_cast "cpp/language/explicit cast") or other constructor invocations, where braced-init-list is used in place of a constructor argument. Copy-list-initialization initializes the constructor's parameter (note; the type U in this example is not the type that's being list-initialized; U's constructor's parameter is) 12) in a non-static [data member initializer](data_members#Member_initialization "cpp/language/data members") that uses the equals sign ### Explanation The effects of list-initialization of an object of type `T` are: * If `T` is an aggregate class and the braced-init-list has a single element of the same or derived type (possibly cv-qualified), the object is initialized from that element (by [copy-initialization](copy_initialization "cpp/language/copy initialization") for copy-list-initialization, or by [direct-initialization](direct_initialization "cpp/language/direct initialization") for direct-list-initialization). * Otherwise, if `T` is a character array and the braced-init-list has a single element that is an appropriately-typed string literal, the array is [initialized from the string literal as usual](aggregate_initialization#Character_arrays "cpp/language/aggregate initialization"). * Otherwise, if `T` is an [aggregate type](aggregate_initialization "cpp/language/aggregate initialization"), [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") is performed. * Otherwise, if the braced-init-list is empty and `T` is a class type with a default constructor, [value-initialization](value_initialization "cpp/language/value initialization") is performed. * Otherwise, if `T` is a specialization of `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")`, the `T` object is direct-initialized or copy-initialized, depending on context, from a prvalue of the same type initialized from (until C++17) the braced-init-list. * Otherwise, the constructors of `T` are considered, in two phases: + All constructors that take `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` as the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by [overload resolution](overload_resolution "cpp/language/overload resolution") against a single argument of type `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` + If the previous stage does not produce a match, all constructors of `T` participate in [overload resolution](overload_resolution#Implicit_conversion_sequence_in_list-initialization "cpp/language/overload resolution") against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only non-narrowing conversions are allowed. If this stage produces an explicit constructor as the best match for a copy-list-initialization, compilation fails (note, in simple copy-initialization, explicit constructors are not considered at all). | | | | --- | --- | | * Otherwise, if: + `T` is an [enumeration type](enum "cpp/language/enum") that with fixed underlying type `U` (which is `int` if the enumeration is scoped and its underlying type is not manually specified), and + the initialization is direct-list-initialization, and + the braced-init-list has only one initializer `v` that is implicitly convertible to `U`, and + the conversion from `v` to `U` is non-narrowing, then the enumeration is initialized with the result of converting `v` to `U`. | (since C++17) | * Otherwise (if `T` is not a class type), if the braced-init-list has only one element and either `T` is not a reference type or is a reference type whose referenced type is same as or is a base class of the type of the element, `T` is [direct-initialized](direct_initialization "cpp/language/direct initialization") (in direct-list-initialization) or [copy-initialized](copy_initialization "cpp/language/copy initialization") (in copy-list-initialization), except that narrowing conversions are not allowed. * Otherwise, if `T` is a reference type that is not compatible with the type of the element: | | | | --- | --- | | * a prvalue temporary of the type referenced by `T` is copy-list-initialized, and the reference is bound to that temporary (this fails if the reference is a non-const lvalue reference). | (until C++17) | | * a prvalue is generated. The prvalue initializes its result object by copy-list-initialization. The prvalue is then used to direct-initialize the reference (this fails if the reference is a non-const lvalue reference). The type of the temporary is the type referenced by `T`, unless `T` is “reference to array of unknown bound of `U`”, in which case the type of the temporary is the type of `x` in the declaration `U x[] H`, where `H` is the initializer list (since C++20). | (since C++17) | * Otherwise, if the braced-init-list has no elements, `T` is [value-initialized](value_initialization "cpp/language/value initialization"). ### Narrowing conversions List-initialization limits the allowed [implicit conversions](implicit_conversion "cpp/language/implicit conversion") by prohibiting the following: * conversion from a floating-point type to an integer type * conversion from a `long double` to `double` or to `float` and conversion from `double` to `float`, except where the source is a [constant expression](constant_expression "cpp/language/constant expression") and overflow does not occur * conversion from an integer type to a floating-point type, except where the source is a constant expression whose value can be stored exactly in the target type * conversion from integer or unscoped enumeration type to integer type that cannot represent all values of the original, except where source is a constant expression whose value can be stored exactly in the target type * conversion from a pointer type or pointer-to-member type to `bool` ### Notes Every initializer clause is [sequenced before](eval_order "cpp/language/eval order") any initializer clause that follows it in the braced-init-list. This is in contrast with the arguments of a [function call expression](operator_other#Built-in_function_call_operator "cpp/language/operator other"), which are [unsequenced](eval_order "cpp/language/eval order") (until C++17)[indeterminately sequenced](eval_order "cpp/language/eval order") (since C++17). A braced-init-list is not an expression and therefore has no type, e.g. `decltype({1,2})` is ill-formed. Having no type implies that template type deduction cannot deduce a type that matches a braced-init-list, so given the declaration `template<class T> void f(T);` the expression `f({1,2,3})` is ill-formed. However, the template parameter can otherwise be deduced, as is the case for `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<int> v([std::istream\_iterator](http://en.cppreference.com/w/cpp/iterator/istream_iterator)<int>([std::cin](http://en.cppreference.com/w/cpp/io/cin)), {})`, where the iterator type is deduced by the first argument but also used in the second parameter position. A special exception is made for [type deduction using the keyword `auto`](template_argument_deduction#Other_contexts "cpp/language/template argument deduction") , which deduces any braced-init-list as `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` in copy-list-initialization. Also because a braced-init-list has no type, [special rules for overload resolution](overload_resolution#Implicit_conversion_sequence_in_list-initialization "cpp/language/overload resolution") apply when it is used as an argument to an overloaded function call. Aggregates copy/move initialize directly from single-element braced-init-list of the same type, but non-aggregates consider initializer\_list constructors first: ``` struct X {}; // aggregate struct Q // non-aggregate { Q() = default; Q(Q const&) = default; Q(std::initializer_list<Q>) {} }; int main() { X x; X x2 = X{x}; // copy-constructor (not aggregate initialization) Q q; Q q2 = Q{q}; // initializer-list constructor (not copy constructor) } ``` Some compilers (e.g., gcc 10) only consider conversion from a pointer or a pointer-to-member to `bool` narrowing in C++20 mode. ### Example ``` #include <iostream> #include <vector> #include <map> #include <string> struct Foo { std::vector<int> mem = {1, 2, 3}; // list-initialization of a non-static member std::vector<int> mem2; Foo() : mem2{-1, -2, -3} {} // list-initialization of a member in constructor }; std::pair<std::string, std::string> f(std::pair<std::string, std::string> p) { return {p.second, p.first}; // list-initialization in return statement } int main() { int n0{}; // value-initialization (to zero) int n1{1}; // direct-list-initialization std::string s1{'a', 'b', 'c', 'd'}; // initializer-list constructor call std::string s2{s1, 2, 2}; // regular constructor call std::string s3{0x61, 'a'}; // initializer-list ctor is preferred to (int, char) int n2 = {1}; // copy-list-initialization double d = double{1.2}; // list-initialization of a prvalue, then copy-init auto s4 = std::string{"HelloWorld"}; // same as above, no temporary created since C++17 std::map<int, std::string> m = // nested list-initialization { {1, "a"}, {2, {'a', 'b', 'c'}}, {3, s1} }; std::cout << f({"hello", "world"}).first // list-initialization in function call << '\n'; const int (&ar)[2] = {1, 2}; // binds a lvalue reference to a temporary array int&& r1 = {1}; // binds a rvalue reference to a temporary int // int& r2 = {2}; // error: cannot bind rvalue to a non-const lvalue ref // int bad{1.0}; // error: narrowing conversion unsigned char uc1{10}; // okay // unsigned char uc2{-1}; // error: narrowing conversion Foo f; std::cout << n0 << ' ' << n1 << ' ' << n2 << '\n' << s1 << ' ' << s2 << ' ' << s3 << '\n'; for(auto p: m) std::cout << p.first << ' ' << p.second << '\n'; for(auto n: f.mem) std::cout << n << ' '; for(auto n: f.mem2) std::cout << n << ' '; } ``` Output: ``` world 0 1 1 abcd cd aa 1 a 2 abc 3 abcd 1 2 3 -1 -2 -3 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1288](https://cplusplus.github.io/CWG/issues/1288.html) | C++11 | list-initializing a reference with a single-elementbraced-init-list always bound the reference to a temporary | bind to thatelement if valid | | [CWG 1324](https://cplusplus.github.io/CWG/issues/1324.html) | C++11 | initialization considered first for initialization from `{}` | aggregate initializationconsidered first | | [CWG 1467](https://cplusplus.github.io/CWG/issues/1467.html) | C++11 | same-type initialization of aggregates and characterarrays was prohibited; initializer-list constructors hadpriority over copy constructors for single-element lists | same-type initializationallowed; single-elementlists initialize directly | | [CWG 1494](https://cplusplus.github.io/CWG/issues/1494.html) | C++11 | when list-initializing a reference with an element of anincompatible type, it was unspecified whether the temporarycreated is direct-list-initialized or copy-list-initialized | it depends on thekind of initializationfor the reference | | [CWG 2137](https://cplusplus.github.io/CWG/issues/2137.html) | C++11 | initializer-list constructors lost to copyconstructors when list-initializing X from `{X}` | non-aggregates considerinitializer-lists first | | [CWG 2267](https://cplusplus.github.io/CWG/issues/2267.html) | C++11 | the resolution of [CWG issue 1494](https://cplusplus.github.io/CWG/issues/1494.html) made clearthat temporaries could be direct-list-initialized | they are copy-list-initializedwhen list-initializing references | | [CWG 2374](https://cplusplus.github.io/CWG/issues/2374.html) | C++17 | direct-list-initialization of an enum allowed too many source types | restricted | | [P1957R2](https://wg21.link/P1957R2) | C++11 | conversion from a pointer/pointer-to-member to `bool` was not narrowing | made narrowing | ### See also * [constructor](constructor "cpp/language/constructor") * [converting constructor](converting_constructor "cpp/language/converting constructor") * [copy assignment](copy_assignment "cpp/language/copy assignment") * [copy constructor](copy_constructor "cpp/language/copy constructor") * [copy elision](copy_elision "cpp/language/copy elision") * [default constructor](default_constructor "cpp/language/default constructor") * [`explicit`](explicit "cpp/language/explicit") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [copy initialization](copy_initialization "cpp/language/copy initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [reference initialization](reference_initialization "cpp/language/reference initialization") + [value initialization](value_initialization "cpp/language/value initialization") + [zero initialization](zero_initialization "cpp/language/zero initialization") * [move assignment](move_assignment "cpp/language/move assignment") * [move constructor](move_constructor "cpp/language/move constructor") * [`new`](new "cpp/language/new")
programming_docs
cpp Dependent names Dependent names =============== Inside the definition of a [template](templates "cpp/language/templates") (both [class template](class_template "cpp/language/class template") and [function template](function_template "cpp/language/function template")), the meaning of some constructs may differ from one instantiation to another. In particular, types and expressions may depend on types of type template parameters and values of non-type template parameters. ``` template<typename T> struct X : B<T> // "B<T>" is dependent on T { typename T::A* pa; // "T::A" is dependent on T // (see below for the meaning of this use of "typename") void f(B<T>* pb) { static int i = B<T>::i; // "B<T>::i" is dependent on T pb->j++; // "pb->j" is dependent on T } }; ``` Name lookup and binding are different for *dependent names* and non-*dependent names*. ### Binding rules Non-dependent names are looked up and bound at the point of template definition. This binding holds even if at the point of template instantiation there is a better match: ``` #include <iostream> void g(double) { std::cout << "g(double)\n"; } template<class T> struct S { void f() const { g(1); // "g" is a non-dependent name, bound now } }; void g(int) { std::cout << "g(int)\n"; } int main() { g(1); // calls g(int) S<int> s; s.f(); // calls g(double) } ``` If the meaning of a *non-dependent name* changes between the definition context and the point of instantiation of a specialization of the template, the program is ill-formed, no diagnostic required. This is possible in the following situations: * a type used in a non-dependent name is [incomplete](incomplete_type "cpp/language/incomplete type") at the point of definition but complete at the point of instantiation | | | | --- | --- | | * lookup for a name in the template definition found a [using-declaration](using_declaration "cpp/language/using declaration"), but the lookup in the corresponding scope in the instantiation does not find any declarations because the using-declaration was a pack expansion and the corresponding pack is empty | (since C++17) | * an instantiation uses a default argument or default template argument that had not been defined at the point of definition * a [constant expression](constant_expression "cpp/language/constant expression") at the point of instantiation uses the value of a const object of integral or unscoped enum type, the value of a constexpr object, the value of a reference, or the definition of a constexpr function (since C++11), and that object/reference/function (since C++11) was not defined at the point of definition * the template uses a non-dependent class template specialization or variable template specialization (since C++14) at the point of instantiation, and this template it uses is either instantiated from a partial specialization that was not defined at the point of definition or names an explicit specialization that was not declared at the point of definition Binding of *dependent names* is postponed until lookup takes place. ### Lookup rules As discussed in [lookup](lookup "cpp/language/lookup"), the lookup of a dependent name used in a template is postponed until the template arguments are known, at which time. * non-ADL lookup examines function declarations with external linkage that are visible from the *template definition* context * [ADL](adl "cpp/language/adl") examines function declarations with external linkage that are visible from either the *template definition* context or the *template instantiation* context (in other words, adding a new function declaration after template definition does not make it visible, except via ADL). The purpose of this rule is to help guard against violations of the [ODR](definition#One_Definition_Rule "cpp/language/definition") for template instantiations: ``` // an external library namespace E { template<typename T> void writeObject(const T& t) { std::cout << "Value = " << t << '\n'; } } // translation unit 1: // Programmer 1 wants to allow E::writeObject to work with vector<int> namespace P1 { std::ostream& operator<<(std::ostream& os, const std::vector<int>& v) { for(int n : v) os << n << ' '; return os; } void doSomething() { std::vector<int> v; E::writeObject(v); // error: will not find P1::operator<< } } // translation unit 2: // Programmer 2 wants to allow E::writeObject to work with vector<int> namespace P2 { std::ostream& operator<<(std::ostream& os, const std::vector<int>& v) { for(int n : v) os << n <<':'; return os << "[]"; } void doSomethingElse() { std::vector<int> v; E::writeObject(v); // error: will not find P2::operator<< } } ``` In the above example, if non-ADL lookup for `operator<<` were allowed from the instantiation context, the instantiation of `E::writeObject<vector<int>>` would have two different definitions: one using `P1::operator<<` and one using `P2::operator<<`. Such ODR violation may not be detected by the linker, leading to one or the other being used in both instances. To make ADL examine a user-defined namespace, either `std::vector` should be replaced by a user-defined class or its element type should be a user-defined class: ``` namespace P1 { // if C is a class defined in the P1 namespace std::ostream& operator<<(std::ostream& os, const std::vector<C>& v) { for(C n : v) os << n; return os; } void doSomething() { std::vector<C> v; E::writeObject(v); // OK: instantiates writeObject(std::vector<P1::C>) // which finds P1::operator<< via ADL } } ``` Note: this rule makes it impractical to overload operators for standard library types: ``` #include <iostream> #include <vector> #include <iterator> #include <utility> // Bad idea: operator in global namespace, but its arguments are in std:: std::ostream& operator<<(std::ostream& os, std::pair<int, double> p) { return os << p.first << ',' << p.second; } int main() { typedef std::pair<int, double> elem_t; std::vector<elem_t> v(10); std::cout << v[0] << '\n'; // OK, ordinary lookup finds ::operator<< std::copy(v.begin(), v.end(), std::ostream_iterator<elem_t>(std::cout, " ")); // Error: both ordinary lookup from the point of definition of // std::ostream_iterator and ADL will only consider the std namespace, // and will find many overloads of std::operator<<, so the lookup will be done. // Overload resolution will then fail to find operator<< for elem_t // in the set found by the lookup. } ``` Note: limited lookup (but not binding) of dependent names also takes place at template definition time, as needed to distinguish them from non-dependent names and also to determine whether they are members of the current instantiation or members of unknown specialization. The information obtained by this lookup can be used to detect errors, see below. ### Dependent types The following types are dependent types: * template parameter * a member of an *unknown specialization* (see below) * a nested class/enum that is a dependent member of *unknown specialization* (see below) * a cv-qualified version of a dependent type * a compound type constructed from a dependent type * an array type whose element type is dependent or whose bound (if any) is value-dependent | | | | --- | --- | | * a function type whose parameters include one or more function [parameter packs](parameter_pack "cpp/language/parameter pack") | (since C++11) | * a function type whose exception specification is value-dependent * a [template-id](templates#template-id "cpp/language/templates") where either + the template name is a template parameter, or + any of template arguments is type-dependent, or value-dependent, or is a pack expansion (since C++11) (even if the template-id is used without its argument list, as [injected-class-name](injected-class-name "cpp/language/injected-class-name")) | | | | --- | --- | | * the result of [`decltype`](decltype "cpp/language/decltype") applied to a type-dependent expression The result of `decltype` applied to a type-dependent expression is a unique dependent type. Two such results refer to the same type only if their expressions are [equivalent](function_template#Function_template_overloading "cpp/language/function template"). | (since C++11) | Note: a typedef member of a current instantiation is only dependent when the type it refers to is. ### Type-dependent expressions The following expressions are type-dependent: * an expression whose any subexpression is a type-dependent expression * `this`, if the class is a dependent type. * an [id-expression](identifiers "cpp/language/identifiers") that is not a [concept-id](constraints "cpp/language/constraints") and (since C++20) + contains an identifier for which name lookup finds at least one dependent declaration + contains a dependent [template-id](templates#template-id "cpp/language/templates") | | | | --- | --- | | * contains the special identifier `__func__` (if some enclosing function is a template, a non-template member of a class template, or a generic lambda (since C++14)) | (since C++11) | * contains the name of [conversion function](cast_operator "cpp/language/cast operator") to a dependent type * contains a nested name specifier or [qualified-id](identifiers "cpp/language/identifiers") that is a member of *unknown specialization* * names a dependent member of the *current instantiation* which is a static data member of type "array of unknown bound" | | | | --- | --- | | * contains an identifier for which name lookup finds one or more declarations of member functions of the current instantiation declared with [return type deduction](function#Return_type_deduction "cpp/language/function") | (since C++14) | | * contains an identifier for which name lookup finds a [structured binding declaration](structured_binding "cpp/language/structured binding") whose initializer is type-dependent * contains an identifier for which name lookup finds a non-type template parameter whose type contains the placeholder `auto` * contains an identifier for which by name lookup finds a variable declared with a type that contains a placeholder type (e.g., `auto` static data member), where the initializer is type-dependent, | (since C++17) | * any cast expression to a dependent type * [new-expression](new "cpp/language/new") that creates an object of a dependent type * member access expression that refers to a member of the *current instantiation* whose type is dependent * member access expression that refers to a member of *unknown specialization* | | | | --- | --- | | * [fold-expression](fold "cpp/language/fold") | (since C++17) | Note: literals, pseudo-destructor calls, [`alignof`](alignof "cpp/language/alignof"), [`noexcept`](noexcept "cpp/language/noexcept") (since C++11), [`sizeof`](sizeof "cpp/language/sizeof"), [`typeid`](typeid "cpp/language/typeid"), [`delete`](delete "cpp/language/delete"), and [`throw`](throw "cpp/language/throw")-expressions are never type-dependent because the types of these expressions cannot be. ### Value-dependent expressions * an expression used in context where [constant expression](constant_expression "cpp/language/constant expression") is required, and whose any subexpression is value-dependent * an [id-expression](identifiers "cpp/language/identifiers") that | | | | --- | --- | | * is a [concept-id](constraints "cpp/language/constraints") and any of its arguments are dependent | (since C++20) | * is type-dependent * is a name of a non-type template parameter * names a static data member that is a dependent member of the *current instantiation* and is not initialized. * names a static member function that is a dependent member of the *current instantiation* * is a constant with a integer or enumeration (until C++11)literal (since C++11) type, initialized from a value-dependent expression * [`alignof`](alignof "cpp/language/alignof"), [`noexcept`](noexcept "cpp/language/noexcept"), (since C++11)[`sizeof`](sizeof "cpp/language/sizeof"), [`typeid`](typeid "cpp/language/typeid")-expressions where the argument is a type-dependent expression or a dependent type-id * any cast expression to a dependent type or from a value-dependent expression * address-of expression where the argument is [qualified-id](identifiers "cpp/language/identifiers") that names a dependent member of the *current instantiation* * address-of expression where the argument is any expression which, evaluated as a core [constant expression](constant_expression "cpp/language/constant expression"), refers to a [templated entity](templates#Templated_entity "cpp/language/templates") that is an object with static or thread storage (since C++11) duration or a member function. | | | | --- | --- | | * [fold-expression](fold "cpp/language/fold") | (since C++17) | ### Dependent names ### Current instantiation Within a class template definition (including its member functions and nested classes) some names may be deduced to refer to the *current instantiation*. This allows certain errors to be detected at the point of definition, rather than instantiation, and removes the requirement on the `typename` and `template` disambiguators for dependent names, see below. Only the following names can refer to the current instantiation: * in a class template definition: + a nested class, a member of class template, a member of a nested class, the injected-class-name of the template, the injected-class-name of a nested class. * in a primary class template definition or in the definition of its member: + name of the class template followed by template argument list (or an equivalent alias template specialization) for the primary template where each argument is equivalent (defined below) to its corresponding parameter. * in the definition of a nested class or class template: + name of the nested class used as a member of the current instantiation. * in the definition of a partial specialization or of a member of a partial specialization: + the name of the class template followed by template argument list for the partial specialization, where each argument is equivalent to its corresponding parameter. A template argument is equivalent to a template parameter if. * for a [type parameter](template_parameters#Type_template_parameter "cpp/language/template parameters"), the template argument denotes the same type as the template parameter. * for a [non-type parameter](template_parameters#Non-type_template_parameter "cpp/language/template parameters"), the template argument is an [identifier](identifiers "cpp/language/identifiers") that names a variable that is equivalent to the template parameter. A variable is equivalent to a template parameter if + it has the same type as the template parameter (ignoring cv-qualification) and + its initializer consists of a single identifier that names the template parameter or, recursively, such a variable. ``` template<class T> class A { A* p1; // A is the current instantiation A<T>* p2; // A<T> is the current instantiation ::A<T>* p4; // ::A<T> is the current instantiation A<T*> p3; // A<T*> is not the current instantiation class B { B* p1; // B is the current instantiation A<T>::B* p2; // A<T>::B is the current instantiation typename A<T*>::B* p3; // A<T*>::B is not the current instantiation }; }; template<class T> class A<T*> { A<T*>* p1; // A<T*> is the current instantiation A<T>* p2; // A<T> is not the current instantiation }; template<int I> struct B { static const int my_I = I; static const int my_I2 = I + 0; static const int my_I3 = my_I; static const long my_I4 = I; static const int my_I5 = (I); B<my_I>* b1; // B<my_I> is the current instantiation: // my_I has the same type as I, // and it is initialized with only I B<my_I2>* b2; // B<my_I2> is not the current instantiation: // I + 0 is not a single identifier B<my_I3>* b3; // B<my_I3> is the current instantiation: // my_I3 has the same type as I, // and it is initialized with only my_I (which is equivalent to I) B<my_I4>* b4; // B<my_I4> is not the current instantiation: // the type of my_I4 (long) is not the same as the type of I (int) B<my_I5>* b5; // B<my_I5> is not the current instantiation: // (I) is not a single identifier }; ``` Note that a base class can be the current instantiation if a nested class derives from its enclosing class template. Base classes that are dependent types but aren't the current instantiation are *dependent base classes*: ``` template<class T> struct A { typedef int M; struct B { typedef void M; struct C; }; }; template<class T> struct A<T>::B::C : A<T> { M m; // OK, A<T>::M }; ``` A name is classified as a member of the current instantiation if it is. * an unqualified name that is found by [unqualified lookup](unqualified_lookup "cpp/language/unqualified lookup") in the current instantiation or in its non-dependent base. * [qualified name](qualified_lookup "cpp/language/qualified lookup"), if the qualifier (the name to the left of `::`) names the current instantiation and lookup finds the name in the current instantiation or in its non-dependent base * a name used in a class member access expression (`y` in `x.y` or `xp->y`), where the object expression (`x` or `*xp`) is the current instantiation and lookup finds the name in the current instantiation or in its non-dependent base ``` template<class T> class A { static const int i = 5; int n1[i]; // i refers to a member of the current instantiation int n2[A::i]; // A::i refers to a member of the current instantiation int n3[A<T>::i]; // A<T>::i refers to a member of the current instantiation int f(); }; template<class T> int A<T>::f() { return i; // i refers to a member of the current instantiation } ``` Members of the current instantiation may be both dependent and non-dependent. If the lookup of a member of current instantiation gives a different result between the point of instantiation and the point of definition, the lookup is ambiguous. Note however that when a member name is used, it is not automatically converted to a class member access expression, only explicit member access expressions indicate members of current instantiation: ``` struct A { int m; }; struct B { int m; }; template<typename T> struct C : A, T { int f() { return this->m; } // finds A::m in the template definition context int g() { return m; } // finds A::m in the template definition context }; template int C<B>::f(); // error: finds both A::m and B::m template int C<B>::g(); // OK: transformation to class member access syntax // does not occur in the template definition context ``` ### Unknown specializations Within a template definition, certain names are deduced to belong to an *unknown specialization*, in particular, * a [qualified name](qualified_lookup "cpp/language/qualified lookup"), if any name that appears to the left of `::` is a *dependent type* that is not a member of the *current instantiation* * a [qualified name](qualified_lookup "cpp/language/qualified lookup"), whose qualifier is the *current instantiation*, and the name is not found in the current instantiation or any of its non-dependent base classes, and there is a dependent base class * a name of a member in a class member access expression (the `y` in `x.y` or `xp->y`), if the type of the object expression (`x` or `*xp`) is a *dependent type* and is not the *current instantiation* * a name of a member in a class member access expression (the `y` in `x.y` or `xp->y`), if the type of the object expression (`x` or `*xp`) is the *current instantiation*, and the name is not found in the current instantiation or any of its non-dependent base classes, and there is a dependent base class ``` template<typename T> struct Base {}; template<typename T> struct Derived : Base<T> { void f() { // Derived<T> refers to current instantiation // there is no 'unknown_type' in the current instantiation // but there is a dependent base (Base<T>) // Therefore, unknown_type is a member of unknown specialization typename Derived<T>::unknown_type z; } }; template<> struct Base<int> // this specialization provides it { typedef int unknown_type; }; ``` This classification allows the following errors to be detected at the point of template definition (rather than instantiation): * If any template definition has a [qualified name](qualified_lookup "cpp/language/qualified lookup") in which the qualifier refers to the *current instantiation* and the name is neither a member of *current instantiation* nor a member of *unknown specialization*, the program is ill-formed (no diagnostic required) even if the template is never instantiated. ``` template<class T> class A { typedef int type; void f() { A<T>::type i; // OK: 'type' is a member of the current instantiation typename A<T>::other j; // Error: // 'other' is not a member of the current instantiation // and it is not a member of an unknown specialization // because A<T> (which names the current instantiation), // has no dependent bases for 'other' to hide in. } }; ``` * If any template definition has a member acess expression where the object expression is the *current instantiation*, but the name is neither a member of *current instantiation* nor a member of *unknown specialization*, the program is ill-formed even if the template is never instantiated. Members of unknown specialization are always dependent, and are looked up and bound at the point of instantiation as all dependent names (see above). ### The `typename` disambiguator for dependent names In a declaration or a definition of a template, including alias template, a name that is not a member of the *current instantiation* and is dependent on a template parameter is not considered to be a type unless the keyword `typename` is used or unless it was already established as a type name, e.g. with a typedef declaration or by being used to name a base class. ``` #include <iostream> #include <vector> int p = 1; template<typename T> void foo(const std::vector<T> &v) { // std::vector<T>::const_iterator is a dependent name, typename std::vector<T>::const_iterator it = v.begin(); // without 'typename', the following is parsed as multiplication // of the type-dependent member variable 'const_iterator' // and some variable 'p'. Since there is a global 'p' visible // at this point, this template definition compiles. std::vector<T>::const_iterator* p; typedef typename std::vector<T>::const_iterator iter_t; iter_t * p2; // iter_t is a dependent name, but it's known to be a type name } template<typename T> struct S { typedef int value_t; // member of current instantiation void f() { S<T>::value_t n{}; // S<T> is dependent, but 'typename' not needed std::cout << n << '\n'; } }; int main() { std::vector<int> v; foo(v); // template instantiation fails: there is no member variable // called 'const_iterator' in the type std::vector<int> S<int>().f(); } ``` The keyword `typename` may only be used in this way before qualified names (e.g. `T::x`), but the names need not be dependent. Usual [qualified name lookup](qualified_lookup "cpp/language/qualified lookup") is used for the identifier prefixed by `typename`. Unlike the case with [elaborated type specifier](elaborated_type_specifier "cpp/language/elaborated type specifier"), the lookup rules do not change despite the qualifier: ``` struct A // A has a nested variable X and a nested type struct X { struct X {}; int X; }; struct B { struct X {}; // B has a nested type struct X }; template<class T> void f(T t) { typename T::X x; } void foo() { A a; B b; f(b); // OK: instantiates f<B>, T::X refers to B::X f(a); // error: cannot instantiate f<A>: // because qualified name lookup for A::X finds the data member } ``` The keyword `typename` can be used even outside of templates. ``` #include <vector> int main() { // Both OK (after resolving CWG 382) typedef typename std::vector<int>::const_iterator iter_t; typename std::vector<int> v; } ``` | | | | --- | --- | | In some contexts, only type names can validly appear. In these contexts, a dependent qualified name is assumed to name a type and no `typename` is required:* A qualified name that is used as a [declaration specifier](declarations#Specifiers "cpp/language/declarations") in the (top-level) decl-specifier-seq of: + a [simple declaration](declarations#Simple_declaration "cpp/language/declarations") or [function definition](function#Function_definition "cpp/language/function") at namespace scope; + a [class member declaration](class#Member_specification "cpp/language/class"); + a [parameter declaration](function#Parameter_list "cpp/language/function") in a [class member declaration](class#Member_specification "cpp/language/class") (including friend function declarations), outside of default arguments; + a [parameter declaration](function#Parameter_list "cpp/language/function") of a [declarator for a function or function template](function "cpp/language/function") whose name is qualified, outside of default arguments; + a [parameter declaration](function#Parameter_list "cpp/language/function") of a [lambda expression](lambda "cpp/language/lambda") outside of default arguments; + a parameter declaration of a [requires-expression](constraints#Requires_expressions "cpp/language/constraints"); + the type in the declaration of a [non-type template parameter](template_parameters#Non-type_template_parameter "cpp/language/template parameters"); * A qualified name that appears in *[type-id](type#Type_naming "cpp/language/type")*, where the smallest enclosing *type-id* is: + the type in a [new expression](new "cpp/language/new") that does not parenthesize its type; + the type-id in an [alias declaration](type_alias "cpp/language/type alias"); + a [trailing return type](function "cpp/language/function"), + a [default argument of a type template parameter](template_parameters#Type_template_parameter "cpp/language/template parameters"), or + the type-id of a [`static_cast`](static_cast "cpp/language/static cast"), [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast"), [`const_cast`](const_cast "cpp/language/const cast"), or [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast"). | (since C++20) | ### The `template` disambiguator for dependent names Similarly, in a template definition, a dependent name that is not a member of the *current instantiation* is not considered to be a template name unless the disambiguation keyword `template` is used or unless it was already established as a template name: ``` template<typename T> struct S { template<typename U> void foo() {} }; template<typename T> void bar() { S<T> s; s.foo<T>(); // error: < parsed as less than operator s.template foo<T>(); // OK } ``` The keyword `template` may only be used in this way after operators `::` (scope resolution), `->` (member access through pointer), and `.` (member access), the following are all valid examples: * `T::template foo<X>();` * `s.template foo<X>();` * `this->template foo<X>();` * `typename T::template iterator<int>::value_type v;` As is the case with `typename`, the `template` prefix is allowed even if the name is not dependent or the use does not appear in the scope of a template. Even if the name to the left of `::` refers to a namespace, the template disambiguator is allowed: ``` template<typename> struct S {}; ::template S<void> q; // allowed, but unnecessary ``` | | | | --- | --- | | Due to the special rules for [unqualified name lookup](unqualified_lookup "cpp/language/unqualified lookup") for template names in member access expressions, when a non-dependent template name appears in a member access expression (after `->` or after `.`), the disambiguator is unnecessary if there is a class or alias (since C++11) template with the same name found by ordinary lookup in the context of the expression. However, if the template found by lookup in the context of the expression differs from the one found in the context of the class, the program is ill-formed (until C++11). ``` template<int> struct A { int value; }; template<class T> void f(T t) { t.A<0>::value; // Ordinary lookup of A finds a class template. // A<0>::value names member of class A<0> // t.A < 0; // Error: '<' is treated as the start of template argument list } ``` | (until C++23) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 206](https://cplusplus.github.io/CWG/issues/206.html) | C++98 | it was unspecified at what point semantic constraints areapplied when a type used in a non-dependent name isincomplete at the point at which a template is defined but iscomplete at the point at which an instantiation is performed | the program is ill-formedand no diagnostic isrequired in this case | | [CWG 224](https://cplusplus.github.io/CWG/issues/224.html) | C++98 | the definition of dependent types was basedon the form of the name rather than lookup | definition revamped | | [CWG 382](https://cplusplus.github.io/CWG/issues/382.html) | C++98 | the `typename` disambiguator was only allowed in template scope | also allowed outsideof templates | | [CWG 468](https://cplusplus.github.io/CWG/issues/468.html) | C++98 | the `template` disambiguator was only allowed in template scope | also allowed outsideof templates | | [CWG 502](https://cplusplus.github.io/CWG/issues/502.html) | C++98 | it was unspecified whether nested enumerations are dependent | dependent as nested classes | | [CWG 1047](https://cplusplus.github.io/CWG/issues/1047.html) | C++98 | `typeid` expressions were never value-dependent | value-dependent if theoperand is type-dependent | | [CWG 1160](https://cplusplus.github.io/CWG/issues/1160.html) | C++98 | it was unspecified whether a name refers to the current instantiationwhen a template-id matching a primary template or partialspecialization appears in the definition of a member of the template | specified | | [CWG 1413](https://cplusplus.github.io/CWG/issues/1413.html) | C++98 | uninitialized static data member, static member function, and addressof member of a class template weren't listed as value-dependent | listed | | [CWG 1471](https://cplusplus.github.io/CWG/issues/1471.html) | C++98 | a nested type of a non-dependent base ofthe current instantiation was dependent | it is not dependent | | [CWG 1850](https://cplusplus.github.io/CWG/issues/1850.html) | C++98 | the list of cases that meaning may change between thedefinition context and the point of instantiation was incomplete | made complete | | [CWG 1929](https://cplusplus.github.io/CWG/issues/1929.html) | C++98 | it was not clear whether the `template` disambiguator canfollow a `::` where the name to its left refers to a namespace | allowed | | [CWG 2100](https://cplusplus.github.io/CWG/issues/2100.html) | C++98 | address of a static data member of classtemplate wasn't listed as value-dependent | listed | | [CWG 2276](https://cplusplus.github.io/CWG/issues/2276.html) | C++98 | a function type whose exception specificationis value-dependent was not a dependent type | it is | | [CWG 2307](https://cplusplus.github.io/CWG/issues/2307.html) | C++98 | a parenthesized non-type template parameter used as atemplate argument was equivalent to that template parameter | not equivalent anymore | | [CWG 2457](https://cplusplus.github.io/CWG/issues/2457.html) | C++11 | a function type with function parameter pack was not a dependent type | it is |
programming_docs
cpp Friend declaration Friend declaration ================== The friend declaration appears in a [class body](class "cpp/language/class") and grants a function or another class access to private and protected members of the class where the friend declaration appears. ### Syntax | | | | | --- | --- | --- | | `friend` function-declaration | (1) | | | `friend` function-definition | (2) | | | `friend` elaborated-class-specifier `;` | (3) | | | `friend` simple-type-specifier `;` `friend` typename-specifier `;` | (4) | (since C++11) | ### Description 1) Designates a function or several functions as friends of this class: ``` class Y { int data; // private member // the non-member function operator<< will have access to Y's private members friend std::ostream& operator<<(std::ostream& out, const Y& o); friend char* X::foo(int); // members of other classes can be friends too friend X::X(char), X::~X(); // constructors and destructors can be friends }; // friend declaration does not declare a member function // this operator<< still needs to be defined, as a non-member std::ostream& operator<<(std::ostream& out, const Y& y) { return out << y.data; // can access private member Y::data } ``` 2) (only allowed in non-[local](class#Local_classes "cpp/language/class") class definitions) Defines a non-member function, and makes it a friend of this class at the same time. Such non-member function is always [inline](inline "cpp/language/inline"), unless it is attached to a [named module](modules "cpp/language/modules") (since C++20). ``` class X { int a; friend void friend_set(X& p, int i) { p.a = i; // this is a non-member function } public: void member_set(int i) { a = i; // this is a member function } }; ``` 3) Designates the class, struct, or union named by the elaborated-class-specifier (see [elaborated type specifier](elaborated_type_specifier "cpp/language/elaborated type specifier")) as a friend of this class. This means that the friend's member declarations and definitions can access private and protected members of this class and also that the friend can inherit from private and protected members of this class. The name of the class that is used in this `friend` declaration does not need to be previously declared. 4) Designates the type named by the simple-type-specifier or typename-specifier as a friend of this class if that type is a (possibly [cv-qualified](cv "cpp/language/cv")) class, struct, or union; otherwise the `friend` declaration is ignored. This declaration will not forward declare a new type. ``` class Y {}; class A { int data; // private data member class B {}; // private nested type enum { a = 100 }; // private enumerator friend class X; // friend class forward declaration (elaborated class specifier) friend Y; // friend class declaration (simple type specifier) (since c++11) }; class X : A::B // OK: A::B accessible to friend { A::B mx; // OK: A::B accessible to member of friend class Y { A::B my; // OK: A::B accessible to nested member of friend }; int v[A::a]; // OK: A::a accessible to member of friend }; ``` ### Notes Friendship is not transitive (a friend of your friend is not your friend). Friendship is not inherited (your friend's children are not your friends). Storage class specifiers are not allowed in friend function declarations. A function that is defined in the friend declaration has external linkage, a function that was previously defined, keeps the linkage it was defined with. [Access specifiers](access "cpp/language/access") have no effect on the meaning of friend declarations (they can appear in `private:` or in `public:` sections, with no difference). A friend class declaration cannot define a new class (`friend class X {};` is an error). When a local class declares an unqualified function or class as a friend, only functions and classes in the innermost non-class scope are [looked up](lookup "cpp/language/lookup"), not the global functions: ``` class F {}; int f(); int main() { extern int g(); class Local // Local class in the main() function { friend int f(); // Error, no such function declared in main() friend int g(); // OK, there is a declaration for g in main() friend class F; // friends a local F (defined later) friend class ::F; // friends the global F }; class F {}; // local F } ``` A name first declared in a friend declaration within a class or class template `X` becomes a member of the innermost enclosing namespace of `X`, but is not visible for lookup (except argument-dependent lookup that considers `X`) unless a matching declaration at namespace scope is provided - see [namespaces](namespace#Namespaces "cpp/language/namespace") for details. ### Template friends Both [function template](function_template "cpp/language/function template") and [class template](class_template "cpp/language/class template") declarations may appear with the `friend` specifier in any non-local class or class template (although only function templates may be defined within the class or class template that is granting friendship). In this case, every specialization of the template becomes a friend, whether it is implicitly instantiated, partially specialized, or explicitly specialized. ``` class A { template<typename T> friend class B; // every B<T> is a friend of A template<typename T> friend void f(T) {} // every f<T> is a friend of A }; ``` Friend declarations cannot refer to partial specializations, but can refer to full specializations: ``` template<class T> class A {}; // primary template<class T> class A<T*> {}; // partial template<> class A<int> {}; // full class X { template<class T> friend class A<T*>; // error! friend class A<int>; // OK }; ``` When a friend declaration refers to a full specialization of a function template, the keywords `inline`/`constexpr` (since C++11)/`consteval` (since C++20) and default arguments cannot be used: ``` template<class T> void f(int); template<> void f<int>(int); class X { friend void f<int>(int x = 1); // error: default args not allowed }; ``` A template friend declaration can name a member of a class template A, which can be either a member function or a member type (the type must use [elaborated-type-specifier](elaborated_type_specifier "cpp/language/elaborated type specifier")). Such declaration is only well-formed if the last component in its nested-name-specifier (the name to the left of the last `::`) is a simple-template-id (template name followed by argument list in angle brackets) that names the class template. The template parameters of such template friend declaration must be deducible from the simple-template-id. In this case, the member of any specialization of either A or partial specializations of A becomes a friend. This does not involve instantiating the primary template A or partial specializations of A: the only requirements are that the deduction of the template parameters of A from that specialization succeeds, and that substitution of the deduced template arguments into the friend declaration produces a declaration that would be a valid redeclaration of the member of the specialization: ``` // primary template template<class T> struct A { struct B {}; void f(); struct D { void g(); }; T h(); template<T U> T i(); }; // full specialization template<> struct A<int> { struct B {}; int f(); struct D { void g(); }; template<int U> int i(); }; // another full specialization template<> struct A<float*> { int *h(); }; // the non-template class granting friendship to members of class template A class X { template<class T> friend struct A<T>::B; // all A<T>::B are friends, including A<int>::B template<class T> friend void A<T>::f(); // A<int>::f() is not a friend because its signature // does not match, but e.g. A<char>::f() is a friend // template<class T> // friend void A<T>::D::g(); // ill-formed, the last part of the nested-name-specifier, // // D in A<T>::D::, is not simple-template-id template<class T> friend int* A<T*>::h(); // all A<T*>::h are friends: // A<float*>::h(), A<int*>::h(), etc template<class T> template<T U> // all instantiations of A<T>::i() and A<int>::i() are friends, friend T A<T>::i(); // and thereby all specializations of those function templates }; ``` | | | | --- | --- | | [Default template arguments](template_parameters#Default_template_arguments "cpp/language/template parameters") are only allowed on template friend declarations if the declaration is a definition and no other declarations of this function template appear in this translation unit. | (since C++11) | ### Template friend operators A common use case for template friends is declaration of a non-member operator overload that acts on a class template, e.g. `operator<<([std::ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)&, const Foo<T>&)` for some user-defined `Foo<T>`. Such operator can be defined in the class body, which has the effect of generating a separate non-template `operator<<` for each `T` and makes that non-template `operator<<` a friend of its `Foo<T>`: ``` #include <iostream> template<typename T> class Foo { public: Foo(const T& val) : data(val) {} private: T data; // generates a non-template operator<< for this T friend std::ostream& operator<<(std::ostream& os, const Foo& obj) { return os << obj.data; } }; int main() { Foo<double> obj(1.23); std::cout << obj << '\n'; } ``` Output: ``` 1.23 ``` or the function template has to be declared as a template before the class body, in which case the friend declaration within `Foo<T>` can refer to the full specialization of `operator<<` for its `T`: ``` #include <iostream> template<typename T> class Foo; // forward declare to make function declaration possible template<typename T> // declaration std::ostream& operator<<(std::ostream&, const Foo<T>&); template<typename T> class Foo { public: Foo(const T& val) : data(val) {} private: T data; // refers to a full specialization for this particular T friend std::ostream& operator<< <> (std::ostream&, const Foo&); // note: this relies on template argument deduction in declarations // can also specify the template argument with operator<< <T>" }; // definition template<typename T> std::ostream& operator<<(std::ostream& os, const Foo<T>& obj) { return os << obj.data; } int main() { Foo<double> obj(1.23); std::cout << obj << '\n'; } ``` ### Example Stream insertion and extraction operators are often declared as non-member friends: ``` #include <iostream> #include <sstream> class MyClass { int i; // friends have access to non-public, non-static static inline int id{6}; // and static (possibly inline) members friend std::ostream& operator<<(std::ostream& out, const MyClass&); friend std::istream& operator>>(std::istream& in, MyClass&); friend void change_id(int); public: MyClass(int i = 0) : i(i) {} }; std::ostream& operator<<(std::ostream& out, const MyClass& mc) { return out << "MyClass::id = " << MyClass::id << "; i = " << mc.i; } std::istream& operator>>(std::istream& in, MyClass& mc) { return in >> mc.i; } void change_id(int id) { MyClass::id = id; } int main() { MyClass mc(7); std::cout << mc << '\n'; // mc.i = 333*2; // error: i is a private member std::istringstream("100") >> mc; std::cout << mc << '\n'; // MyClass::id = 222*3; // error: id is a private member change_id(9); std::cout << mc << '\n'; } ``` Output: ``` MyClass::id = 6; i = 7 MyClass::id = 6; i = 100 MyClass::id = 9; i = 100 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 45](https://cplusplus.github.io/CWG/issues/45.html) | C++98 | members of a class nested in a friendclass of `T` have no special access to `T` | a nested class has the sameaccess as the enclosing class | | [CWG 500](https://cplusplus.github.io/CWG/issues/500.html) | C++98 | friend class of `T` cannot inherit from private orprotected members of `T`, but its nested class can | both can inheritfrom such members | | [CWG 1439](https://cplusplus.github.io/CWG/issues/1439.html) | C++98 | the rule targeting friend declarations in non-localclasses did not cover template declarations | covered | | [CWG 1477](https://cplusplus.github.io/CWG/issues/1477.html) | C++98 | a name first declared in a friend declaration within a classor class template was not visible for lookup if the matchingdeclaration is provided in another namespace scope | it is visible forlookup in this case | | [CWG 1804](https://cplusplus.github.io/CWG/issues/1804.html) | C++98 | when a member of a class template is friended, the correspondingmember of specializations of partial specializations of the classtemplate was not a friend of the class granting friendship | such membersare also friends | | [CWG 2379](https://cplusplus.github.io/CWG/issues/2379.html) | C++11 | friend declarations referring to full specializationsof function templates could be declared constexpr | prohibited | ### References * C++20 standard (ISO/IEC 14882:2020): + 11.9.3 Friends [class.friend] + 13.7.4 Friends [temp.friend] * C++17 standard (ISO/IEC 14882:2017): + 14.3 Friends [class.friend] + 17.5.4 Friends [temp.friend] * C++14 standard (ISO/IEC 14882:2014): + 11.3 Friends [class.friend] + 14.5.4 Friends [temp.friend] * C++11 standard (ISO/IEC 14882:2011): + 11.3 Friends [class.friend] + 14.5.4 Friends [temp.friend] * C++98 standard (ISO/IEC 14882:1998): + 11.3 Friends [class.friend] + 14.5.3 Friends [temp.friend] ### See also | | | | --- | --- | | [Class types](class "cpp/language/class") | defines types holding several data members | | [Access specifiers](access "cpp/language/access") | defines visibility of class members | cpp virtual function specifier `virtual` function specifier ============================= The `virtual` specifier specifies that a non-static [member function](member_functions "cpp/language/member functions") is *virtual* and supports dynamic dispatch. It may only appear in the decl-specifier-seq of the initial declaration of a non-static member function (i.e., when it is declared in the class definition). ### Explanation Virtual functions are member functions whose behavior can be overridden in derived classes. As opposed to non-virtual functions, the overriding behavior is preserved even if there is no compile-time information about the actual type of the class. That is to say, if a derived class is handled using pointer or reference to the base class, a call to an overridden virtual function would invoke the behavior defined in the derived class. Such a function call is known as *virtual function call* or *virtual call*. Virtual function call is suppressed if the function is selected using [qualified name lookup](lookup "cpp/language/lookup") (that is, if the function's name appears to the right of the scope resolution operator `::`). ``` #include <iostream> struct Base { virtual void f() { std::cout << "base\n"; } }; struct Derived : Base { void f() override // 'override' is optional { std::cout << "derived\n"; } }; int main() { Base b; Derived d; // virtual function call through reference Base& br = b; // the type of br is Base& Base& dr = d; // the type of dr is Base& as well br.f(); // prints "base" dr.f(); // prints "derived" // virtual function call through pointer Base* bp = &b; // the type of bp is Base* Base* dp = &d; // the type of dp is Base* as well bp->f(); // prints "base" dp->f(); // prints "derived" // non-virtual function call br.Base::f(); // prints "base" dr.Base::f(); // prints "base" } ``` ### In detail If some member function `vf` is declared as `virtual` in a class `Base`, and some class `Derived`, which is derived, directly or indirectly, from `Base`, has a declaration for member function with the same. * name * parameter type list (but not the return type) * cv-qualifiers * ref-qualifiers Then this function in the class `Derived` is also *virtual* (whether or not the keyword `virtual` is used in its declaration) and *overrides* Base::vf (whether or not the word `override` is used in its declaration). `Base::vf` does not need to be accessible or visible to be overridden. (`Base::vf` can be declared private, or `Base` can be inherited using private inheritance. Any members with the same name in a base class of `Derived` which inherits `Base` do not matter for override determination, even if they would hide `Base::vf` during name lookup.). ``` class B { virtual void do_f(); // private member public: void f() { do_f(); } // public interface }; struct D : public B { void do_f() override; // overrides B::do_f }; int main() { D d; B* bp = &d; bp->f(); // internally calls D::do_f(); } ``` For every virtual function, there is the *final overrider*, which is executed when a virtual function call is made. A virtual member function `vf` of a base class `Base` is the final overrider unless the derived class declares or inherits (through multiple inheritance) another function that overrides `vf`. ``` struct A { virtual void f(); }; // A::f is virtual struct B : A { void f(); }; // B::f overrides A::f in B struct C : virtual B { void f(); }; // C::f overrides A::f in C struct D : virtual B {}; // D does not introduce an overrider, B::f is final in D struct E : C, D // E does not introduce an overrider, C::f is final in E { using A::f; // not a function declaration, just makes A::f visible to lookup }; int main() { E e; e.f(); // virtual call calls C::f, the final overrider in e e.E::f(); // non-virtual call calls A::f, which is visible in E } ``` If a function has more than one final overrider, the program is ill-formed: ``` struct A { virtual void f(); }; struct VB1 : virtual A { void f(); // overrides A::f }; struct VB2 : virtual A { void f(); // overrides A::f }; // struct Error : VB1, VB2 // { // // Error: A::f has two final overriders in Error // }; struct Okay : VB1, VB2 { void f(); // OK: this is the final overrider for A::f }; struct VB1a : virtual A {}; // does not declare an overrider struct Da : VB1a, VB2 { // in Da, the final overrider of A::f is VB2::f }; ``` A function with the same name but different parameter list does not override the base function of the same name, but *hides* it: when [unqualified name lookup](lookup "cpp/language/lookup") examines the scope of the derived class, the lookup finds the declaration and does not examine the base class. ``` struct B { virtual void f(); }; struct D : B { void f(int); // D::f hides B::f (wrong parameter list) }; struct D2 : D { void f(); // D2::f overrides B::f (doesn't matter that it's not visible) }; int main() { B b; B& b_as_b = b; D d; B& d_as_b = d; D& d_as_d = d; D2 d2; B& d2_as_b = d2; D& d2_as_d = d2; b_as_b.f(); // calls B::f() d_as_b.f(); // calls B::f() d2_as_b.f(); // calls D2::f() d_as_d.f(); // Error: lookup in D finds only f(int) d2_as_d.f(); // Error: lookup in D finds only f(int) } ``` | | | | --- | --- | | If a function is declared with the specifier `override`, but does not override a virtual function, the program is ill-formed: ``` struct B { virtual void f(int); }; struct D : B { virtual void f(int) override; // OK, D::f(int) overrides B::f(int) virtual void f(long) override; // Error: f(long) does not override B::f(int) }; ``` If a function is declared with the specifier `final`, and another function attempts to override it, the program is ill-formed: ``` struct B { virtual void f() const final; }; struct D : B { void f() const; // Error: D::f attempts to override final B::f }; ``` | (since C++11) | Non-member functions and static member functions cannot be virtual. Function templates cannot be declared `virtual`. This applies only to functions that are themselves templates - a regular member function of a class template can be declared virtual. | | | | --- | --- | | Virtual functions (whether declared virtual or overriding one) cannot have any associated constraints. ``` struct A { virtual void f() requires true; // Error: constrained virtual function }; ``` A [`consteval`](consteval "cpp/language/consteval") virtual function must not override or be overidden by a non-`consteval` virtual function. | (since C++20) | [Default arguments](default_arguments "cpp/language/default arguments") for virtual functions are substituted at the compile time. #### Covariant return types If the function `Derived::f` overrides a function `Base::f`, their return types must either be the same or be *covariant*. Two types are covariant if they satisfy all of the following requirements: * both types are pointers or references (lvalue or rvalue) to classes. Multi-level pointers or references are not allowed. * the referenced/pointed-to class in the return type of `Base::f()` must be an unambiguous and accessible direct or indirect base class of the referenced/pointed-to class of the return type of `Derived::f()`. * the return type of `Derived::f()` must be equally or less [cv-qualified](cv "cpp/language/cv") than the return type of `Base::f()`. The class in the return type of `Derived::f` must be either `Derived` itself, or must be a [complete type](incomplete_type "cpp/language/incomplete type") at the point of declaration of `Derived::f`. When a virtual function call is made, the type returned by the final overrider is [implicitly converted](implicit_cast "cpp/language/implicit cast") to the return type of the overridden function that was called: ``` class B {}; struct Base { virtual void vf1(); virtual void vf2(); virtual void vf3(); virtual B* vf4(); virtual B* vf5(); }; class D : private B { friend struct Derived; // in Derived, B is an accessible base of D }; class A; // forward-declared class is an incomplete type struct Derived : public Base { void vf1(); // virtual, overrides Base::vf1() void vf2(int); // non-virtual, hides Base::vf2() // char vf3(); // Error: overrides Base::vf3, but has different // and non-covariant return type D* vf4(); // overrides Base::vf4() and has covariant return type // A* vf5(); // Error: A is incomplete type }; int main() { Derived d; Base& br = d; Derived& dr = d; br.vf1(); // calls Derived::vf1() br.vf2(); // calls Base::vf2() // dr.vf2(); // Error: vf2(int) hides vf2() B* p = br.vf4(); // calls Derived::vf4() and converts the result to B* D* q = dr.vf4(); // calls Derived::vf4() and does not convert the result to B* } ``` #### Virtual destructor Even though destructors are not inherited, if a base class declares its destructor `virtual`, the derived destructor always overrides it. This makes it possible to delete dynamically allocated objects of polymorphic type through pointers to base. ``` class Base { public: virtual ~Base() { /* releases Base's resources */ } }; class Derived : public Base { ~Derived() { /* releases Derived's resources */ } }; int main() { Base* b = new Derived; delete b; // Makes a virtual function call to Base::~Base() // since it is virtual, it calls Derived::~Derived() which can // release resources of the derived class, and then calls // Base::~Base() following the usual order of destruction } ``` Moreover, if the destructor of the base class is not virtual, deleting a derived class object through a pointer to the base class is *undefined behavior* regardless of whether there are resources that would be leaked if the derived destructor is not invoked, unless the selected deallocation function is a destroying `[operator delete](../memory/new/operator_delete "cpp/memory/new/operator delete")` (since C++20). A useful guideline is that the destructor of any base class must be [public and virtual or protected and non-virtual](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-dtor-virtual), whenever delete expressions are involved, e.g. when implicitly used in `[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")` (since C++11). ### During construction and destruction When a virtual function is called directly or indirectly from a constructor or from a destructor (including during the construction or destruction of the class’s non-static data members, e.g. in a member [initializer list](initializer_list "cpp/language/initializer list")), and the object to which the call applies is the object under construction or destruction, the function called is the final overrider in the constructor’s or destructor’s class and not one overriding it in a more-derived class. In other words, during construction or destruction, the more-derived classes do not exist. When constructing a complex class with multiple branches, within a constructor that belongs to one branch, polymorphism is restricted to that class and its bases: if it obtains a pointer or reference to a base subobject outside this subhierarchy, and attempts to invoke a virtual function call (e.g. using explicit member access), the behavior is undefined: ``` struct V { virtual void f(); virtual void g(); }; struct A : virtual V { virtual void f(); // A::f is the final overrider of V::f in A }; struct B : virtual V { virtual void g(); // B::g is the final overrider of V::g in B B(V*, A*); }; struct D : A, B { virtual void f(); // D::f is the final overrider of V::f in D virtual void g(); // D::g is the final overrider of V::g in D // note: A is initialized before B D() : B((A*) this, this) {} }; // the constructor of B, called from the constructor of D B::B(V* v, A* a) { f(); // virtual call to V::f (although D has the final overrider, D doesn't exist) g(); // virtual call to B::g, which is the final overrider in B v->g(); // v's type V is base of B, virtual call calls B::g as before a->f(); // a’s type A is not a base of B. it belongs to a different branch of the // hierarchy. Attempting a virtual call through that branch causes // undefined behavior even though A was already fully constructed in this // case (it was constructed before B since it appears before B in the list // of the bases of D). In practice, the virtual call to A::f will be // attempted using B's virtual member function table, since that's what // is active during B's construction) } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 258](https://cplusplus.github.io/CWG/issues/258.html) | C++98 | a non-const member function of a derived class might becomevirtual because of a const virtual member function of its base | virtuality also require cv-qualifications to be the same | | [CWG 477](https://cplusplus.github.io/CWG/issues/477.html) | C++98 | a friend declaration could contain the `virtual` specifier | not allowed | | [CWG 1516](https://cplusplus.github.io/CWG/issues/1516.html) | C++98 | the definition of the terms "virtual function call"and "virtual call" were not provided | provided | ### See also | | | --- | | [derived classes and modes of inheritance](derived_class "cpp/language/derived class") | | [`override` specifier](override "cpp/language/override")(C++11) | explicitly declares that a method overrides another method | | [`final` specifier](final "cpp/language/final")(C++11) | declares that a method cannot be overridden |
programming_docs
cpp Object Object ====== C++ programs create, destroy, refer to, access, and manipulate *objects*. An object, in C++, has. * size (can be determined with [`sizeof`](sizeof "cpp/language/sizeof")); * alignment requirement (can be determined with [`alignof`](alignof "cpp/language/alignof")); * [storage duration](storage_duration "cpp/language/storage duration") (automatic, static, dynamic, thread-local); * [lifetime](lifetime "cpp/language/lifetime") (bounded by storage duration or temporary); * [type](type "cpp/language/type"); * value (which may be indeterminate, e.g. for [default-initialized](default_initialization "cpp/language/default initialization") non-class types); * optionally, a [name](name "cpp/language/name"). The following entities are not objects: value, reference, function, enumerator, type, non-static class member, template, class or function template specialization, namespace, parameter pack, and `this`. A *variable* is an object or a reference that is not a non-static data member, that is introduced by a [declaration](declarations "cpp/language/declarations"). ### Object creation Objects can be explicitly created by [definitions](definition "cpp/language/definition"), [new-expressions](new "cpp/language/new"), [throw-expressions](throw "cpp/language/throw"), changing the active member of a [union](union "cpp/language/union") and evaluating expressions that require [temporary objects](lifetime#Temporary_object_lifetime "cpp/language/lifetime"). The created object is uniquely defined in explicit object creation. Objects of [implicit-lifetime types](../named_req/implicitlifetimetype "cpp/named req/ImplicitLifetimeType") can also be implicitly created by. * operations that begin lifetime of an array of type `char`, `unsigned char`, or [`std::byte`](../types/byte "cpp/types/byte"), (since C++17) in which case such objects are created in the array, * call to following allocating functions, in which case such objects are created in the allocated storage: + `[operator new](../memory/new/operator_new "cpp/memory/new/operator new")` + `[operator new[]](../memory/new/operator_new "cpp/memory/new/operator new")` + `[std::malloc](../memory/c/malloc "cpp/memory/c/malloc")` + `[std::calloc](../memory/c/calloc "cpp/memory/c/calloc")` + `[std::realloc](../memory/c/realloc "cpp/memory/c/realloc")` | | | | --- | --- | | * `[std::aligned\_alloc](../memory/c/aligned_alloc "cpp/memory/c/aligned alloc")` | (since C++17) | * call to following [object representation](#Object_representation_and_value_representation) copying functions, in which case such objects are created in the destination region of storage or the result: + `[std::memcpy](../string/byte/memcpy "cpp/string/byte/memcpy")` + `[std::memmove](../string/byte/memmove "cpp/string/byte/memmove")` | | | | --- | --- | | * [`std::bit_cast`](../numeric/bit_cast "cpp/numeric/bit cast") | (since C++20) | Zero or more objects may be created in the same region of storage, as long as doing so would give the program defined behavior. If such creation is impossible, e.g. due to conflicting operations, the behavior of the program is undefined. If multiple such sets of implicitly created objects would give the program defined behavior, it is unspecified which such set of objects is created. In other words, implicitly created objects are not required to be uniquely defined. After implicitly creating objects within a specified region of storage, some operations produce a pointer to a *suitable created object*. The suitable created object has the same address as the region of storage. Likewise, the behavior is undefined if only if no such pointer value can give the program defined behavior, and it is unspecified which pointer value is produced if there are multiple values giving the program defined behavior. ``` #include <cstdlib> struct X { int a, b; }; X* MakeX() { // One of possible defined behaviors: // the call to std::malloc implicitly creates an object of type X // and its subobjects a and b, and returns a pointer to that X object X* p = static_cast<X*>(std::malloc(sizeof(X))); p->a = 1; p->b = 2; return p; } ``` Call to `[std::allocator::allocate](../memory/allocator/allocate "cpp/memory/allocator/allocate")` or implicitly defined copy/move special member functions of [union](union "cpp/language/union") types can also create objects. ### Object representation and value representation For an object of type `T`: * its *object representation* is the sequence of `sizeof(T)` objects of type `unsigned char` (or, equivalently, [`std::byte`](../types/byte "cpp/types/byte")) (since C++17) beginning at the same address as the `T` object, * its *value representation* is the set of bits that hold the value of its type `T`, and * its *padding bits* are the bits in the object representation that are not part of the value representation. For [trivially copyable types](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"), value representation is a part of the object representation, which means that copying the bytes occupied by the object in the storage is sufficient to produce another object with the same value (except if the value is a *trap representation* of its type and loading it into the CPU raises a hardware exception, such as SNaN ("signalling not-a-number") floating-point values or NaT ("not-a-thing") integers). The reverse is not necessarily true: two objects of a [trivially copyable type](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") with different object representations may represent the same value. For example, multiple floating-point bit patterns represent the same special value [NaN](../numeric/math/nan "cpp/numeric/math/NAN"). More commonly, padding bits may be introduced to satisfy [alignment requirements](object#Alignment "cpp/language/object"), [bit-field](bit_field "cpp/language/bit field") sizes, etc. ``` #include <cassert> struct S { char c; // 1 byte value // 3 bytes of padding bits (assuming alignof(float) == 4) float f; // 4 bytes value (assuming sizeof(float) == 4) bool operator==(const S& arg) const // value-based equality { return c == arg.c && f == arg.f; } }; void f() { assert(sizeof(S) == 8); S s1 = {'a', 3.14}; S s2 = s1; reinterpret_cast<unsigned char*>(&s1)[2] = 'b'; // modify some padding bits assert(s1 == s2); // value did not change } ``` For the objects of type `char`, `signed char`, and `unsigned char` (unless they are oversize [bit-fields](bit_field "cpp/language/bit field")), every bit of the object representation is required to participate in the value representation and each possible bit pattern represents a distinct value (no padding bits, trap bits, or multiple representations allowed). ### Subobjects An object can have *subobjects*. These include. * member objects * base class subobjects * array elements An object that is not a subobject of another object is called *complete object*. A subobject is *potentially overlapping* if it is a base class subobject or a non-static data member declared with the `[[[no\_unique\_address](attributes/no_unique_address "cpp/language/attributes/no unique address")]]` attribute (since C++20). Complete objects, member objects, and array elements are also known as *most derived objects*, to distinguish them from base class subobjects. The size of an object that is neither potentially overlapping nor a [bit-field](bit_field "cpp/language/bit field") is required to be non-zero (the size of a base class subobject may be zero even without `[[no_unique_address]]` (since C++20): see [empty base optimization](ebo "cpp/language/ebo")). An object can contain other objects, in which case the contained objects are *nested within* the former object. An object `a` is nested within another object `b` if. * `a` is a subobject of `b`, or * `b` provides storage for `a`, or * there exists an object `c` where `a` is nested within `c`, and `c` is nested within `b`. Any two objects with overlapping [lifetimes](lifetime "cpp/language/lifetime") (that are not [bit-fields](bit_field "cpp/language/bit field")) are guaranteed to have different addresses unless one of them is nested within another, or if they are subobjects of different type within the same complete object, and one of them is a subobject of zero size. ``` static const char c1 = 'x'; static const char c2 = 'x'; assert(&c1 != &c2); // same values, different addresses ``` ### Polymorphic objects Objects of a class type that declares or inherits at least one virtual function are polymorphic objects. Within each polymorphic object, the implementation stores additional information (in every existing implementation, it is one pointer unless optimized out), which is used by [virtual function](virtual "cpp/language/virtual") calls and by the RTTI features ([`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") and [`typeid`](typeid "cpp/language/typeid")) to determine, at run time, the type with which the object was created, regardless of the expression it is used in. For non-polymorphic objects, the interpretation of the value is determined from the expression in which the object is used, and is decided at compile time. ``` #include <iostream> #include <typeinfo> struct Base1 { // polymorphic type: declares a virtual member virtual ~Base1() {} }; struct Derived1 : Base1 { // polymorphic type: inherits a virtual member }; struct Base2 { // non-polymorphic type }; struct Derived2 : Base2 { // non-polymorphic type }; int main() { Derived1 obj1; // object1 created with type Derived1 Derived2 obj2; // object2 created with type Derived2 Base1& b1 = obj1; // b1 refers to the object obj1 Base2& b2 = obj2; // b2 refers to the object obj2 std::cout << "Expression type of b1: " << typeid(decltype(b1)).name() << '\n' << "Expression type of b2: " << typeid(decltype(b2)).name() << '\n' << "Object type of b1: " << typeid(b1).name() << '\n' << "Object type of b2: " << typeid(b2).name() << '\n' << "Size of b1: " << sizeof b1 << '\n' << "Size of b2: " << sizeof b2 << '\n'; } ``` Possible output: ``` Expression type of b1: Base1 Expression type of b2: Base2 Object type of b1: Derived1 Object type of b2: Base2 Size of b1: 8 Size of b2: 1 ``` ### Strict aliasing Accessing an object using an expression of a type other than the type with which it was created is undefined behavior in many cases, see [`reinterpret_cast`](reinterpret_cast#Type_aliasing "cpp/language/reinterpret cast") for the list of exceptions and examples. ### Alignment Every [object type](type "cpp/language/type") has the property called *alignment requirement*, which is an integer value (of type `[std::size\_t](../types/size_t "cpp/types/size t")`, always a power of 2) representing the number of bytes between successive addresses at which objects of this type can be allocated. | | | | --- | --- | | The alignment requirement of a type can be queried with [`alignof`](alignof "cpp/language/alignof") or `[std::alignment\_of](../types/alignment_of "cpp/types/alignment of")`. The pointer alignment function `[std::align](../memory/align "cpp/memory/align")` can be used to obtain a suitably-aligned pointer within some buffer, and `[std::aligned\_storage](../types/aligned_storage "cpp/types/aligned storage")` can be used to obtain suitably-aligned storage. | (since C++11) | Each object type imposes its alignment requirement on every object of that type; stricter alignment (with larger alignment requirement) can be requested using [`alignas`](alignas "cpp/language/alignas") (since C++11). In order to satisfy alignment requirements of all non-static members of a [class](class "cpp/language/class"), [padding bits](#Object_representation_and_value_representation) may be inserted after some of its members. ``` #include <iostream> // objects of type S can be allocated at any address // because both S.a and S.b can be allocated at any address struct S { char a; // size: 1, alignment: 1 char b; // size: 1, alignment: 1 }; // size: 2, alignment: 1 // objects of type X must be allocated at 4-byte boundaries // because X.n must be allocated at 4-byte boundaries // because int's alignment requirement is (usually) 4 struct X { int n; // size: 4, alignment: 4 char c; // size: 1, alignment: 1 // three bytes of padding bits }; // size: 8, alignment: 4 int main() { std::cout << "sizeof(S) = " << sizeof(S) << " alignof(S) = " << alignof(S) << '\n'; std::cout << "sizeof(X) = " << sizeof(X) << " alignof(X) = " << alignof(X) << '\n'; } ``` Possible output: ``` sizeof(S) = 2 alignof(S) = 1 sizeof(X) = 8 alignof(X) = 4 ``` The weakest alignment (the smallest alignment requirement) is the alignment of `char`, `signed char`, and `unsigned char`, which equals 1; the largest *fundamental alignment* of any type is implementation-defined and equal to the alignment of `[std::max\_align\_t](../types/max_align_t "cpp/types/max align t")` (since C++11). | | | | --- | --- | | If a type's alignment is made stricter (larger) than `[std::max\_align\_t](../types/max_align_t "cpp/types/max align t")` using [`alignas`](alignas "cpp/language/alignas"), it is known as a type with *extended alignment* requirement. A type whose alignment is extended or a class type whose non-static data member has extended alignment is an *over-aligned type*. [Allocator](../named_req/allocator "cpp/named req/Allocator") types are required to handle over-aligned types correctly. | (since C++11) | | | | | --- | --- | | It is implementation-defined if [new-expressions](new "cpp/language/new") and (until C++17) `[std::get\_temporary\_buffer](../memory/get_temporary_buffer "cpp/memory/get temporary buffer")` support over-aligned types. | (since C++11)(until C++20) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 633](https://cplusplus.github.io/CWG/issues/633.html) | C++98 | variables could only be objects | they can also be references | | [CWG 734](https://cplusplus.github.io/CWG/issues/734.html) | C++98 | it was unspecified whether variables definedin the same scope that are guaranteed to havethe same value can have the same address | address is guauanteed to bedifferent if their lifetimes overlap,regardless of their values | | [CWG 1189](https://cplusplus.github.io/CWG/issues/1189.html) | C++98 | two base class subobjects of the sametype could have the same address | they always have distinct addresses | | [CWG 1861](https://cplusplus.github.io/CWG/issues/1861.html) | C++98 | for oversize bit-fields of narrow character types, all bits of theobject representation still participated in the value representation | allowed padding bits | | [P0593R6](https://wg21.link/P0593R6) | C++98 | previous object model did not support manyuseful idioms required by the standard libraryand was not compatible with effective types in C | implicit object creation added | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/object "c/language/object") for Object | cpp Class declaration Class declaration ================= Classes are user-defined types, defined by class-specifier, which appears in decl-specifier-seq of the [declaration](declarations "cpp/language/declarations") syntax. The class specifier has the following syntax: | | | | | --- | --- | --- | | class-key attr(optional) class-head-name `final`(optional) base-clause(optional) `{` member-specification `}` | (1) | | | class-key attr(optional) base-clause(optional) `{` member-specification `}` | (2) | | 1) named class definition 2) unnamed class definition | | | | | --- | --- | --- | | class-key | - | one of [`class`](../keyword/class "cpp/keyword/class"), [`struct`](../keyword/struct "cpp/keyword/struct") and [`union`](../keyword/union "cpp/keyword/union"). The keywords `class` and `struct` are identical except for the default [member access](access "cpp/language/access") and the default [base class access](derived_class "cpp/language/derived class"). If it is `union`, the declaration introduces a [union type](union "cpp/language/union"). | | attr | - | (since C++11) any number of [attributes](attributes "cpp/language/attributes"), may include [`alignas`](alignas "cpp/language/alignas") specifier | | class-head-name | - | the name of the class that's being defined, optionally [qualified](identifiers#Qualified_identifiers "cpp/language/identifiers") | | `final` | - | (since C++11) if present, the class [cannot be derived](final "cpp/language/final") | | base-clause | - | list of one or more base classes and the model of inheritance used for each (see [derived class](derived_class "cpp/language/derived class")) | | member-specification | - | list of access specifiers, member object and member function declarations and definitions ([see below](#Member_specification)). | ### Forward declaration A declaration of the following form. | | | | | --- | --- | --- | | class-key attr identifier `;` | | | Declares a class type which will be defined later in this scope. Until the definition appears, this class name has [incomplete type](incomplete_type "cpp/language/incomplete type"). This allows classes that refer to each other: ``` class Vector; // forward declaration class Matrix { // ... friend Vector operator*(const Matrix&, const Vector&); }; class Vector { // ... friend Vector operator*(const Matrix&, const Vector&); }; ``` and if a particular source file only uses pointers and references to the class, this makes it possible to reduce #include dependencies: ``` // in MyStruct.h #include <iosfwd> // contains forward declaration of std::ostream struct MyStruct { int value; friend std::ostream& operator<<(std::ostream& os, const S& s); // definition provided in MyStruct.cpp file which uses #include <ostream> }; ``` If forward declaration appears in local scope, it *hides* previously declared class, variable, function, and all other declarations of the same name that may appear in enclosing scopes: ``` struct s { int a; }; struct s; // does nothing (s already defined in this scope) void g() { struct s; // forward declaration of a new, local struct "s" // this hides global struct s until the end of this block s* p; // pointer to local struct s struct s { char* p; }; // definitions of the local struct s } ``` Note that a new class name may also be introduced by an [elaborated type specifier](elaborated_type_specifier "cpp/language/elaborated type specifier") which appears as part of another declaration, but only if [name lookup](lookup "cpp/language/lookup") can't find a previously declared class with the same name. ``` class U; namespace ns { class Y f(class T p); // declares function ns::f and declares ns::T and ns::Y class U f(); // U refers to ::U // can use pointers and references to T and Y Y* p; T* q; } ``` ### Member specification The member specification, or the *body* of a class definition, is a brace-enclosed sequence of any number of the following: 1) Member declarations of the form | | | | | --- | --- | --- | | attr(optional) decl-specifier-seq(optional) member-declarator-list(optional) `;` | | | | | | | | --- | --- | --- | | attr | - | (since C++11) any number of [attributes](attributes "cpp/language/attributes") | | decl-specifier-seq | - | sequence of [specifiers](declarations#Specifiers "cpp/language/declarations"). It is only optional in the declarations of constructors, destructors, and user-defined type [conversion functions](cast_operator "cpp/language/cast operator") | | member-declarator-list | - | similar to a [init-declarator-list](declarations "cpp/language/declarations"), but additionally allows [bit-field declaration](bit_field "cpp/language/bit field"), [pure-specifier](abstract_class "cpp/language/abstract class"), and virt-specifier (`[override](override "cpp/language/override")` or `[final](final "cpp/language/final")`) (since C++11), and does not allow [direct-non-list-initialization syntax](direct_initialization "cpp/language/direct initialization"). | This declaration may declare [static](static "cpp/language/static") and non-static [data members](data_members "cpp/language/data members") and [member functions](member_functions "cpp/language/member functions"), member [typedefs](typedef "cpp/language/typedef"), member [enumerations](enum "cpp/language/enum"), and [nested classes](nested_classes "cpp/language/nested classes"). It may also be a [friend declaration](friend "cpp/language/friend"). ``` class S { int d1; // non-static data member int a[10] = {1,2}; // non-static data member with initializer (C++11) static const int d2 = 1; // static data member with initializer virtual void f1(int) = 0; // pure virtual member function std::string d3, *d4, f2(int); // two data members and a member function enum {NORTH, SOUTH, EAST, WEST}; struct NestedS { std::string s; } d5, *d6; typedef NestedS value_type, *pointer_type; }; ``` 2) Function definitions, which both declare and define [member functions](member_functions "cpp/language/member functions") or [friend functions](friend "cpp/language/friend"). A semicolon after a member function definition is optional. All functions that are defined inside a class body are automaticaly [inline](inline "cpp/language/inline"), unless they are attached to a [named module](modules "cpp/language/modules") (since C++20). ``` class M { std::size_t C; std::vector<int> data; public: M(std::size_t R, std::size_t C) : C(C), data(R*C) {} // constructor definition int operator()(size_t r, size_t c) const // member function definition { return data[r * C + c]; } int& operator()(size_t r, size_t c) // another member function definition { return data[r * C + c]; } }; ``` 3) [Access specifiers](access "cpp/language/access") `public:`, `protected:`, and `private:` ``` class S { public: S(); // public constructor S(const S&); // public copy constructor virtual ~S(); // public virtual destructor private: int* ptr; // private data member }; ``` 4) [Using-declarations](using_declaration "cpp/language/using declaration"): ``` class Base { protected: int d; }; class Derived : public Base { public: using Base::d; // make Base's protected member d a public member of Derived using Base::Base; // inherit all bases' constructors (C++11) }; ``` 5) [`static_assert`](static_assert "cpp/language/static assert") declarations: ``` template<typename T> struct Foo { static_assert(std::is_floating_point<T>::value, "Foo<T>: T must be floating point"); }; ``` 6) [member template declarations](member_template "cpp/language/member template"): ``` struct S { template<typename T> void f(T&& n); template<class CharT> struct NestedS { std::basic_string<CharT> s; }; }; ``` | | | | --- | --- | | 7) [alias declarations](type_alias "cpp/language/type alias"): ``` template<typename T> struct identity { using type = T; }; ``` | (since C++11) | | | | | --- | --- | | 8) [deduction guides](deduction_guide "cpp/language/deduction guide") of member class templates: ``` struct S { template<class CharT> struct NestedS { std::basic_string<CharT> s; }; template<class CharT> NestedS(std::basic_string<CharT>) -> NestedS<CharT>; }; ``` | (since C++17) | | | | | --- | --- | | 9) [Using-enum-declarations](enum#Using-enum-declaration "cpp/language/enum"): ``` enum class color { red, orange, yellow }; struct highlight { using enum color; }; ``` | (since C++20) | ### Local classes A class declaration can appear inside the body of a function, in which case it defines a *local class*. The name of such a class only exists within the function scope, and is not accessible outside. * A local class cannot have static data members * Member functions of a local class have no linkage * Member functions of a local class have to be defined entirely inside the class body * Local classes other than [closure types](lambda "cpp/language/lambda") (since C++14) cannot have member templates * Local classes cannot have [friend templates](friend#Template_friends "cpp/language/friend") * Local classes cannot define [friend functions](friend "cpp/language/friend") inside the class definition * A local class inside a function (including member function) can access the same names that the enclosing function can access. | | | | --- | --- | | * local classes could not be used as template arguments | (until C++11) | ``` #include <vector> #include <algorithm> #include <iostream> int main() { std::vector<int> v{1, 2, 3}; struct Local { bool operator()(int n, int m) { return n > m; } }; std::sort(v.begin(), v.end(), Local()); // since C++11 for (int n : v) std::cout << n << ' '; } ``` Output: ``` 3 2 1 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1693](https://cplusplus.github.io/CWG/issues/1693.html) | C++98 | member declarations could not be empty | empty declaration allowed | | [CWG 1930](https://cplusplus.github.io/CWG/issues/1930.html) | C++98 | member-declarator-list could be empty when decl-specifier-seqcontains a storage class specifier or cv qualifier | the list must not be empty | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/struct "c/language/struct") for `Struct declaration` |
programming_docs
cpp Reference declaration Reference declaration ===================== Declares a named variable as a reference, that is, an alias to an already-existing object or function. ### Syntax A reference variable declaration is any simple declaration whose [declarator](declarations "cpp/language/declarations") has the form. | | | | | --- | --- | --- | | `&` attr(optional) declarator | (1) | | | `&&` attr(optional) declarator | (2) | (since C++11) | 1) **Lvalue reference declarator**: the declaration `S& D;` declares `D` as an *lvalue reference* to the type determined by decl-specifier-seq `S`. 2) **Rvalue reference declarator**: the declaration `S&& D;` declares `D` as an *rvalue reference* to the type determined by decl-specifier-seq `S`. | | | | | --- | --- | --- | | declarator | - | any [declarator](declarations "cpp/language/declarations") except another reference declarator (there are no references to references) | | attr | - | (since C++11) list of [attributes](attributes "cpp/language/attributes") | A reference is required to be initialized to refer to a valid object or function: see [reference initialization](reference_initialization "cpp/language/reference initialization"). There are no references to `void` and no references to references. Reference types cannot be [cv-qualified](cv "cpp/language/cv") at the top level; there is no syntax for that in declaration, and if a qualification is added to a typedef-name or [`decltype`](decltype "cpp/language/decltype") specifier, (since C++11) or [type template parameter](template_parameters#Type_template_parameter "cpp/language/template parameters"), it is ignored. References are not objects; they do not necessarily occupy storage, although the compiler may allocate storage if it is necessary to implement the desired semantics (e.g. a non-static data member of reference type usually increases the size of the class by the amount necessary to store a memory address). Because references are not objects, there are no arrays of references, no pointers to references, and no references to references: ``` int& a[3]; // error int&* p; // error int& &r; // error ``` | | | | --- | --- | | Reference collapsing It is permitted to form references to references through type manipulations in templates or typedefs, in which case the *reference collapsing* rules apply: rvalue reference to rvalue reference collapses to rvalue reference, all other combinations form lvalue reference: ``` typedef int& lref; typedef int&& rref; int n; lref& r1 = n; // type of r1 is int& lref&& r2 = n; // type of r2 is int& rref& r3 = n; // type of r3 is int& rref&& r4 = 1; // type of r4 is int&& ``` (This, along with special rules for [template argument deduction](template_argument_deduction "cpp/language/template argument deduction") when `T&&` is used in a function template, forms the rules that make `[std::forward](../utility/forward "cpp/utility/forward")` possible.). | (since C++11) | #### Lvalue references Lvalue references can be used to alias an existing object (optionally with different cv-qualification): ``` #include <iostream> #include <string> int main() { std::string s = "Ex"; std::string& r1 = s; const std::string& r2 = s; r1 += "ample"; // modifies s // r2 += "!"; // error: cannot modify through reference to const std::cout << r2 << '\n'; // prints s, which now holds "Example" } ``` They can also be used to implement pass-by-reference semantics in function calls: ``` #include <iostream> #include <string> void double_string(std::string& s) { s += s; // 's' is the same object as main()'s 'str' } int main() { std::string str = "Test"; double_string(str); std::cout << str << '\n'; } ``` When a function's return type is lvalue reference, the function call expression becomes an [lvalue](value_category#lvalue "cpp/language/value category") expression: ``` #include <iostream> #include <string> char& char_number(std::string& s, std::size_t n) { return s.at(n); // string::at() returns a reference to char } int main() { std::string str = "Test"; char_number(str, 1) = 'a'; // the function call is lvalue, can be assigned to std::cout << str << '\n'; } ``` | | | | --- | --- | | Rvalue references Rvalue references can be used to [extend the lifetimes](reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization") of temporary objects (note, lvalue references to const can extend the lifetimes of temporary objects too, but they are not modifiable through them): ``` #include <iostream> #include <string> int main() { std::string s1 = "Test"; // std::string&& r1 = s1; // error: can't bind to lvalue const std::string& r2 = s1 + s1; // okay: lvalue reference to const extends lifetime // r2 += "Test"; // error: can't modify through reference to const std::string&& r3 = s1 + s1; // okay: rvalue reference extends lifetime r3 += "Test"; // okay: can modify through reference to non-const std::cout << r3 << '\n'; } ``` More importantly, when a function has both rvalue reference and lvalue reference [overloads](overload_resolution "cpp/language/overload resolution"), the rvalue reference overload binds to rvalues (including both prvalues and xvalues), while the lvalue reference overload binds to lvalues: ``` #include <iostream> #include <utility> void f(int& x) { std::cout << "lvalue reference overload f(" << x << ")\n"; } void f(const int& x) { std::cout << "lvalue reference to const overload f(" << x << ")\n"; } void f(int&& x) { std::cout << "rvalue reference overload f(" << x << ")\n"; } int main() { int i = 1; const int ci = 2; f(i); // calls f(int&) f(ci); // calls f(const int&) f(3); // calls f(int&&) // would call f(const int&) if f(int&&) overload wasn't provided f(std::move(i)); // calls f(int&&) // rvalue reference variables are lvalues when used in expressions int&& x = 1; f(x); // calls f(int& x) f(std::move(x)); // calls f(int&& x) } ``` This allows [move constructors](move_constructor "cpp/language/move constructor"), [move assignment](move_assignment "cpp/language/move assignment") operators, and other move-aware functions (e.g. `[std::vector::push\_back()](../container/vector/push_back "cpp/container/vector/push back")`) to be automatically selected when suitable. Because rvalue references can bind to xvalues, they can refer to non-temporary objects: ``` int i2 = 42; int&& rri = std::move(i2); // binds directly to i2 ``` This makes it possible to move out of an object in scope that is no longer needed: ``` std::vector<int> v{1, 2, 3, 4, 5}; std::vector<int> v2(std::move(v)); // binds an rvalue reference to v assert(v.empty()); ``` Forwarding references Forwarding references are a special kind of references that preserve the value category of a function argument, making it possible to *forward* it by means of `[std::forward](../utility/forward "cpp/utility/forward")`. Forwarding references are either: 1) function parameter of a function template declared as rvalue reference to cv-unqualified [type template parameter](template_parameters#Type_template_parameter "cpp/language/template parameters") of that same function template: ``` template<class T> int f(T&& x) // x is a forwarding reference { return g(std::forward<T>(x)); // and so can be forwarded } int main() { int i; f(i); // argument is lvalue, calls f<int&>(int&), std::forward<int&>(x) is lvalue f(0); // argument is rvalue, calls f<int>(int&&), std::forward<int>(x) is rvalue } template<class T> int g(const T&& x); // x is not a forwarding reference: const T is not cv-unqualified template<class T> struct A { template<class U> A(T&& x, U&& y, int* p); // x is not a forwarding reference: T is not a // type template parameter of the constructor, // but y is a forwarding reference }; ``` 2) `auto&&` except when deduced from a brace-enclosed initializer list: ``` auto&& vec = foo(); // foo() may be lvalue or rvalue, vec is a forwarding reference auto i = std::begin(vec); // works either way (*i)++; // works either way g(std::forward<decltype(vec)>(vec)); // forwards, preserving value category for (auto&& x: f()) { // x is a forwarding reference; this is the safest way to use range for loops } auto&& z = {1, 2, 3}; // *not* a forwarding reference (special case for initializer lists) ``` See also [template argument deduction](template_argument_deduction#Deduction_from_a_function_call "cpp/language/template argument deduction") and `[std::forward](../utility/forward "cpp/utility/forward")`. | (since C++11) | #### Dangling references Although references, once initialized, always refer to valid objects or functions, it is possible to create a program where the [lifetime](lifetime "cpp/language/lifetime") of the referred-to object ends, but the reference remains accessible (*dangling*). Accessing such a reference is undefined behavior. A common example is a function returning a reference to an automatic variable: ``` std::string& f() { std::string s = "Example"; return s; // exits the scope of s: // its destructor is called and its storage deallocated } std::string& r = f(); // dangling reference std::cout << r; // undefined behavior: reads from a dangling reference std::string s = f(); // undefined behavior: copy-initializes from a dangling reference ``` Note that rvalue references and lvalue references to const extend the lifetimes of temporary objects (see [Reference initialization](reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization") for rules and exceptions). If the referred-to object was destroyed (e.g. by explicit destructor call), but the storage was not deallocated, a reference to the out-of-lifetime object may be used in limited ways, and may become valid if the object is recreated in the same storage (see [Access outside of lifetime](lifetime#Access_outside_of_lifetime "cpp/language/lifetime") for details). ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1510](https://cplusplus.github.io/CWG/issues/1510.html) | C++11 | cv-qualified references could not be formed in the operand of `decltype` | allowed | ### External links * Thomas Becker, 2013 - [C++ Rvalue References Explained](http://thbecker.net/articles/rvalue_references/section_01.html) cpp Empty base optimization Empty base optimization ======================= Allows the size of an empty base subobject to be zero. ### Explanation The size of any [object](object "cpp/language/object") or member subobject is required to be at least 1 even if the type is an empty [class type](class "cpp/language/class") (that is, a class or struct that has no non-static data members), (unless with `[[[no\_unique\_address](attributes/no_unique_address "cpp/language/attributes/no unique address")]]`, see below) (since C++20) in order to be able to guarantee that the addresses of distinct objects of the same type are always distinct. However, base class subobjects are not so constrained, and can be completely optimized out from the object layout: ``` struct Base {}; // empty class struct Derived1 : Base { int i; }; int main() { // the size of any object of empty class type is at least 1 static_assert(sizeof(Base) >= 1); // empty base optimization applies static_assert(sizeof(Derived1) == sizeof(int)); } ``` Empty base optimization is prohibited if one of the empty base classes is also the type or the base of the type of the first non-static data member, since the two base subobjects of the same type are required to have different addresses within the object representation of the most derived type. A typical example of such situation is the naive implementation of `[std::reverse\_iterator](../iterator/reverse_iterator "cpp/iterator/reverse iterator")` (derived from the empty base `[std::iterator](../iterator/iterator "cpp/iterator/iterator")`), which holds the underlying iterator (also derived from `[std::iterator](../iterator/iterator "cpp/iterator/iterator")`) as its first non-static data member. ``` struct Base {}; // empty class struct Derived1 : Base { int i; }; struct Derived2 : Base { Base c; // Base, occupies 1 byte, followed by padding for i int i; }; struct Derived3 : Base { Derived1 c; // derived from Base, occupies sizeof(int) bytes int i; }; int main() { // empty base optimization does not apply, // base occupies 1 byte, Base member occupies 1 byte // followed by 2 bytes of padding to satisfy int alignment requirements static_assert(sizeof(Derived2) == 2*sizeof(int)); // empty base optimization does not apply, // base takes up at least 1 byte plus the padding // to satisfy alignment requirement of the first member (whose // alignment is the same as int) static_assert(sizeof(Derived3) == 3*sizeof(int)); } ``` | | | | --- | --- | | Empty base optimization is *required* for [StandardLayoutTypes](../named_req/standardlayouttype "cpp/named req/StandardLayoutType") in order to maintain the requirement that the pointer to a standard-layout object, converted using [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast"), points to its initial member, which is why the requirements for a standard layout type include "has all non-static data members declared in the same class (either all in the derived or all in some base)" and "has no base classes of the same type as the first non-static data member". | (since C++11) | | | | | --- | --- | | The empty member subobjects are permitted to be optimized out just like the empty bases if they use the attribute `[[[no\_unique\_address](attributes/no_unique_address "cpp/language/attributes/no unique address")]]`. Taking the address of such member results in an address that may equal the address of some other member of the same object. ``` struct Empty {}; // empty class struct X { int i; [[no_unique_address]] Empty e; }; int main() { // the size of any object of empty class type is at least 1 static_assert(sizeof(Empty) >= 1); // empty member optimized out: static_assert(sizeof(X) == sizeof(int)); } ``` | (since C++20) | ### Notes Empty base optimization is commonly used by allocator-aware standard library classes (`[std::vector](../container/vector "cpp/container/vector")`, `[std::function](../utility/functional/function "cpp/utility/functional/function")`, `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")`, etc) to avoid occupying any additional storage for its allocator member if the allocator is stateless. This is achieved by storing one of the required data members (e.g., `begin`, `end`, or `capacity` pointer for the `vector`) in an equivalent of [`boost::compressed_pair`](https://www.boost.org/doc/libs/release/libs/utility/doc/html/boost/compressed_pair.html) with the allocator. ### References * C++20 standard (ISO/IEC 14882:2020): + 7.6.10 Equality operators [expr.eq] + 7.6.2.4 Sizeof [expr.sizeof] + 11 Classes [class] + 11.4 Class members [class.mem] * C++17 standard (ISO/IEC 14882:2017): + 8.10 Equality operators [expr.eq] + 8.3.3 Sizeof [expr.sizeof] + 12 Classes [class] + 12.2 Class members [class.mem] * C++14 standard (ISO/IEC 14882:2014): + 5.10 Equality operators [expr.eq] + 5.3.3 Sizeof [expr.sizeof] + 9 Classes [class] + 9.2 Class members [class.mem] * C++11 standard (ISO/IEC 14882:2011): + 5.10 Equality operators [expr.eq] (p: 2) + 5.3.3 Sizeof [expr.sizeof] (p: 2) + 9 Classes [class] (p: 4,7) + 9.2 Class members [class.mem] (p: 20) * C++98 standard (ISO/IEC 14882:1998): + 5.10 Equality operators [expr.eq] (p: 2) + 5.3.3 Sizeof [expr.sizeof] (p: 2) + 9 Classes [class] (p: 3) ### External links * [More C++ Idioms/Empty Base Optimization](https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Empty_Base_Optimization) cpp RAII RAII ==== *Resource Acquisition Is Initialization* or RAII, is a C++ programming technique[[1]](#cite_note-1)[[2]](#cite_note-2) which binds the life cycle of a resource that must be acquired before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, database connection—anything that exists in limited supply) to the [lifetime](lifetime "cpp/language/lifetime") of an object. RAII guarantees that the resource is available to any function that may access the object (resource availability is a [class invariant](https://en.wikipedia.org/wiki/Class_invariant "enwiki:Class invariant"), eliminating redundant runtime tests). It also guarantees that all resources are released when the lifetime of their controlling object ends, in reverse order of acquisition. Likewise, if resource acquisition fails (the constructor exits with an exception), all resources acquired by every fully-constructed member and base subobject are released in reverse order of initialization. This leverages the core language features ([object lifetime](lifetime "cpp/language/lifetime"), [scope exit](statements "cpp/language/statements"), [order of initialization](initializer_list#Initialization_order "cpp/language/initializer list") and [stack unwinding](throw#Stack_unwinding "cpp/language/throw")) to eliminate resource leaks and guarantee exception safety. Another name for this technique is *Scope-Bound Resource Management* (SBRM), after the basic use case where the lifetime of an RAII object ends due to scope exit. RAII can be summarized as follows: * encapsulate each resource into a class, where + the constructor acquires the resource and establishes all class invariants or throws an exception if that cannot be done, + the destructor releases the resource and never throws exceptions; * always use the resource via an instance of a RAII-class that either + has automatic storage duration or temporary lifetime itself, or + has lifetime that is bounded by the lifetime of an automatic or temporary object | | | | --- | --- | | Move semantics make it possible to safely transfer resource ownership between objects, across scopes, and in and out of threads, while maintaining resource safety. | (since C++11) | Classes with `open()`/`close()`, `lock()`/`unlock()`, or `init()`/`copyFrom()`/`destroy()` member functions are typical examples of non-RAII classes: ``` std::mutex m; void bad() { m.lock(); // acquire the mutex f(); // if f() throws an exception, the mutex is never released if(!everything_ok()) return; // early return, the mutex is never released m.unlock(); // if bad() reaches this statement, the mutex is released } void good() { std::lock_guard<std::mutex> lk(m); // RAII class: mutex acquisition is initialization f(); // if f() throws an exception, the mutex is released if(!everything_ok()) return; // early return, the mutex is released } // if good() returns normally, the mutex is released ``` ### The standard library The C++ library classes that manage their own resources follow RAII: `[std::string](../string/basic_string "cpp/string/basic string")`, `[std::vector](../container/vector "cpp/container/vector")`, `[std::jthread](../thread/jthread "cpp/thread/jthread")` (since C++20), and many others acquire their resources in constructors (which throw exceptions on errors), release them in their destructors (which never throw), and don't require explicit cleanup. | | | | --- | --- | | In addition, the standard library offers several RAII wrappers to manage user-provided resources:* `[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")` and `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` to manage dynamically-allocated memory or, with a user-provided deleter, any resource represented by a plain pointer; * `[std::lock\_guard](../thread/lock_guard "cpp/thread/lock guard")`, `[std::unique\_lock](../thread/unique_lock "cpp/thread/unique lock")`, `[std::shared\_lock](../thread/shared_lock "cpp/thread/shared lock")` to manage mutexes. | (since C++11) | ### Notes RAII does not apply to the management of the resources that are not acquired before use: CPU time, cores, and cache capacity, entropy pool capacity, network bandwidth, electric power consumption, stack memory. ### External links 1. [RAII in Stroustrup's C++ FAQ](http://www.stroustrup.com/bs_faq2.html#finally) 2. [C++ Core Guidelines E.6 "Use RAII to prevent leaks"](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e6-use-raii-to-prevent-leaks)
programming_docs
cpp Exceptions Exceptions ========== Exception handling provides a way of transferring control and information from some point in the execution of a program to a handler associated with a point previously passed by the execution (in other words, exception handling transfers control up the call stack). An exception can be thrown by a [throw-expression](throw "cpp/language/throw"), [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast"), [`typeid`](typeid "cpp/language/typeid"), [new-expression](new "cpp/language/new"), [allocation function](../memory/new/operator_new "cpp/memory/new/operator new"), and any of the standard library functions that are specified to throw exceptions to signal certain error conditions (e.g. `[std::vector::at](../container/vector/at "cpp/container/vector/at")`, `[std::string::substr](../string/basic_string/substr "cpp/string/basic string/substr")`, etc). In order for an exception to be caught, the throw-expression has to be inside a [try-block](try_catch "cpp/language/try catch") or inside a function called from a try-block, and there has to be a [catch clause](try_catch "cpp/language/try catch") that matches the type of the exception object. When declaring a function, the following specification(s) may be provided to limit the types of the exceptions a function may throw: | | | | --- | --- | | * [dynamic exception specifications](except_spec "cpp/language/except spec") | (until C++17) | | | | | --- | --- | | * [noexcept specifications](noexcept_spec "cpp/language/noexcept spec") | (since C++11) | Errors that arise during exception handling are handled by `[std::terminate](../error/terminate "cpp/error/terminate")` and `[std::unexpected](../error/unexpected "cpp/error/unexpected")` (until C++17). ### Usage While throw-expression can be used to transfer control to an arbitrary block of code up the execution stack, for arbitrary reasons (similar to `[std::longjmp](../utility/program/longjmp "cpp/utility/program/longjmp")`), its intended usage is error handling. #### Error handling Throwing an exception is used to signal errors from functions, where "errors" are typically limited to only the following[[1]](#cite_note-1)[[2]](#cite_note-2)[[3]](#cite_note-3): 1. Failures to meet the postconditions, such as failing to produce a valid return value object 2. Failures to meet the preconditions of another function that must be called 3. (for non-private member functions) Failures to (re)establish a class invariant In particular, this implies that the failures of constructors (see also [RAII](raii "cpp/language/raii")) and most operators should be reported by throwing exceptions. In addition, so-called *wide contract* functions use exceptions to indicate unacceptable inputs, for example, `[std::string::at](../string/basic_string/at "cpp/string/basic string/at")` has no preconditions, but throws an exception to indicate index out of range. #### Exception safety After the error condition is reported by a function, additional guarantees may be provided with regards to the state of the program. The following four levels of exception guarantee are generally recognized[[4]](#cite_note-4)[[5]](#cite_note-5)[[6]](#cite_note-6), which are strict supersets of each other: 1. *Nothrow (or nofail) exception guarantee* -- the function never throws exceptions. Nothrow (errors are reported by other means or concealed) is expected of [destructors](destructor "cpp/language/destructor") and other functions that may be called during stack unwinding. The [destructors](destructor "cpp/language/destructor") are [`noexcept`](noexcept "cpp/language/noexcept") by default. (since C++11) Nofail (the function always succeeds) is expected of swaps, [move constructors](move_constructor "cpp/language/move constructor"), and other functions used by those that provide strong exception guarantee. 2. *Strong exception guarantee* -- If the function throws an exception, the state of the program is rolled back to the state just before the function call. (for example, `[std::vector::push\_back](../container/vector/push_back "cpp/container/vector/push back")`) 3. *Basic exception guarantee* -- If the function throws an exception, the program is in a valid state. No resources are leaked, and all objects' invariants are intact. 4. *No exception guarantee* -- If the function throws an exception, the program may not be in a valid state: resource leaks, memory corruption, or other invariant-destroying errors may have occurred. Generic components may, in addition, offer *exception-neutral guarantee*: if an exception is thrown from a template parameter (e.g. from the `Compare` function object of `[std::sort](../algorithm/sort "cpp/algorithm/sort")` or from the constructor of `T` in `[std::make\_shared](../memory/shared_ptr/make_shared "cpp/memory/shared ptr/make shared")`), it is propagated, unchanged, to the caller. ### Exception objects While objects of any complete type and cv pointers to void may be thrown as exception objects, all standard library functions throw anonymous temporary objects by value, and the types of those objects are derived (directly or indirectly) from `[std::exception](../error/exception "cpp/error/exception")`. User-defined exceptions usually follow this pattern.[[7]](#cite_note-7)[[8]](#cite_note-8)[[9]](#cite_note-9) To avoid unnecessary copying of the exception object and object slicing, the best practice for catch clauses is to catch by reference.[[10]](#cite_note-10)[[11]](#cite_note-11)[[12]](#cite_note-12)[[13]](#cite_note-13) ### External links 1. H. Sutter (2004) ["When and How to Use Exceptions"](http://www.drdobbs.com/when-and-how-to-use-exceptions/184401836) in Dr. Dobb's 2. H.Sutter, A. Alexandrescu (2004), "C++ Coding Standards", Item 70 3. C++ Core Guidelines [I.10](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#i10-use-exceptions-to-signal-a-failure-to-perform-a-required-task) 4. B. Stroustrup (2000), "The C++ Programming Language"[Appendix E"](http://stroustrup.com/3rd_safe.pdf) 5. H. Sutter (2000) "Exceptional C++" 6. D. Abrahams (2001) ["Exception Safety in Generic Components"](http://www.boost.org/community/exception_safety.html) 7. D. Abrahams (2001) ["Error and Exception Handling"](http://www.boost.org/community/error_handling.html) 8. isocpp.org Super-FAQ ["What should I throw?"](https://isocpp.org/wiki/faq/exceptions#what-to-throw) 9. C++ Core Guidelines [E.14](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e14-use-purpose-designed-user-defined-types-as-exceptions-not-built-in-types) 10. C++ Core Guidelines [E.15](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e15-catch-exceptions-from-a-hierarchy-by-reference) 11. S. Meyers (1996) "More Effective C++" Item 13 12. isocpp.org Super-FAQ ["What should I catch?"](https://isocpp.org/wiki/faq/exceptions#what-to-catch) 13. H.Sutter, A. Alexandrescu (2004) "C++ Coding Standards" Item 73 cpp Qualified name lookup Qualified name lookup ===================== A *qualified* name is a name that appears on the right hand side of the scope resolution operator `::` (see also [qualified identifiers](identifiers#Qualified_identifiers "cpp/language/identifiers")). A qualified name may refer to a. * class member (including static and non-static functions, types, templates, etc) * namespace member (including another namespace) * enumerator If there is nothing on the left hand side of the `::`, the lookup considers only declarations made in the global namespace scope (or introduced into the global namespace by a [using declaration](namespace "cpp/language/namespace")). This makes it possible to refer to such names even if they were hidden by a local declaration: ``` #include <iostream> int main() { struct std {}; std::cout << "fail\n"; // Error: unqualified lookup for 'std' finds the struct ::std::cout << "ok\n"; // OK: ::std finds the namespace std } ``` Before name lookup can be performed for the name on the right hand side of `::`, lookup must be completed for the name on its left hand side (unless a [decltype](decltype "cpp/language/decltype") expression is used, or there is nothing on the left). This lookup, which may be qualified or unqualified, depending on whether there's another `::` to the left of that name, considers only namespaces, class types, enumerations, and templates whose specializations are types. If the name found on the left does not designate a namespace or a class, enumeration, or dependent type, the program is ill-formed: ``` struct A { static int n; }; int main() { int A; A::n = 42; // OK: unqualified lookup of A to the left of :: ignores the variable A b; // Error: unqualified lookup of A finds the variable A } template<int> struct B : A {}; namespace N { template<int> void B(); int f() { return B<0>::n; // error: N::B<0> is not a type } } ``` When a qualified name is used as a [declarator](declarations "cpp/language/declarations"), then [unqualified lookup](unqualified_lookup "cpp/language/unqualified lookup") of the names used in the same declarator that follow that qualified name, but not the names that precede it, is performed in the scope of the member's class or namespace: ``` class X {}; constexpr int number = 100; struct C { class X {}; static const int number = 50; static X arr[number]; }; X C::arr[number], brr[number]; // Error: look up for X finds ::X, not C::X C::X C::arr[number], brr[number]; // OK: size of arr is 50, size of brr is 100 ``` If `::` is followed by the character `~` that is in turn followed by an identifier (that is, it specifies a destructor or pseudo-destructor), that identifier is looked up in the same scope as the name on the left hand side of `::` ``` struct C { typedef int I; }; typedef int I1, I2; extern int *p, *q; struct A { ~A(); }; typedef A AB; int main() { p->C::I::~I(); // the name I after ~ is looked up in the same scope as I before :: // (that is, within the scope of C, so it finds C::I) q->I1::~I2(); // The name I2 is looked up in the same scope as I1 // that is, from the current scope, so it finds ::I2 AB x; x.AB::~AB(); // The name AB after ~ is looked up in the same scope as AB before :: // that is, from the current scope, so it finds ::AB } ``` | | | | --- | --- | | Enumerators If the lookup of the left-hand side name comes up with an [enumeration](enum "cpp/language/enum") (either scoped or unscoped), the lookup of the right-hand side must result in an enumerator that belongs that enumeration, otherwise the program is ill-formed. | (since C++11) | #### Class members If the lookup of the left hand side name comes up with a class/struct or union name, the name on the right hand side of `::` is looked up in the scope of that class (and so may find a declaration of a member of that class or of its base), with the following exceptions. * A destructor is looked up as described above (in the scope of the name to the left of ::) * A conversion-type-id in a [user-defined conversion](cast_operator "cpp/language/cast operator") function name is first looked up in the scope of the class. If not found, the name is then looked up in the current scope. * names used in template arguments are looked up in the current scope (not in the scope of the template name) * names in [using-declarations](namespace "cpp/language/namespace") also consider class/enum names that are hidden by the name of a variable, data member, function, or enumerator declared in the same scope If the right hand side of `::` names the same class as the left hand side, the name designates the [constructor](constructor "cpp/language/constructor") of that class. Such qualified name can only be used in a declaration of a constructor and in the [using-declaration](using_declaration "cpp/language/using declaration") for an [inheriting constructor](using_declaration#Inheriting_constructors "cpp/language/using declaration"). In those lookups where function names are ignored (that is, when looking up a name on the left of `::`, when looking up a name in [elaborated type specifier](elaborated_type_specifier "cpp/language/elaborated type specifier"), or [base specifier](derived_class "cpp/language/derived class")), the same syntax resolves to the injected-class-name: ``` struct A { A(); }; struct B : A { B(); }; A::A() {} // A::A names a constructor, used in a declaration B::B() {} // B::B names a constructor, used in a declaration B::A ba; // B::A names the type A (looked up in the scope of B) A::A a; // Error, A::A does not name a type struct A::A a2; // OK: lookup in elaborated type specifier ignores functions // so A::A simply names the class A as seen from within the scope of A // (that is, the injected-class-name) ``` Qualified name lookup can be used to access a class member that is hidden by a nested declaration or by a derived class. A call to a qualified member function is never virtual. ``` struct B { virtual void foo(); }; struct D : B { void foo() override; }; int main() { D x; B& b = x; b.foo(); // calls D::foo (virtual dispatch) b.B::foo(); // calls B::foo (static dispatch) } ``` #### Namespace members If the name on the left of `::` refers to a namespace or if there is nothing on the left of `::` (in which case it refers to the global namespace), the name that appears on the right hand side of `::` is looked up in the scope of that namespace, except that. * names used in template arguments are looked up in the current scope ``` namespace N { template<typename T> struct foo {}; struct X {}; } N::foo<X> x; // error: X is looked up as ::X, not as N::X ``` Qualified lookup within the scope of a [namespace](namespace "cpp/language/namespace") `N` first considers all declarations that are located in `N` and all declarations that are located in the [inline namespace members](namespace#Inline_namespaces "cpp/language/namespace") of `N` (and, transitively, in their inline namespace members). If there are no declarations in that set then it considers declarations in all namespaces named by [using-directives](namespace#Using-directives "cpp/language/namespace") found in `N` and in all transitive inline namespace members of `N`. The rules are applied recursively: ``` int x; namespace Y { void f(float); void h(int); } namespace Z { void h(double); } namespace A { using namespace Y; void f(int); void g(int); int i; } namespace B { using namespace Z; void f(char); int i; } namespace AB { using namespace A; using namespace B; void g(); } void h() { AB::g(); // AB is searched, AB::g found by lookup and is chosen AB::g(void) // (A and B are not searched) AB::f(1); // First, AB is searched, there is no f // Then, A, B are searched // A::f, B::f found by lookup // (but Y is not searched so Y::f is not considered) // overload resolution picks A::f(int) AB::x++; // First, AB is searched, there is no x // Then A, B are searched. There is no x // Then Y and Z are searched. There is still no x: this is an error AB::i++; // AB is searched, there is no i // Then A, B are searched. A::i and B::i found by lookup: this is an error AB::h(16.8); // First, AB is searched: there is no h // Then A, B are searched. There is no h // Then Y and Z are searched. // lookup finds Y::h and Z::h. Overload resolution picks Z::h(double) } ``` It is allowed for the same declaration to be found more than once: ``` namespace A { int a; } namespace B { using namespace A; } namespace D { using A::a; } namespace BD { using namespace B; using namespace D; } void g() { BD::a++; // OK: finds the same A::a through B and through D } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 215](https://cplusplus.github.io/CWG/issues/215.html) | C++98 | the name preceding `::` must be a class name or namespacename, so template parameters were not allowed there | the name must designate a class,namespace or dependent type | | [CWG 318](https://cplusplus.github.io/CWG/issues/318.html) | C++98 | if the right hand side of `::` names the same classas the left hand side, the qualified name was alwaysconsidered to name the constructor of that class | only name the constructorwhen acceptable (e.g. not inan elaborated type specifier) | ### See also * [Unqualified name lookup](unqualified_lookup "cpp/language/unqualified lookup") * [Scope](scope "cpp/language/scope") * [Argument-dependent lookup](adl "cpp/language/adl") * [Template argument deduction](function_template "cpp/language/function template") * [Overload resolution](overload_resolution "cpp/language/overload resolution") cpp Templates Templates ========= A template is a C++ entity that defines one of the following: * a family of classes ([class template](class_template "cpp/language/class template")), which may be [nested classes](member_template "cpp/language/member template") * a family of functions ([function template](function_template "cpp/language/function template")), which may be [member functions](member_template "cpp/language/member template") | | | | --- | --- | | * an alias to a family of types ([alias template](type_alias "cpp/language/type alias")) | (since C++11) | | | | | --- | --- | | * a family of variables ([variable template](variable_template "cpp/language/variable template")) | (since C++14) | | | | | --- | --- | | * a concept ([constraints and concepts](constraints "cpp/language/constraints")) | (since C++20) | Templates are parameterized by one or more [template parameters](template_parameters "cpp/language/template parameters"), of three kinds: type template parameters, non-type template parameters, and template template parameters. When template arguments are provided, or, for [function](function_template#Template_argument_deduction "cpp/language/function template") and [class](class_template_argument_deduction "cpp/language/class template argument deduction") (since C++17) templates only, deduced, they are substituted for the template parameters to obtain a *specialization* of the template, that is, a specific type or a specific function lvalue. Specializations may also be provided explicitly: [full specializations](template_specialization "cpp/language/template specialization") are allowed for class, variable (since C++14) and function templates, [partial specializations](partial_specialization "cpp/language/partial specialization") are only allowed for class templates and variable templates (since C++14). When a class template specialization is referenced in context that requires a complete object type, or when a function template specialization is referenced in context that requires a function definition to exist, the template is *instantiated* (the code for it is actually compiled), unless the template was already explicitly specialized or explicitly instantiated. Instantiation of a class template doesn't instantiate any of its member functions unless they are also used. At link time, identical instantiations generated by different translation units are merged. The definition of a template must be visible at the point of implicit instantiation, which is why template libraries typically provide all template definitions in the headers (e.g. [most boost libraries are header-only](http://www.boost.org/doc/libs/release/more/getting_started/unix-variants.html#header-only-libraries)). ### Syntax | | | | | --- | --- | --- | | `template` `<` parameter-list `>` requires-clause(optional) declaration | (1) | | | `export` `template` `<` parameter-list `>` declaration | (2) | (until C++11) | | `template` `<` parameter-list `>` `concept` concept-name `=` constraint-expression `;` | (3) | (since C++20) | | | | | | --- | --- | --- | | parameter-list | - | a non-empty comma-separated list of the [template parameters](template_parameters "cpp/language/template parameters"), each of which is either [non-type parameter](template_parameters#Non-type_template_parameter "cpp/language/template parameters"), a [type parameter](template_parameters#Type_template_parameter "cpp/language/template parameters"), a [template parameter](template_parameters#Template_template_parameter "cpp/language/template parameters"), or a [parameter pack](parameter_pack "cpp/language/parameter pack") of any of those. | | requires-clause | - | (since C++20) a [requires-clause](constraints#requires_clauses "cpp/language/constraints") that specifies the [constraints](constraints "cpp/language/constraints") on the template arguments. | | declaration | - | declaration of a [class (including struct and union)](class_template "cpp/language/class template"), a [member class or member enumeration type](member_template "cpp/language/member template"), a [function](function_template "cpp/language/function template") or [member function](member_template "cpp/language/member template"), a static data member at namespace scope, [a variable or static data member at class scope](variable_template "cpp/language/variable template"), (since C++14) or an [alias template](type_alias "cpp/language/type alias") (since C++11) It may also define a [template specialization](template_specialization "cpp/language/template specialization"). | | concept-nameconstraint-expression | - | see [constraints and concepts](constraints "cpp/language/constraints") | | | | | --- | --- | | `export` was an optional modifier which declared the template as *exported* (when used with a class template, it declared all of its members exported as well). Files that instantiated exported templates did not need to include their definitions: the declaration was sufficient. Implementations of `export` were rare and disagreed with each other on details. | (until C++11) | ### template-id | | | | | --- | --- | --- | | template-name `<` parameter-list `>` | | | | | | | | --- | --- | --- | | template-name | - | either an [identifier](identifiers "cpp/language/identifiers") that names a template (in which case this is called "simple-template-id") or a name of an overloaded operator template or user-defined literal template. | A simple-template-id that names a class template specialization names a class. A template-id that names an alias template specialization names a type. A template-id that names a function template specialization names a function. A template-id is only valid if. * there are at most as many arguments as there are parameters or a parameter is a template parameter pack, * there is an argument for each non-deducible non-pack parameter that does not have a default template-argument, * each template-argument matches the corresponding template-parameter, * substitution of each template argument into the following template parameters (if any) succeeds, and | | | | --- | --- | | * if the template-id is non-dependent, the associated constraints are satisfied as specified below. | (since C++20) | An invalid simple-template-id is a compile-time error, unless it names a function template specialization (in which case [SFINAE](sfinae "cpp/language/sfinae") may apply). ``` template<class T, T::type n = 0> class X; struct S { using type = int; }; using T1 = X<S, int, int>; // error: too many arguments using T2 = X<>; // error: no default argument for first template parameter using T3 = X<1>; // error: value 1 does not match type-parameter using T4 = X<int>; // error: substitution failure for second template parameter using T5 = X<S>; // OK ``` | | | | --- | --- | | When the template-name of a simple-template-id names a constrained non-function template or a constrained template template-parameter, but not a member template that is a member of an unknown specialization, and all template-arguments in the simple-template-id are non-dependent, the associated constraints of the constrained template must be satisfied: ``` template<typename T> concept C1 = sizeof(T) != sizeof(int); template<C1 T> struct S1 {}; template<C1 T> using Ptr = T*; S1<int>* p; // error: constraints not satisfied Ptr<int> p; // error: constraints not satisfied template<typename T> struct S2 { Ptr<int> x; }; // error, no diagnostic required template<typename T> struct S3 { Ptr<T> x; }; // OK, satisfaction is not required S3<int> x; // error: constraints not satisfied template<template<C1 T> class X> struct S4 { X<int> x; // error, no diagnostic required }; template<typename T> concept C2 = sizeof(T) == 1; template<C2 T> struct S {}; template struct S<char[2]>; // error: constraints not satisfied template<> struct S<char[2]> {}; // error: constraints not satisfied ``` | (since C++20) | Two template-ids are same if. * their template-names refer to the same template, and * their corresponding type template arguments are the same type, and * their corresponding non-type template arguments are [template-argument-equivalent](template_parameters#Template_argument_equivalence "cpp/language/template parameters") after conversion to the type of the template parameter, and * their corresponding template template arguments refer to the same template. Two template-ids that are the same refer to the same variable, (since C++14) class, or function. ### Templated entity A templated entity (or, in some sources, "temploid") is any entity that is defined (or, for a lambda-expression, created) within a template definition. All of the following are templated entities: * a class/function/variable (since C++14) template | | | | --- | --- | | * a [concept](constraints "cpp/language/constraints") | (since C++20) | * a member of a templated entity (such as a non-template member function of a class template) * an enumerator of an enumeration that is a templated entity * any entity defined or created within a templated entity: a local class, a local variable, a friend function, etc * the closure type of a lambda expression that appears in the declaration of a templated entity For example, in. ``` template<typename T> struct A { void f() {} }; ``` the function `A::f` is not a function template, but is still considered to be templated. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 2293](https://cplusplus.github.io/CWG/issues/2293.html) | C++98 | the rules of determining whether a template-id is valid were not provided | provided |
programming_docs
cpp Derived classes Derived classes =============== Any class type (whether declared with class-key `class` or `struct`) may be declared as *derived* from one or more *base classes* which, in turn, may be derived from their own base classes, forming an inheritance hierarchy. The list of base classes is provided in the base-clause of the [class declaration syntax](class "cpp/language/class"). The base-clause consists of the character `:` followed by a comma-separated list of one or more base-specifiers. | | | | | --- | --- | --- | | attr(optional) class-or-decltype | (1) | | | attr(optional) `virtual` class-or-decltype | (2) | | | attr(optional) access-specifier class-or-decltype | (3) | | | attr(optional) `virtual` access-specifier class-or-decltype | (4) | | | attr(optional) access-specifier `virtual` class-or-decltype | (5) | | 1) Specifies a non-virtual inheritance with default member accessibility. 2) Specifies a virtual inheritance with default member accessibility. 3) Specifies a non-virtual inheritance with given member accessibility. 4) Specifies a virtual inheritance with given member accessibility. 5) Same as 4), `virtual` and access-specifier can appear in any order. | | | | | --- | --- | --- | | attr | - | (since C++11) sequence of any number of [attributes](attributes "cpp/language/attributes") | | access-specifier | - | one of `private`, `public`, or `protected` | | class-or-decltype | - | one of * nested-name-specifier(optional) type-name * nested-name-specifier `template` simple-template-id | | | | --- | --- | | * [decltype-specifier](decltype "cpp/language/decltype") | (since C++11) | | An [elaborated type specifier](elaborated_type_specifier "cpp/language/elaborated type specifier") cannot directly appear as class-or-decltype due to syntax limitations. | | | | --- | --- | | base-specifiers in a base-clause may be [pack expansions](parameter_pack "cpp/language/parameter pack"). A class or struct declared [`final`](final "cpp/language/final") cannot be denoted by class-or-decltype. | (since C++11) | If access-specifier is omitted, it defaults to `public` for classes declared with class-key `struct` and to `private` for classes declared with class-key `class`. ``` struct Base { int a, b, c; }; // every object of type Derived includes Base as a subobject struct Derived : Base { int b; }; // every object of type Derived2 includes Derived and Base as subobjects struct Derived2 : Derived { int c; }; ``` Classes denoted by class-or-decltype's listed in the base-clause are direct base classes. Their bases are indirect base classes. The same class cannot be specified as a direct base class more than once, but the same class can be both direct and indirect base class. Each direct and indirect base class is present, as *base class subobject*, within the object representation of the derived class at ABI-dependent offset. Empty base classes usually do not increase the size of the derived object due to [empty base optimization](ebo "cpp/language/ebo"). The constructors of base class subobjects are called by the constructor of the derived class: arguments may be provided to those constructors in the [member initializer list](initializer_list "cpp/language/initializer list"). ### Virtual base classes For each distinct base class that is specified `virtual`, the most derived object contains only one base class subobject of that type, even if the class appears many times in the inheritance hierarchy (as long as it is inherited `virtual` every time). ``` struct B { int n; }; class X : public virtual B {}; class Y : virtual public B {}; class Z : public B {}; // every object of type AA has one X, one Y, one Z, and two B's: // one that is the base of Z and one that is shared by X and Y struct AA : X, Y, Z { AA() { X::n = 1; // modifies the virtual B subobject's member Y::n = 2; // modifies the same virtual B subobject's member Z::n = 3; // modifies the non-virtual B subobject's member std::cout << X::n << Y::n << Z::n << '\n'; // prints 223 } }; ``` An example of an inheritance hierarchy with virtual base classes is the iostreams hierarchy of the standard library: `[std::istream](../io/basic_istream "cpp/io/basic istream")` and `[std::ostream](../io/basic_ostream "cpp/io/basic ostream")` are derived from `[std::ios](../io/basic_ios "cpp/io/basic ios")` using virtual inheritance. `[std::iostream](../io/basic_iostream "cpp/io/basic iostream")` is derived from both `[std::istream](../io/basic_istream "cpp/io/basic istream")` and `[std::ostream](../io/basic_ostream "cpp/io/basic ostream")`, so every instance of `[std::iostream](../io/basic_iostream "cpp/io/basic iostream")` contains a `[std::ostream](../io/basic_ostream "cpp/io/basic ostream")` subobject, a `[std::istream](../io/basic_istream "cpp/io/basic istream")` subobject, and just one `[std::ios](../io/basic_ios "cpp/io/basic ios")` subobject (and, consequently, one `[std::ios\_base](../io/ios_base "cpp/io/ios base")`). All virtual base subobjects are initialized before any non-virtual base subobject, so only the most derived class calls the constructors of the virtual bases in its [member initializer list](initializer_list "cpp/language/initializer list"): ``` struct B { int n; B(int x) : n(x) {} }; struct X : virtual B { X() : B(1) {} }; struct Y : virtual B { Y() : B(2) {} }; struct AA : X, Y { AA() : B(3), X(), Y() {} }; // the default constructor of AA calls the default constructors of X and Y // but those constructors do not call the constructor of B because B is a virtual base AA a; // a.n == 3 // the default constructor of X calls the constructor of B X x; // x.n == 1 ``` There are [special rules](unqualified_lookup#Member_function_definition "cpp/language/unqualified lookup") for unqualified name lookup for class members when virtual inheritance is involved (sometimes referred to as the rules of dominance). ### Public inheritance When a class uses `public` [member access specifier](access "cpp/language/access") to derive from a base, all public members of the base class are accessible as public members of the derived class and all protected members of the base class are accessible as protected members of the derived class (private members of the base are never accessible unless friended). Public inheritance models the subtyping relationship of object-oriented programming: the derived class object IS-A base class object. References and pointers to a derived object are expected to be usable by any code that expects references or pointers to any of its public bases (see [LSP](https://en.wikipedia.org/wiki/Liskov_substitution_principle "enwiki:Liskov substitution principle")) or, in [DbC](https://en.wikipedia.org/wiki/Design_by_contract "enwiki:Design by contract") terms, a derived class should maintain class invariants of its public bases, should not strengthen any precondition or weaken any postcondition of a member function it [overrides](virtual "cpp/language/virtual"). ``` #include <vector> #include <string> #include <iostream> struct MenuOption { std::string title; }; // Menu is a vector of MenuOption: options can be inserted, removed, reordered... // and has a title. class Menu : public std::vector<MenuOption> { public: std::string title; void print() const { std::cout << title << ":\n"; for (std::size_t i = 0, s = size(); i < s; ++i) std::cout << " " << (i+1) << ". " << at(i).title << '\n'; } }; // Note: Menu::title is not problematic because its role is independent of the base class. enum class Color { WHITE, RED, BLUE, GREEN }; void apply_terminal_color(Color) { /* OS-specific */ } // THIS IS BAD! // ColorMenu is a Menu where every option has a custom color. class ColorMenu : public Menu { public: std::vector<Color> colors; void print() const { std::cout << title << ":\n"; for (std::size_t i = 0, s = size(); i < s; ++i) { std::cout << " " << (i+1) << ". "; apply_terminal_color(colors[i]); std::cout << at(i).title << '\n'; apply_terminal_color(Color::WHITE); } } }; // ColorMenu needs the following invariants that cannot be satisfied // by publicly inheriting from Menu, for example: // - ColorMenu::colors and Menu must have the same number of elements // - To make sense, calling erase() should remove also elements from colors, // in order to let options keep their colors // Basically every non-const call to a std::vector method will break the invariant // of the ColorMenu and will need fixing from the user by correctly managing colors. int main() { ColorMenu color_menu; // The big problem of this class is that we must keep ColorMenu::Color // in sync with Menu. color_menu.push_back(MenuOption{"Some choice"}); // color_menu.print(); // ERROR! colors[i] in print() is out of range color_menu.colors.push_back(Color::RED); color_menu.print(); // OK: colors and Menu has the same number of elements } ``` ### Protected inheritance When a class uses `protected` [member access specifier](access "cpp/language/access") to derive from a base, all public and protected members of the base class are accessible as protected members of the derived class (private members of the base are never accessible unless friended). Protected inheritance may be used for "controlled polymorphism": within the members of Derived, as well as within the members of all further-derived classes, the derived class IS-A base: references and pointers to Derived may be used where references and pointers to Base are expected. ### Private inheritance When a class uses `private` [member access specifier](access "cpp/language/access") to derive from a base, all public and protected members of the base class are accessible as private members of the derived class (private members of the base are never accessible unless friended). Private inheritance is commonly used in policy-based design, since policies are usually empty classes, and using them as bases both enables static polymorphism and leverages [empty-base optimization](ebo "cpp/language/ebo"). Private inheritance can also be used to implement the composition relationship (the base class subobject is an implementation detail of the derived class object). Using a member offers better encapsulation and is generally preferred unless the derived class requires access to protected members (including constructors) of the base, needs to override a virtual member of the base, needs the base to be constructed before and destructed after some other base subobject, needs to share a virtual base or needs to control the construction of a virtual base. Use of members to implement composition is also not applicable in the case of multiple inheritance from a [parameter pack](parameter_pack "cpp/language/parameter pack") or when the identities of the base classes are determined at compile time through template metaprogramming. Similar to protected inheritance, private inheritance may also be used for controlled polymorphism: within the members of the derived (but not within further-derived classes), derived IS-A base. ``` template<typename Transport> class service : private Transport // private inheritance from the Transport policy { public: void transmit() { this->send(...); // send using whatever transport was supplied } }; // TCP transport policy class tcp { public: void send(...); }; // UDP transport policy class udp { public: void send(...); }; service<tcp> service(host, port); service.transmit(...); // send over TCP ``` ### Member name lookup Unqualified and qualified name lookup rules for class members are detailed in [name lookup](lookup "cpp/language/lookup"). ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1710](https://cplusplus.github.io/CWG/issues/1710.html) | C++98 | the syntax of class-or-decltype made it impossible to derive froma dependent class where the `template` disambiguator is required | allowed `template` | ### See also * [virtual functions](virtual "cpp/language/virtual") * [abstract classes](abstract_class "cpp/language/abstract class") cpp typeid operator typeid operator =============== Queries information of a type. Used where the [dynamic type](type#Dynamic_type "cpp/language/type") of a [polymorphic object](object#Polymorphic_objects "cpp/language/object") must be known and for static type identification. ### Syntax | | | | | --- | --- | --- | | `typeid` `(` type `)` | (1) | | | `typeid` `(` expression `)` | (2) | | The header [`<typeinfo>`](../header/typeinfo "cpp/header/typeinfo") must be included before using `typeid` (if the header is not included, every use of the keyword `typeid` makes the program ill-formed.). The typeid expression is an [lvalue expression](value_category "cpp/language/value category") which refers to an object with [static storage duration](static "cpp/language/static"), of const-qualified version of the polymorphic type `[std::type\_info](../types/type_info "cpp/types/type info")` or some type derived from it. ### Explanation 1) Refers to a `[std::type\_info](../types/type_info "cpp/types/type info")` object representing the type type. If type is a reference type, the result refers to a `[std::type\_info](../types/type_info "cpp/types/type info")` object representing the referenced type. 2) Examines the expression expression a) If expression is a [glvalue expression](value_category "cpp/language/value category") that identifies an [object of a polymorphic type](object#Polymorphic_objects "cpp/language/object") (that is, a class that declares or inherits at least one [virtual function](virtual "cpp/language/virtual")), the `typeid` expression evaluates the expression and then refers to the `[std::type\_info](../types/type_info "cpp/types/type info")` object that represents the dynamic type of the expression. If the glvalue expression is obtained by applying the unary \* operator to a pointer and the pointer is a null pointer value, an exception of type `[std::bad\_typeid](../types/bad_typeid "cpp/types/bad typeid")` or a type derived from `[std::bad\_typeid](../types/bad_typeid "cpp/types/bad typeid")` is thrown. b) If expression is not a glvalue expression of polymorphic type, `typeid` does [not evaluate the expression](expressions#Unevaluated_expressions "cpp/language/expressions"), and the `[std::type\_info](../types/type_info "cpp/types/type info")` object it identifies represents the static type of the expression. Lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversions are not performed. [Temporary materialization](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion"), however, is (formally) performed for prvalue arguments: the argument must be destructible in the context in which the `typeid` expression appears. (since C++17) In all cases, top-level cv-qualifiers are ignored by `typeid` (that is, `typeid(const T) == typeid(T)`). If the operand to `typeid` is a class type or a reference to a class type, then that class type must not be an [incomplete type](incomplete_type "cpp/language/incomplete type"). If `typeid` is used on an object under construction or destruction (in a destructor or in a constructor, including constructor's [initializer list](initializer_list "cpp/language/initializer list") or [default member initializers](data_members#Member_initialization "cpp/language/data members")), then the `[std::type\_info](../types/type_info "cpp/types/type info")` object referred to by this `typeid` represents the class that is being constructed or destroyed even if it is not the most-derived class. ### Keywords [`typeid`](../keyword/typeid "cpp/keyword/typeid"). ### Notes When applied to an expression of polymorphic type, evaluation of a typeid expression may involve runtime overhead (a virtual table lookup), otherwise typeid expression is resolved at compile time. It is unspecified whether the destructor for the object referred to by `typeid` is executed at the end of the program. There is no guarantee that the same `[std::type\_info](../types/type_info "cpp/types/type info")` instance will be referred to by all evaluations of the typeid expression on the same type, although they would compare equal, `[std::type\_info::hash\_code](../types/type_info/hash_code "cpp/types/type info/hash code")` of those `type_info` objects would be identical, as would be their `[std::type\_index](../types/type_index "cpp/types/type index")`. ``` const std::type_info& ti1 = typeid(A); const std::type_info& ti2 = typeid(A); assert(&ti1 == &ti2); // not guaranteed assert(ti1 == ti2); // guaranteed assert(ti1.hash_code() == ti2.hash_code()); // guaranteed assert(std::type_index(ti1) == std::type_index(ti2)); // guaranteed ``` ### Example The example showing output using one of the implementations where `type_info::name` returns full type names; filter through c++filt -t if using gcc or similar. ``` #include <iostream> #include <string> #include <typeinfo> struct Base {}; // non-polymorphic struct Derived : Base {}; struct Base2 { virtual void foo() {} }; // polymorphic struct Derived2 : Base2 {}; int main() { int myint = 50; std::string mystr = "string"; double *mydoubleptr = nullptr; std::cout << "myint has type: " << typeid(myint).name() << '\n' << "mystr has type: " << typeid(mystr).name() << '\n' << "mydoubleptr has type: " << typeid(mydoubleptr).name() << '\n'; // std::cout << myint is a glvalue expression of polymorphic type; it is evaluated const std::type_info& r1 = typeid(std::cout << myint); // side-effect: prints 50 std::cout << '\n' << "std::cout<<myint has type : " << r1.name() << '\n'; // std::printf() is not a glvalue expression of polymorphic type; NOT evaluated const std::type_info& r2 = typeid(std::printf("%d\n", myint)); std::cout << "printf(\"%d\\n\",myint) has type : " << r2.name() << '\n'; // Non-polymorphic lvalue is a static type Derived d1; Base& b1 = d1; std::cout << "reference to non-polymorphic base: " << typeid(b1).name() << '\n'; Derived2 d2; Base2& b2 = d2; std::cout << "reference to polymorphic base: " << typeid(b2).name() << '\n'; try { // dereferencing a null pointer: okay for a non-polymorphic expression std::cout << "mydoubleptr points to " << typeid(*mydoubleptr).name() << '\n'; // dereferencing a null pointer: not okay for a polymorphic lvalue Derived2* bad_ptr = nullptr; std::cout << "bad_ptr points to... "; std::cout << typeid(*bad_ptr).name() << '\n'; } catch (const std::bad_typeid& e) { std::cout << " caught " << e.what() << '\n'; } } ``` Possible output: ``` ======== output from Clang ======== myint has type: i mystr has type: NSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE mydoubleptr has type: Pd 50 std::cout<<myint has type : NSt3__113basic_ostreamIcNS_11char_traitsIcEEEE printf("%d\n",myint) has type : i reference to non-polymorphic base: 4Base reference to polymorphic base: 8Derived2 mydoubleptr points to d bad_ptr points to... caught std::bad_typeid ======== output from MSVC ======== myint has type: int mystr has type: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > mydoubleptr has type: double * __ptr64 50 std::cout<<myint has type : class std::basic_ostream<char,struct std::char_traits<char> > printf("%d\n",myint) has type : int reference to non-polymorphic base: struct Base reference to polymorphic base: struct Derived2 mydoubleptr points to double bad_ptr points to... caught Attempted a typeid of nullptr pointer! ```
programming_docs
cpp nullptr, the pointer literal nullptr, the pointer literal ============================ ### Syntax | | | | | --- | --- | --- | | `nullptr` | | (since C++11) | ### Explanation The keyword `nullptr` denotes the pointer literal. It is a [prvalue](value_category "cpp/language/value category") of type `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")`. There exist [implicit conversions](implicit_conversion "cpp/language/implicit conversion") from `nullptr` to null pointer value of any pointer type and any pointer to member type. Similar conversions exist for any null pointer constant, which includes values of type `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` as well as the macro `[NULL](../types/null "cpp/types/NULL")`. ### Example Demonstrates that `nullptr` retains the meaning of null pointer constant even if it is no longer a literal. ``` #include <cstddef> #include <iostream> template<class T> constexpr T clone(const T& t) { return t; } void g(int*) { std::cout << "Function g called\n"; } int main() { g(nullptr); // Fine g(NULL); // Fine g(0); // Fine g(clone(nullptr)); // Fine // g(clone(NULL)); // ERROR: non-literal zero cannot be a null pointer constant // g(clone(0)); // ERROR: non-literal zero cannot be a null pointer constant } ``` Output: ``` Function g called Function g called Function g called Function g called ``` ### Keywords [`nullptr`](../keyword/nullptr "cpp/keyword/nullptr"). ### References * C++20 standard (ISO/IEC 14882:2020): + 7.3.12 Pointer conversions [conv.ptr] * C++17 standard (ISO/IEC 14882:2017): + 7.11 Pointer conversions [conv.ptr] * C++14 standard (ISO/IEC 14882:2014): + 4.10 Pointer conversions [conv.ptr] * C++11 standard (ISO/IEC 14882:2011): + 4.10 Pointer conversions [conv.ptr] ### See also | | | | --- | --- | | [NULL](../types/null "cpp/types/NULL") | implementation-defined null pointer constant (macro constant) | | [nullptr\_t](../types/nullptr_t "cpp/types/nullptr t") (C++11) | the type of the null pointer literal **`nullptr`** (typedef) | | [C documentation](https://en.cppreference.com/w/c/language/nullptr "c/language/nullptr") for `nullptr` | cpp Arithmetic operators Arithmetic operators ==================== Returns the result of specific arithmetic operation. | Operator name | Syntax | [Over​load​able](operators "cpp/language/operators") | Prototype examples (for `class T`) | | --- | --- | --- | --- | | Inside class definition | Outside class definition | | unary plus | `+a` | Yes | `T T::operator+() const;` | `T operator+(const T &a);` | | unary minus | `-a` | Yes | `T T::operator-() const;` | `T operator-(const T &a);` | | addition | `a + b` | Yes | `T T::operator+(const T2 &b) const;` | `T operator+(const T &a, const T2 &b);` | | subtraction | `a - b` | Yes | `T T::operator-(const T2 &b) const;` | `T operator-(const T &a, const T2 &b);` | | multiplication | `a * b` | Yes | `T T::operator*(const T2 &b) const;` | `T operator*(const T &a, const T2 &b);` | | division | `a / b` | Yes | `T T::operator/(const T2 &b) const;` | `T operator/(const T &a, const T2 &b);` | | modulo | `a % b` | Yes | `T T::operator%(const T2 &b) const;` | `T operator%(const T &a, const T2 &b);` | | bitwise NOT | `~a` | Yes | `T T::operator~() const;` | `T operator~(const T &a);` | | bitwise AND | `a & b` | Yes | `T T::operator&(const T2 &b) const;` | `T operator&(const T &a, const T2 &b);` | | bitwise OR | `a | b` | Yes | `T T::operator|(const T2 &b) const;` | `T operator|(const T &a, const T2 &b);` | | bitwise XOR | `a ^ b` | Yes | `T T::operator^(const T2 &b) const;` | `T operator^(const T &a, const T2 &b);` | | bitwise left shift | `a << b` | Yes | `T T::operator<<(const T2 &b) const;` | `T operator<<(const T &a, const T2 &b);` | | bitwise right shift | `a >> b` | Yes | `T T::operator>>(const T2 &b) const;` | `T operator>>(const T &a, const T2 &b);` | | **Notes*** All built-in operators return values, and most [user-defined overloads](operators "cpp/language/operators") also return values so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including `void`). In particular, stream insertion and stream extraction overloads of `operator<<` and `operator>>` return `T&`. * `T2` can be any type including `T` | ### Explanation All arithmetic operators compute the result of specific arithmetic operation and returns its result. The arguments are not modified. #### Conversions If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoes [integral promotion](implicit_conversion#Integral_promotion "cpp/language/implicit conversion"). If an operand has array or function type, [array-to-pointer](implicit_conversion#array_to_pointer_conversion "cpp/language/implicit conversion") and [function-to-pointer](implicit_conversion#function_to_pointer "cpp/language/implicit conversion") conversions are applied. For the binary operators (except shifts), if the promoted operands have different types, additional set of implicit conversions is applied, known as *usual arithmetic conversions* with the goal to produce the *common type* (also accessible via the `[std::common\_type](../types/common_type "cpp/types/common type")` type trait). If, prior to any integral promotion, one operand is of enumeration type and the other operand is of a floating-point type or a different enumeration type, this behavior is deprecated. (since C++20). * If either operand has [scoped enumeration type](enum_class "cpp/language/enum class"), no conversion is performed: the other operand and the return type must have the same type. * Otherwise, if either operand is `long double`, the other operand is converted to `long double`. * Otherwise, if either operand is `double`, the other operand is converted to `double`. * Otherwise, if either operand is `float`, the other operand is converted to `float`. * Otherwise, the operand has integer type (because `bool`, `char`, `char8_t`, (since C++20) `char16_t`, `char32_t`, (since C++11) `wchar_t`, and unscoped enumeration were promoted at this point) and [integral conversions](implicit_conversion#Integral_conversions "cpp/language/implicit conversion") are applied to produce the common type, as follows: + If both operands are signed or both are unsigned, the operand with lesser *conversion rank* is converted to the operand with the greater integer conversion rank. + Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type. + Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type. + Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type. The *conversion rank* above increases in order `bool`, `signed char`, `short`, `int`, `long`, `long long` (since C++11). The rank of any unsigned type is equal to the rank of the corresponding signed type. The rank of `char` is equal to the rank of `signed char` and `unsigned char`. The ranks of `char8_t`, (since C++20)`char16_t`, `char32_t`, and (since C++11)`wchar_t` are equal to the ranks of their corresponding underlying types. #### Overflows Unsigned integer arithmetic is always performed modulo 2n where n is the number of bits in that particular integer. E.g. for `unsigned int`, adding one to `[UINT\_MAX](../types/climits "cpp/types/climits")` gives `​0​`, and subtracting one from `​0​` gives `[UINT\_MAX](../types/climits "cpp/types/climits")`. When signed integer arithmetic operation overflows (the result does not fit in the result type), the behavior is undefined, — the possible manifestations of such an operation include: * it wraps around according to the rules of the representation (typically 2's complement), * it traps — on some platforms or due to compiler options (e.g. `-ftrapv` in GCC and Clang), * it saturates to minimal or maximal value (on many DSPs), * it is completely [optimized out by the compiler](http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html). #### Floating-point environment If [`#pragma STDC FENV_ACCESS`](../preprocessor/impl "cpp/preprocessor/impl") is supported and set to `ON`, all floating-point arithmetic operators obey the current floating-point [rounding direction](../numeric/fenv/fe_round "cpp/numeric/fenv/FE round") and report floating-point arithmetic errors as specified in [`math_errhandling`](../numeric/math/math_errhandling "cpp/numeric/math/math errhandling") unless part of a [static initializer](initialization#Non-local_variables "cpp/language/initialization") (in which case floating-point exceptions are not raised and the rounding mode is to nearest). #### Floating-point contraction Unless [`#pragma STDC FP_CONTRACT`](../preprocessor/impl "cpp/preprocessor/impl") is supported and set to `OFF`, all floating-point arithmetic may be performed as if the intermediate results have infinite range and precision, that is, optimizations that omit rounding errors and floating-point exceptions are allowed. For example, C++ allows the implementation of `(x * y) + z` with a single fused multiply-add CPU instruction or optimization of `a = x * x * x * x;` as `tmp = x * x; a = tmp * tmp`. Unrelated to contracting, intermediate results of floating-point arithmetic may have range and precision that is different from the one indicated by its type, see `[FLT\_EVAL\_METHOD](../types/climits/flt_eval_method "cpp/types/climits/FLT EVAL METHOD")`. Formally, the C++ standard makes no guarantee on the accuracy of floating-point operations. #### Unary arithmetic operators The unary arithmetic operator expressions have the form. | | | | | --- | --- | --- | | `+` expression | (1) | | | `-` expression | (2) | | 1) unary plus (promotion). For the built-in operator, expression must have arithmetic, unscoped enumeration, or pointer type. Integral promotion is performed on the operand if it has integral or unscoped enumeration type and determines the type of the result. 2) unary minus (negation). For the built-in operator, expression must have arithmetic or unscoped enumeration type. Integral promotion is performed on the operand and determines the type of the result. The built-in unary plus operator returns the value of its operand. The only situation where it is not a no-op is when the operand has integral type or unscoped enumeration type, which is changed by integral promotion, e.g, it converts `char` to `int` or if the operand is subject to lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversion. The builtin unary minus operator calculates the negative of its promoted operand. For unsigned `a`, the value of `-a` is 2b -a, where `b` is the number of bits after promotion. In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for every cv-unqualified promoted arithmetic type `A` and for every type `T`, the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` A operator+(A) ``` | | | | ``` T* operator+(T*) ``` | | | | ``` A operator-(A) ``` | | | ``` #include <iostream> int main() { char c = 0x6a; int n1 = 1; unsigned char n2 = 1; unsigned int n3 = 1; std::cout << "char: " << c << " int: " << +c << '\n' << "-1, where 1 is signed: " << -n1 << '\n' << "-1, where 1 is unsigned char: " << -n2 << '\n' << "-1, where 1 is unsigned int: " << -n3 << '\n'; char a[3]; std::cout << "size of array: " << sizeof a << '\n' << "size of pointer: " << sizeof +a << '\n'; } ``` Possible output: ``` char: j int: 106 -1, where 1 is signed: -1 -1, where 1 is unsigned char: -1 -1, where 1 is unsigned int: 4294967295 size of array: 3 size of pointer: 8 ``` #### Additive operators The binary additive arithmetic operator expressions have the form. | | | | | --- | --- | --- | | lhs `+` rhs | (1) | | | lhs `-` rhs | (2) | | 1) addition For the built-in operator, lhs and rhs must be one of the following: * both have arithmetic or unscoped enumeration type. In this case, the usual arithmetic conversions are performed on both operands and determine the type of the result. * one is a pointer to completely-defined object type, the other has integral or unscoped enumeration type. In this case, the result type has the type of the pointer. 2) subtraction For the built-in operator, lhs and rhs must be one of the following: * both have arithmetic or unscoped enumeration type. In this case, the usual arithmetic conversions are performed on both operands and determine the type of the result. * lhs is a pointer to completely-defined object type, rhs has integral or unscoped enumeration type. In this case, the result type has the type of the pointer. * both are pointers to the same completely-defined object types, ignoring cv-qualifiers. In this case, the result type is `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`. With operands of arithmetic or enumeration type, the result of binary plus is the sum of the operands (after usual arithmetic conversions), and the result of the binary minus operator is the result of subtracting the second operand from the first (after usual arithmetic conversions), except that, if the type supports IEEE floating-point arithmetic (see `[std::numeric\_limits::is\_iec559](../types/numeric_limits/is_iec559 "cpp/types/numeric limits/is iec559")`), * if one operand is NaN, the result is NaN * infinity minus infinity is NaN and `[FE\_INVALID](../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised * infinity plus the negative infinity is NaN and `[FE\_INVALID](../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised If any of the operands is a pointer, the following rules apply: * A pointer to non-array object is treated as a pointer to the first element of an array with size 1. * If the pointer `P` points to the `i`th element of an array, then the expressions `P + n`, `n + P`, and `P - n` are pointers of the same type that point to the `i+n`th, `i+n`th, and `i-n`th element of the same array, respectively. The result of pointer addition may also be a one-past-the-end pointer (that is, pointer `P` such that the expression `P - 1` points to the last element of the array). Any other situations (that is, attempts to generate a pointer that isn't pointing at an element of the same array or one past the end) invoke undefined behavior. * If the pointer `P` points to the `i`th element of an array, and the pointer `Q` points at the `j`th element of the same array, the expression `P - Q` has the value `i - j`, if the value fits in `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`. Both operands must point to the elements of the same array (or one past the end), otherwise the behavior is undefined. If the result does not fit in `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")`, the behavior is undefined. * In any case, if the pointed-to type is different from the array element type, disregarding cv-qualifications, at every level if the elements are themselves pointers, the behavior of pointer arithmetic is undefined. In particular, pointer arithmetic with pointer to base, which is pointing at an element of an array of derived objects is undefined. * If the value `​0​` is added or subtracted from a pointer, the result is the pointer, unchanged. If two pointers point at the same object or are both one past the end of the same array, or both are null pointers, then the result of subtraction is equal to `([std::ptrdiff\_t](http://en.cppreference.com/w/cpp/types/ptrdiff_t))0`. These pointer arithmetic operators allow pointers to satisfy the [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") requirements. In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for every pair of promoted arithmetic types `L` and `R` and for every object type `T`, the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` LR operator+(L, R) ``` | | | | ``` LR operator-(L, R) ``` | | | | ``` T* operator+(T*, std::ptrdiff_t) ``` | | | | ``` T* operator+(std::ptrdiff_t, T*) ``` | | | | ``` T* operator-(T*, std::ptrdiff_t) ``` | | | | ``` std::ptrdiff_t operator-(T*, T*) ``` | | | where `LR` is the result of usual arithmetic conversions on `L` and `R`. ``` #include <iostream> int main() { char c = 2; unsigned int un = 2; int n = -10; std::cout << " 2 + (-10), where 2 is a char = " << c + n << '\n' << " 2 + (-10), where 2 is unsigned = " << un + n << '\n' << " -10 - 2.12 = " << n - 2.12 << '\n'; char a[4] = {'a', 'b', 'c', 'd'}; char* p = &a[1]; std::cout << "Pointer addition examples: " << *p << *(p + 2) << *(2 + p) << *(p - 1) << '\n'; char* p2 = &a[4]; std::cout << "Pointer difference: " << p2 - p << '\n'; } ``` Output: ``` 2 + (-10), where 2 is a char = -8 2 + (-10), where 2 is unsigned = 4294967288 -10 - 2.12 = -12.12 Pointer addition examples: bdda Pointer difference: 3 ``` #### Multiplicative operators The binary multiplicative arithmetic operator expressions have the form. | | | | | --- | --- | --- | | lhs `*` rhs | (1) | | | lhs `/` rhs | (2) | | | lhs `%` rhs | (3) | | 1) multiplication For the built-in operator, lhs and rhs must both have arithmetic or unscoped enumeration type. 2) division For the built-in operator, lhs and rhs must both have arithmetic or unscoped enumeration type. 3) remainder For the built-in operator, lhs and rhs must both have integral or unscoped enumeration type For all three operators, the usual arithmetic conversions are performed on both operands and determine the type of the result. The binary operator \* performs multiplication of its operands (after usual arithmetic conversions), except that, for floating-point multiplication, * multiplication of a NaN by any number gives NaN * multiplication of infinity by zero gives NaN and `[FE\_INVALID](../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised The binary operator / divides the first operand by the second (after usual arithmetic conversions). For integral operands, it yields the algebraic quotient. The quotient is truncated towards zero (fractional part is discarded). If the second operand is zero, the behavior is undefined, except that if floating-point division is taking place and the type supports IEEE floating-point arithmetic (see `[std::numeric\_limits::is\_iec559](../types/numeric_limits/is_iec559 "cpp/types/numeric limits/is iec559")`), then: * if one operand is NaN, the result is NaN * dividing a non-zero number by ±0.0 gives the correctly-signed infinity and `[FE\_DIVBYZERO](../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised * dividing 0.0 by 0.0 gives NaN and `[FE\_INVALID](../numeric/fenv/fe_exceptions "cpp/numeric/fenv/FE exceptions")` is raised The binary operator % yields the remainder of the integer division of the first operand by the second (after usual arithmetic conversions; note that the operand types must be integral types). If the quotient `a / b` is representable in the result type, `(a / b) * b + a % b == a`. If the second operand is zero, the behavior is undefined. If the quotient `a / b` is not representable in the result type, the behavior of both `a / b` and `a % b` is undefined (that means `[INT\_MIN](http://en.cppreference.com/w/cpp/types/climits) % -1` is undefined on 2's complement systems). Note: Until [CWG issue 614](https://cplusplus.github.io/CWG/issues/614.html) was resolved ([N2757](https://wg21.link/n2757)), if one or both operands to binary operator % were negative, the sign of the remainder was implementation-defined, as it depends on the rounding direction of integer division. The function `[std::div](../numeric/math/div "cpp/numeric/math/div")` provided well-defined behavior in that case. Note: for floating-point remainder, see `[std::remainder](../numeric/math/remainder "cpp/numeric/math/remainder")` and `[std::fmod](../numeric/math/fmod "cpp/numeric/math/fmod")`. In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for every pair of promoted arithmetic types `LA` and `RA` and for every pair of promoted integral types `LI` and `RI` the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` LRA operator*(LA, RA) ``` | | | | ``` LRA operator/(LA, RA) ``` | | | | ``` LRI operator%(LI, RI) ``` | | | where `LRx` is the result of usual arithmetic conversions on `Lx` and `Rx`. ``` #include <iostream> int main() { char c = 2; unsigned int un = 2; int n = -10; std::cout << "2 * (-10), where 2 is a char = " << c * n << '\n' << "2 * (-10), where 2 is unsigned = " << un * n << '\n' << "-10 / 2.12 = " << n / 2.12 << '\n' << "-10 / 21 = " << n / 21 << '\n' << "-10 % 21 = " << n % 21 << '\n'; } ``` Output: ``` 2 * (-10), where 2 is a char = -20 2 * (-10), where 2 is unsigned = 4294967276 -10 / 2.12 = -4.71698 -10 / 21 = 0 -10 % 21 = -10 ``` #### Bitwise logic operators The bitwise arithmetic operator expressions have the form. | | | | | --- | --- | --- | | `~` rhs | (1) | | | lhs `&` rhs | (2) | | | lhs `|` rhs | (3) | | | lhs `^` rhs | (4) | | 1) bitwise NOT 2) bitwise AND 3) bitwise OR 4) bitwise XOR For the built-in operators, lhs and rhs must both have integral or unscoped enumeration type. Usual arithmetic conversions are performed on both operands and determine the type of the result. The result of operator~ is the bitwise NOT (one's complement) value of the argument (after promotion). The result of operator& is the bitwise AND value of the operands (after usual arithmetic conversions). The result of operator|is the bitwise OR value of the operands (after usual arithmetic conversions). The result of operator^ is the bitwise XOR value of the operands (after usual arithmetic conversions). There is an ambiguity in the grammar when `~` is followed by a [type name](type#type_naming "cpp/language/type") or [decltype](decltype "cpp/language/decltype") specifier (since C++11): it can either be operator~ or start a [destructor](destructor "cpp/language/destructor") identifier). The ambiguity is resolved by treating `~` as operator~. `~` can start a destructor identifier only in places where forming an operator~ is syntatically invalid. In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for every pair of promoted integral types `L` and `R` the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` R operator~(R) ``` | | | | ``` LR operator&(L, R) ``` | | | | ``` LR operator^(L, R) ``` | | | | ``` LR operator|(L, R) ``` | | | where `LR` is the result of usual arithmetic conversions on `L` and `R`. ``` #include <iostream> #include <iomanip> #include <bitset> int main() { uint16_t mask = 0x00f0; uint32_t x0 = 0x12345678; uint32_t x1 = x0 | mask; uint32_t x2 = x0 & ~mask; uint32_t x3 = x0 & mask; uint32_t x4 = x0 ^ mask; uint32_t x5 = ~x0; using bin16 = std::bitset<16>; using bin32 = std::bitset<32>; std::cout << std::hex << std::showbase << "Mask: " << mask << std::setw(49) << bin16(mask) << '\n' << "Value: " << x0 << std::setw(42) << bin32(x0) << '\n' << "Setting bits: " << x1 << std::setw(35) << bin32(x1) << '\n' << "Clearing bits: " << x2 << std::setw(34) << bin32(x2) << '\n' << "Selecting bits: " << x3 << std::setw(39) << bin32(x3) << '\n' << "XOR-ing bits: " << x4 << std::setw(35) << bin32(x4) << '\n' << "Inverting bits: " << x5 << std::setw(33) << bin32(x5) << '\n'; } ``` Output: ``` Mask: 0xf0 0000000011110000 Value: 0x12345678 00010010001101000101011001111000 Setting bits: 0x123456f8 00010010001101000101011011111000 Clearing bits: 0x12345608 00010010001101000101011000001000 Selecting bits: 0x70 00000000000000000000000001110000 XOR-ing bits: 0x12345688 00010010001101000101011010001000 Inverting bits: 0xedcba987 11101101110010111010100110000111 ``` #### Bitwise shift operators The bitwise shift operator expressions have the form. | | | | | --- | --- | --- | | lhs `<<` rhs | (1) | | | lhs `>>` rhs | (2) | | 1) left shift of lhs by rhs bits 2) right shift of lhs by rhs bits For the built-in operators, lhs and rhs must both have integral or unscoped enumeration type. Integral promotions are performed on both operands. The return type is the type of the left operand after integral promotions. | | | | --- | --- | | For unsigned `a`, the value of `a << b` is the value of a \* 2b, reduced modulo 2N where N is the number of bits in the return type (that is, bitwise left shift is performed and the bits that get shifted out of the destination type are discarded). For signed and non-negative `a`, if a \* 2b is representable in the unsigned version of the return type, then that value, [converted](implicit_conversion#Integral_conversions "cpp/language/implicit conversion") to signed, is the value of `a << b` (this makes it legal to create `[INT\_MIN](../types/climits "cpp/types/climits")` as `1 << 31`); otherwise the behavior is undefined. For negative `a`, the behavior of `a << b` is undefined. For unsigned `a` and for signed and non-negative `a`, the value of `a >> b` is the integer part of a/2b. For negative `a`, the value of `a >> b` is implementation-defined (in most implementations, this performs arithmetic right shift, so that the result remains negative). | (until C++20) | | The value of `a << b` is the unique value congruent to a \* 2b modulo 2N where N is the number of bits in the return type (that is, bitwise left shift is performed and the bits that get shifted out of the destination type are discarded). The value of `a >> b` is a/2b, rounded down (in other words, right shift on signed `a` is arithmetic right shift). | (since C++20) | In any case, if the value of the right operand is negative or is greater or equal to the number of bits in the promoted left operand, the behavior is undefined. In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for every pair of promoted integral types `L` and `R`, the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` L operator<<(L, R) ``` | | | | ``` L operator>>(L, R) ``` | | | ``` #include <iostream> enum { ONE = 1, TWO = 2 }; int main() { std::cout << std::hex << std::showbase; char c = 0x10; unsigned long long ull = 0x123; std::cout << "0x123 << 1 = " << (ull << 1) << '\n' << "0x123 << 63 = " << (ull << 63) << '\n' // overflow in unsigned << "0x10 << 10 = " << (c << 10) << '\n'; // char is promoted to int long long ll = -1000; std::cout << std::dec << "-1000 >> 1 = " << (ll >> ONE) << '\n'; } ``` Output: ``` 0x123 << 1 = 0x246 0x123 << 63 = 0x8000000000000000 0x10 << 10 = 0x4000 -1000 >> 1 = -500 ``` ### Standard library Arithmetic operators are overloaded for many standard library types. #### Unary arithmetic operators | | | | --- | --- | | [operator+operator-](../chrono/duration/operator_arith "cpp/chrono/duration/operator arith") | implements unary + and unary - (public member function of `std::chrono::duration<Rep,Period>`) | | [operator+operator-](../numeric/complex/operator_arith2 "cpp/numeric/complex/operator arith2") | applies unary operators to complex numbers (function template) | | [operator+operator-operator~operator!](../numeric/valarray/operator_arith "cpp/numeric/valarray/operator arith") | applies a unary arithmetic operator to each element of the valarray (public member function of `std::valarray<T>`) | #### Additive operators | | | | --- | --- | | [operator+operator-](../chrono/time_point/operator_arith2 "cpp/chrono/time point/operator arith2") (C++11) | performs add and subtract operations involving a time point (function template) | | [operator+operator-operator\*operator/operator%](../chrono/duration/operator_arith4 "cpp/chrono/duration/operator arith4") (C++11) | implements arithmetic operations with durations as arguments (function template) | | [operator+operator-](../chrono/year_month_day/operator_arith_2 "cpp/chrono/year month day/operator arith 2") (C++20) | adds or subtracts a `year_month_day` and some number of years or months (function) | | [operator+](../string/basic_string/operator_plus_ "cpp/string/basic string/operator+") | concatenates two strings or a string and a char (function template) | | [operator+operator-](../iterator/reverse_iterator/operator_arith "cpp/iterator/reverse iterator/operator arith") | advances or decrements the iterator (public member function of `std::reverse_iterator<Iter>`) | | [operator+operator-](../iterator/move_iterator/operator_arith "cpp/iterator/move iterator/operator arith") | advances or decrements the iterator (public member function of `std::move_iterator<Iter>`) | | [operator+operator-operator\*operator/](../numeric/complex/operator_arith3 "cpp/numeric/complex/operator arith3") | performs complex number arithmetics on two complex values or a complex and a scalar (function template) | | [operator+operator-operator\*operator/operator%operator&operator|operator^operator<<operator>>operator&&operator||](../numeric/valarray/operator_arith3 "cpp/numeric/valarray/operator arith3") | applies binary operators to each element of two valarrays, or a valarray and a value (function template) | #### Multiplicative operators | | | | --- | --- | | [operator+operator-operator\*operator/operator%](../chrono/duration/operator_arith4 "cpp/chrono/duration/operator arith4") (C++11) | implements arithmetic operations with durations as arguments (function template) | | [operator+operator-operator\*operator/](../numeric/complex/operator_arith3 "cpp/numeric/complex/operator arith3") | performs complex number arithmetics on two complex values or a complex and a scalar (function template) | | [operator+operator-operator\*operator/operator%operator&operator|operator^operator<<operator>>operator&&operator||](../numeric/valarray/operator_arith3 "cpp/numeric/valarray/operator arith3") | applies binary operators to each element of two valarrays, or a valarray and a value (function template) | #### Bitwise logic operators | | | | --- | --- | | [operator&=operator|=operator^=operator~](../utility/bitset/operator_logic "cpp/utility/bitset/operator logic") | performs binary AND, OR, XOR and NOT (public member function of `std::bitset<N>`) | | [operator&operator|operator^](../utility/bitset/operator_logic2 "cpp/utility/bitset/operator logic2") | performs binary logic operations on bitsets (function template) | | [operator~](../numeric/valarray/operator_arith "cpp/numeric/valarray/operator arith") | applies a unary arithmetic operator to each element of the valarray (public member function of `std::valarray<T>`) | | [operator^operator&operator|](../numeric/valarray/operator_arith3 "cpp/numeric/valarray/operator arith3") | applies binary operators to each element of two valarrays, or a valarray and a value (function template) | #### Bitwise shift operators | | | | --- | --- | | [operator<<operator>>](../numeric/valarray/operator_arith3 "cpp/numeric/valarray/operator arith3") | applies binary operators to each element of two valarrays, or a valarray and a value (function template) | | [operator<<operator>>](../utility/bitset/operator_ltltgtgt "cpp/utility/bitset/operator ltltgtgt") | performs binary shift left and shift right (public member function of `std::bitset<N>`) | #### Stream insertion/extraction operators Throughout the standard library, bitwise shift operators are commonly overloaded with I/O stream (`[std::ios\_base](http://en.cppreference.com/w/cpp/io/ios_base)&` or one of the classes derived from it) as both the left operand and return type. Such operators are known as *stream insertion* and *stream extraction* operators: | | | | --- | --- | | [operator>>](../io/basic_istream/operator_gtgt "cpp/io/basic istream/operator gtgt") | extracts formatted data (public member function of `std::basic_istream<CharT,Traits>`) | | [operator>>(std::basic\_istream)](../io/basic_istream/operator_gtgt2 "cpp/io/basic istream/operator gtgt2") | extracts characters and character arrays (function template) | | [operator<<](../io/basic_ostream/operator_ltlt "cpp/io/basic ostream/operator ltlt") | inserts formatted data (public member function of `std::basic_ostream<CharT,Traits>`) | | [operator<<(std::basic\_ostream)](../io/basic_ostream/operator_ltlt2 "cpp/io/basic ostream/operator ltlt2") | inserts character data or insert into rvalue stream (function template) | | [operator<<operator>>](../numeric/complex/operator_ltltgtgt "cpp/numeric/complex/operator ltltgtgt") | serializes and deserializes a complex number (function template) | | [operator<<operator>>](../utility/bitset/operator_ltltgtgt2 "cpp/utility/bitset/operator ltltgtgt2") | performs stream input and output of bitsets (function template) | | [operator<<operator>>](../string/basic_string/operator_ltltgtgt "cpp/string/basic string/operator ltltgtgt") | performs stream input and output on strings (function template) | | [operator<<operator>>](../numeric/random/linear_congruential_engine/operator_ltltgtgt "cpp/numeric/random/linear congruential engine/operator ltltgtgt") (C++11) | performs stream input and output on pseudo-random number engine (function template) | | [operator<<operator>>](../numeric/random/uniform_int_distribution/operator_ltltgtgt "cpp/numeric/random/uniform int distribution/operator ltltgtgt") (C++11) | performs stream input and output on pseudo-random number distribution (function template) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 614](https://cplusplus.github.io/CWG/issues/614.html) | C++98 | the algebraic quotient of integer division wasrounded in implementation-defined direction | the algebraic quotient of integerdivision is truncated towards zero(fractional part is discarded) | | [CWG 1450](https://cplusplus.github.io/CWG/issues/1450.html) | C++98 | the result of `a / b` was unspecified ifit is not representable in the result type | the behavior of both `a / b` and`a % b` is undefined in this case | | [CWG 1457](https://cplusplus.github.io/CWG/issues/1457.html) | C++98 | the behavior of shifting the leftmost `1` bit of apositive signed value into the sign bit was undefined | made well-defined | | [CWG 1504](https://cplusplus.github.io/CWG/issues/1504.html) | C++98 | a pointer to a base class subobject of an arrayelement could be used in pointer arithmetic | the behavior isundefined in this case | | [CWG 1515](https://cplusplus.github.io/CWG/issues/1515.html) | C++98 | only unsigned integers which declared `unsigned` should obey the laws of arithmetic modulo 2n | applies to all unsigned integers | | [CWG 1865](https://cplusplus.github.io/CWG/issues/1865.html) | C++98 | the resolution of [CWG issue 1504](https://cplusplus.github.io/CWG/issues/1504.html) made the behaviorsof pointer arithmetic involving pointers to array elementundefined if the pointed-to type and the array elementtype have different cv-qualifications in non-top levels | made well-defined | | [CWG 1971](https://cplusplus.github.io/CWG/issues/1971.html) | C++98 | it was unclear whether the rule resolving theambiguity of `~` applies to cases such as `~X(0)` | the rule applies to such cases | | [CWG 2419](https://cplusplus.github.io/CWG/issues/2419.html) | C++98 | a pointer to non-array object was only treated as apointer to the first element of an array with size 1in pointer arithmetic if the pointer is obtained by `&` | applies to all pointersto non-array objects | ### See also [Operator precedence](operator_precedence "cpp/language/operator precedence"). [Operator overloading](operators "cpp/language/operators"). | Common operators | | --- | | [assignment](operator_assignment "cpp/language/operator assignment") | [incrementdecrement](operator_incdec "cpp/language/operator incdec") | **arithmetic** | [logical](operator_logical "cpp/language/operator logical") | [comparison](operator_comparison "cpp/language/operator comparison") | [memberaccess](operator_member_access "cpp/language/operator member access") | [other](operator_other "cpp/language/operator other") | | `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b a <=> b`. | `a[b] *a &a a->b a.b a->*b a.*b`. | `a(...) a, b a ? b : c`. | | Special operators | | [`static_cast`](static_cast "cpp/language/static cast") converts one type to another related type [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") converts within inheritance hierarchies [`const_cast`](const_cast "cpp/language/const cast") adds or removes [cv](cv "cpp/language/cv") qualifiers [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") converts type to unrelated type [C-style cast](explicit_cast "cpp/language/explicit cast") converts one type to another by a mix of `static_cast`, `const_cast`, and `reinterpret_cast` [`new`](new "cpp/language/new") creates objects with dynamic storage duration [`delete`](delete "cpp/language/delete") destructs objects previously created by the new expression and releases obtained memory area [`sizeof`](sizeof "cpp/language/sizeof") queries the size of a type [`sizeof...`](sizeof... "cpp/language/sizeof...") queries the size of a [parameter pack](parameter_pack "cpp/language/parameter pack") (since C++11) [`typeid`](typeid "cpp/language/typeid") queries the type information of a type [`noexcept`](noexcept "cpp/language/noexcept") checks if an expression can throw an exception (since C++11) [`alignof`](alignof "cpp/language/alignof") queries alignment requirements of a type (since C++11). | | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/operator_arithmetic "c/language/operator arithmetic") for Arithmetic operators |
programming_docs
cpp override specifier (since C++11) `override` specifier (since C++11) =================================== Specifies that a [virtual function](virtual "cpp/language/virtual") overrides another virtual function. ### Syntax The identifier `override`, if used, appears immediately after the [declarator](function "cpp/language/function") in the syntax of a member function declaration or a member function definition inside a class definition. | | | | | --- | --- | --- | | declarator virt-specifier-seq(optional) pure-specifier(optional) | (1) | | | declarator virt-specifier-seq(optional) function-body | (2) | | 1) In a member function declaration, `override` may appear in virt-specifier-seq immediately after the declarator, and before the [pure-specifier](abstract_class "cpp/language/abstract class"), if used. 2) In a member function definition inside a class definition, `override` may appear in virt-specifier-seq immediately after the declarator and just before function-body. In both cases, virt-specifier-seq, if used, is either `override` or [`final`](final "cpp/language/final"), or `final override` or `override final`. ### Explanation In a member function declaration or definition, `override` specifier ensures that the function is virtual and is overriding a virtual function from a base class. The program is ill-formed (a compile-time error is generated) if this is not true. `override` is an identifier with a special meaning when used after member function declarators: it's not a reserved keyword otherwise. ### Example ``` #include <iostream> struct A { virtual void foo(); void bar(); virtual ~A(); }; // member functions definitions of struct A: void A::foo() { std::cout << "A::foo();\n"; } A::~A() { std::cout << "A::~A();\n"; } struct B : A { // void foo() const override; // Error: B::foo does not override A::foo // (signature mismatch) void foo() override; // OK: B::foo overrides A::foo // void bar() override; // Error: A::bar is not virtual ~B() override; // OK: `override` can also be applied to virtual // special member functions, e.g. destructors void override(); // OK, member function name, not a reserved keyword }; // member functions definitions of struct B: void B::foo() { std::cout << "B::foo();\n"; } B::~B() { std::cout << "B::~B();\n"; } void B::override() { std::cout << "B::override();\n"; } int main() { B b; b.foo(); b.override(); // OK, invokes the member function `override()` int override{42}; // OK, defines an integer variable std::cout << "override: " << override << '\n'; } ``` Output: ``` B::foo(); B::override(); override: 42 B::~B(); A::~A(); ``` ### See also | | | | --- | --- | | [`final` specifier](final "cpp/language/final")(C++11) | declares that a method cannot be overridden | cpp Function template Function template ================= A function template defines a family of functions. ### Syntax | | | | | --- | --- | --- | | `template` `<` parameter-list `>` function-declaration | (1) | | | `template` `<` parameter-list `>` `requires` constraint function-declaration | (2) | (since C++20) | | function-declaration-with-placeholders | (3) | (since C++20) | | `export` `template` `<` parameter-list `>` function-declaration | (4) | (removed in C++11) | ### Explanation | | | | | --- | --- | --- | | parameter-list | - | a non-empty comma-separated list of the [template parameters](template_parameters "cpp/language/template parameters"), each of which is either [non-type parameter](template_parameters#Non-type_template_parameter "cpp/language/template parameters"), a [type parameter](template_parameters#Type_template_parameter "cpp/language/template parameters"), a [template parameter](template_parameters#Template_template_parameter "cpp/language/template parameters"), or a [parameter pack](parameter_pack "cpp/language/parameter pack") of any of those (since C++11). As with any template, parameters may be [constrained](template_parameters#Constrained_template_parameter "cpp/language/template parameters") (since C++20) | | function-declaration | - | a [function declaration](function "cpp/language/function"). The function name declared becomes a template name. | | constraint | - | a [constraint expression](constraints "cpp/language/constraints") which restricts the template parameters accepted by this function template | | function-declaration-with-placeholders | - | a [function declaration](function "cpp/language/function") where the type of at least one parameter uses the placeholder [auto](auto "cpp/language/auto") or [Concept auto](../concepts "cpp/concepts"): the template parameter list will have one invented parameter for each placeholder (see Abbreviated function templates below) | | | | | --- | --- | | `export` was an optional modifier which declared the template as *exported* (when used with a class template, it declared all of its members exported as well). Files that instantiated exported templates did not need to include their definitions: the declaration was sufficient. Implementations of `export` were rare and disagreed with each other on details. | (until C++11) | | | | | --- | --- | | Abbreviated function template When placeholder types (either [auto](auto "cpp/language/auto") or [Concept auto](../concepts "cpp/concepts")) appear in the parameter list of a function declaration or of a function template declaration, the declaration declares a function template, and one invented template parameter for each placeholder is appended to the template parameter list: ``` void f1(auto); // same as template<class T> void f1(T) void f2(C1 auto); // same as template<C1 T> void f2(T), if C1 is a concept void f3(C2 auto...); // same as template<C2... Ts> void f3(Ts...), if C2 is a concept void f4(const C3 auto*, C4 auto&); // same as template<C3 T, C4 U> void f4(const T*, U&); template<class T, C U> void g(T x, U y, C auto z); // same as template<class T, C U, C W> void g(T x, U y, W z); ``` Abbreviated function templates can be specialized like all function templates. ``` template<> void f4<int>(const int*, const double&); // specialization of f4<int, const double> ``` | (since C++20) | ### Function template instantiation A function template by itself is not a type, or a function, or any other entity. No code is generated from a source file that contains only template definitions. In order for any code to appear, a template must be instantiated: the template arguments must be determined so that the compiler can generate an actual function (or class, from a class template). #### Explicit instantiation | | | | | --- | --- | --- | | `template` return-type name `<` argument-list `>` `(` parameter-list `)` `;` | (1) | | | `template` return-type name `(` parameter-list `)` `;` | (2) | | | `extern` `template` return-type name `<` argument-list `>` `(` parameter-list `)` `;` | (3) | (since C++11) | | `extern` `template` return-type name `(` parameter-list `)` `;` | (4) | (since C++11) | 1) Explicit instantiation definition (without [template argument deduction](template_argument_deduction "cpp/language/template argument deduction") if every non-default template parameter is explicitly specified) 2) Explicit instantiation definition with template argument deduction for all parameters 3) Explicit instantiation declaration (without template argument deduction if every non-default template parameter is explicitly specified) 4) Explicit instantiation declaration with template argument deduction for all parameters An explicit instantiation definition forces instantiation of the function or member function they refer to. It may appear in the program anywhere after the template definition, and for a given argument-list, is only allowed to appear once in the program, no diagnostic required. | | | | --- | --- | | An explicit instantiation declaration (an extern template) prevents implicit instantiations: the code that would otherwise cause an implicit instantiation has to use the explicit instantiation definition provided somewhere else in the program. | (since C++11) | A trailing template-argument can be left unspecified in an explicit instantiation of a function template specialization or of a member function template specialization if it can be [deduced](template_argument_deduction "cpp/language/template argument deduction") from the function parameter: ``` template<typename T> void f(T s) { std::cout << s << '\n'; } template void f<double>(double); // instantiates f<double>(double) template void f<>(char); // instantiates f<char>(char), template argument deduced template void f(int); // instantiates f<int>(int), template argument deduced ``` Explicit instantiation of a function template or of a member function of a class template cannot use `inline` or `constexpr`. If the declaration of the explicit instantiation names an implicitly-declared special member function, the program is ill-formed. Explicit instantiation of a [constructor](constructor "cpp/language/constructor") cannot use a template parameter list (syntax (1)), which is also never necessary because they can be deduced (syntax (2)). | | | | --- | --- | | Explicit instantiation of a [prospective destructor](destructor#Prospective_destructor "cpp/language/destructor") must name the selected destructor of the class. | (since C++20) | Explicit instantiation declarations do not suppress the implicit instantiation of [inline](inline "cpp/language/inline") functions, [auto](auto "cpp/language/auto")-declarations, references, and class template specializations. (thus, when the inline function that is a subject of explicit instantiation declaration is ODR-used, it is implicitly instantiated for inlining, but its out-of-line copy is not generated in this translation unit). Explicit instantiation definition of a function template with [default arguments](default_arguments "cpp/language/default arguments") is not a use of the arguments, and does not attempt to initialize them: ``` char* p = 0; template<class T> T g(T x = &p) { return x; } template int g<int>(int); // OK even though &p isn’t an int. ``` #### Implicit instantiation When code refers to a function in context that requires [the function definition to exist](definition#ODR-use "cpp/language/definition"), or if the existence of the definition affects the semantics of the program (since C++11), and this particular function has not been explicitly instantiated, implicit instantiation occurs. The list of template arguments does not have to be supplied if it can be [deduced](template_argument_deduction "cpp/language/template argument deduction") from context. ``` #include <iostream> template<typename T> void f(T s) { std::cout << s << '\n'; } int main() { f<double>(1); // instantiates and calls f<double>(double) f<>('a'); // instantiates and calls f<char>(char) f(7); // instantiates and calls f<int>(int) void (*pf)(std::string) = f; // instantiates f<string>(string) pf("∇"); // calls f<string>(string) } ``` | | | | --- | --- | | The existence of a definition of function is considered to affect the semantics of the program if the function is [needed for constant evaluation](constant_expression#Functions_and_variables_needed_for_constant_evaluation "cpp/language/constant expression") by an expression, even if constant evaluation of the expression is not required or if constant expression evaluation does not use the definition. ``` template<typename T> constexpr int f() { return T::value; } template<bool B, typename T> void g(decltype(B ? f<T>() : 0)); template<bool B, typename T> void g(...); template<bool B, typename T> void h(decltype(int{B ? f<T>() : 0})); template<bool B, typename T> void h(...); void x() { g<false, int>(0); // OK: B ? f<T>() : 0 is not potentially constant evaluated h<false, int>(0); // error: instantiates f<int> even though B evaluates to false // and list-initialization of int from int cannot be narrowing } ``` | (since C++11) | Note: omitting `<>` entirely allows [overload resolution](overload_resolution "cpp/language/overload resolution") to examine both template and non-template overloads. ### Template argument deduction In order to instantiate a function template, every template argument must be known, but not every template argument has to be specified. When possible, the compiler will deduce the missing template arguments from the function arguments. This occurs when a function call is attempted and when an address of a function template is taken. ``` template<typename To, typename From> To convert(From f); void g(double d) { int i = convert<int>(d); // calls convert<int,double>(double) char c = convert<char>(d); // calls convert<char,double>(double) int(*ptr)(float) = convert; // instantiates convert<int, float>(float) } ``` This mechanism makes it possible to use template operators, since there is no syntax to specify template arguments for an operator other than by re-writing it as a function call expression. ``` #include <iostream> int main() { std::cout << "Hello, world" << std::endl; // operator<< is looked up via ADL as std::operator<<, // then deduced to operator<<<char, std::char_traits<char>> both times // std::endl is deduced to &std::endl<char, std::char_traits<char>> } ``` Template argument deduction takes place after the function template [name lookup](lookup "cpp/language/lookup") (which may involve [argument-dependent lookup](adl "cpp/language/adl")) and before [overload resolution](overload_resolution "cpp/language/overload resolution"). See [template argument deduction](template_argument_deduction "cpp/language/template argument deduction") for details. ### Explicit template arguments Template arguments of a function template may be obtained from. * template argument deduction * default template arguments * specified explicitly, which can be done in the following contexts: + in a function call expression + when an address of a function is taken + when a reference to function is initialized + when a pointer to member function is formed + in an explicit specialization + in an explicit instantiation + in a friend declaration There is no way to explicitly specify template arguments to [overloaded operators](operators "cpp/language/operators"), [conversion functions](cast_operator "cpp/language/cast operator"), and constructors, because they are called without the use of the function name. The specified template arguments must match the template parameters in kind (i.e., type for type, non-type for non-type, and template for template). There cannot be more arguments than there are parameters (unless one parameter is a parameter pack, in which case there has to be an argument for each non-pack parameter) (since C++11). The specified non-type arguments must either match the types of the corresponding non-type template parameters, or be [convertible to them](template_parameters#Template_non-type_arguments "cpp/language/template parameters"). The function parameters that do not participate in template argument deduction (e.g. if the corresponding template arguments are explicitly specified) are subject to implicit conversions to the type of the corresponding function parameter (as in the usual [overload resolution](overload_resolution "cpp/language/overload resolution")). | | | | --- | --- | | A template parameter pack that is explicitly specified may be extended by template argument deduction if there are additional arguments: ``` template<class... Types> void f(Types... values); void g() { f<int*, float*>(0, 0, 0); // Types = {int*, float*, int} } ``` | (since C++11) | ### Template argument substitution When all template arguments have been specified, deduced or obtained from default template arguments, every use of a template parameter in the function parameter list is replaced with the corresponding template arguments. Substitution failure (that is, failure to replace template parameters with the deduced or provided template arguments) of a function template removes the function template from the [overload set](overload_resolution "cpp/language/overload resolution"). This allows a number of ways to manipulate overload sets using template metaprogramming: see [SFINAE](sfinae "cpp/language/sfinae") for details. After substitution, all function parameters of array and function type are adjusted to pointers and all top-level cv-qualifiers are dropped from function parameters (as in a regular [function declaration](function#Function_declaration "cpp/language/function")). The removal of the top-level cv-qualifiers does not affect the type of the parameter as it appears within the function: ``` template<class T> void f(T t); template<class X> void g(const X x); template<class Z> void h(Z z, Z* zp); // two different functions with the same type, but // within the function, t has different cv qualifications f<int>(1); // function type is void(int), t is int f<const int>(1); // function type is void(int), t is const int // two different functions with the same type and the same x // (pointers to these two functions are not equal, // and function-local statics would have different addresses) g<int>(1); // function type is void(int), x is const int g<const int>(1); // function type is void(int), x is const int // only top-level cv-qualifiers are dropped: h<const int>(1, NULL); // function type is void(int, const int*) // z is const int, zp is const int* ``` ### Function template overloading Function templates and non-template functions may be overloaded. A non-template function is always distinct from a template specialization with the same type. Specializations of different function templates are always distinct from each other even if they have the same type. Two function templates with the same return type and the same parameter list are distinct and can be distinguished with explicit template argument list. When an expression that uses type or non-type template parameters appears in the function parameter list or in the return type, that expression remains a part of the function template signature for the purpose of overloading: ``` template<int I, int J> A<I+J> f(A<I>, A<J>); // overload #1 template<int K, int L> A<K+L> f(A<K>, A<L>); // same as #1 template<int I, int J> A<I-J> f(A<I>, A<J>); // overload #2 ``` Two expressions involving template parameters are called *equivalent* if two function definitions that contain these expressions would be the same under [ODR](definition#One_Definition_Rule "cpp/language/definition"), that is, the two expressions contain the same sequence of tokens whose names are resolved to same entities via name lookup, except template parameters may be differently named. Two [lambda expressions](lambda "cpp/language/lambda") are never equivalent. (since C++20). ``` template<int I, int J> void f(A<I+J>); // template overload #1 template<int K, int L> void f(A<K+L>); // equivalent to #1 ``` When determining if two [dependent expressions](dependent_name "cpp/language/dependent name") are equivalent, only the dependent names involved are considered, not the results of name lookup. If multiple declarations of the same template differ in the result of name lookup, the first such declaration is used: ``` template<class T> decltype(g(T())) h(); // decltype(g(T())) is a dependent type int g(int); template<class T> decltype(g(T())) h() { // redeclaration of h() uses earlier lookup return g(T()); // although the lookup here does find g(int) } int i = h<int>(); // template argument substitution fails; g(int) // was not in scope at the first declaration of h() ``` Two function templates are considered *equivalent* if. * they are declared in the same scope * they have the same name * they have *equivalent* template parameter lists, meaning the lists are of the same length, and for each corresponding parameter pair, all of the following is true: + the two parameters are of the same kind (both types, both non-types, or both templates) | | | | --- | --- | | * they are either both parameter packs or neither | (since C++11) | * if non-type, their types are equivalent, * if template, their template parameters are equivalent, | | | | --- | --- | | * if one is declared with concept-name, they both are, and the concept-names are equivalent. | (since C++20) | * the expressions involving template parameters in their return types and parameter lists are *equivalent* | | | | --- | --- | | * the expressions in their requires-clauses that follow the template parameter lists, if present, are equivalent * the expressions in their requires-clauses that follow the function declarators, if present, are equivalent | (since C++20) | Two expressions involving template parameters are called *functionally equivalent* if they are not *equivalent*, but for any given set of template arguments, the evaluation of the two expressions results in the same value. Two function templates are considered *functionally equivalent* if they are *equivalent*, except that one or more expressions that involve template parameters in their return types and parameter lists are *functionally equivalent*. | | | | --- | --- | | In addition, two function templates are *functionally equivalent* but not *equivalent* if their constraints are specified differently, but they accept and are satisfied by the same set of template argument lists. | (since C++20) | If a program contains declarations of function templates that are *functionally equivalent* but not *equivalent*, the program is ill-formed; no diagnostic is required. ``` // equivalent template<int I> void f(A<I>, A<I+10>); // overload #1 template<int I> void f(A<I>, A<I+10>); // redeclaration of overload #1 // not equivalent template<int I> void f(A<I>, A<I+10>); // overload #1 template<int I> void f(A<I>, A<I+11>); // overload #2 // functionally-equivalent but not equivalent // This program is ill-formed, no diagnostic required template<int I> void f(A<I>, A<I+10>); // overload #1 template<int I> void f(A<I>, A<I+1+2+3+4>); // functionally equivalent ``` When the same function template specialization matches more than one overloaded function template (this often results from [template argument deduction](template_argument_deduction "cpp/language/template argument deduction")), *partial ordering of overloaded function templates* is performed to select the best match. Specifically, partial ordering takes place in the following situations: 1) [overload resolution](overload_resolution "cpp/language/overload resolution") for a call to a function template specialization: ``` template<class X> void f(X a); template<class X> void f(X* a); int* p; f(p); ``` 2) when the [address of a function template specialization](overloaded_address "cpp/language/overloaded address") is taken: ``` template<class X> void f(X a); template<class X> void f(X* a); void (*p)(int*) = &f; ``` 3) when a [placement operator delete](../memory/new/operator_delete "cpp/memory/new/operator delete") that is a function template specialization is selected to match a placement operator new: 4) when a [friend function declaration](friend#Template_friends "cpp/language/friend"), an [explicit instantiation](function_template#Explicit_instantiation "cpp/language/function template"), or an [explicit specialization](template_specialization "cpp/language/template specialization") refers to a function template specialization: ``` template<class X> void f(X a); // first template f template<class X> void f(X* a); // second template f template<> void f<>(int *a) {} // explicit specialization // template argument deduction comes up with two candidates: // f<int*>(int*) and f<int>(int*) // partial ordering selects f<int>(int*) as more specialized ``` Informally "A is more specialized than B" means "A accepts fewer types than B". Formally, to determine which of any two function templates is more specialized, the partial ordering process first transforms one of the two templates as follows: * For each type, non-type, and template parameter, including parameter packs, (since C++11) a unique fictitious type, value, or template is generated and substituted into function type of the template * If only one of the two function templates being compared is a member function, and that function template is a non-static member of some class `A`, a new first parameter is inserted into its parameter list. Given *cv* as the cv-qualifiers of the function template and *ref* as the ref-qualifier of the function template (since C++11), the new parameter is of type is *cv* `A&` unless *ref* is `&&`, or *ref* is not present and the first parameter of the other template has rvalue reference type, in this case the type is *cv* `A&&` (since C++11). This helps the ordering of operators, which are looked up both as member and as non-member functions: ``` struct A {}; template<class T> struct B { template<class R> int operator*(R&); // #1 }; template<class T, class R> int operator*(T&, R&); // #2 int main() { A a; B<A> b; b * a; // template argument deduction for int B<A>::operator*(R&) gives R=A // for int operator*(T&, R&), T=B<A>, R=A // For the purpose of partial ordering, the member template B<A>::operator* // is transformed into template<class R> int operator*(B<A>&, R&); // partial ordering between // int operator*( T&, R&) T=B<A>, R=A // and int operator*(B<A>&, R&) R=A // selects int operator*(B<A>&, A&) as more specialized } ``` After one of the two templates was transformed as described above, [template argument deduction](template_argument_deduction "cpp/language/template argument deduction") is executed using the transformed template as the argument template and the original template type of the other template as the parameter template. The process is then repeated using the second template (after transformations) as the argument and the first template in its original form as the parameter. The types used to determine the order depend on the context: * in the context of a function call, the types are those function parameter types for which the function call has arguments (default function arguments, parameter packs, (since C++11) and ellipsis parameters are not considered -- see examples below) * in the context of a call to a user-defined conversion function, the return types of the conversion function templates are used * in other contexts, the function template type is used Each type from the list above from the parameter template is deduced. Before deduction begins, each parameter `P` of the parameter template and the corresponding argument `A` of the argument template is adjusted as follows: * If both `P` and `A` are reference types before, determine which is more cv-qualified (in all other cases, cv-qualificiations are ignored for partial ordering purposes) * If `P` is a reference type, it is replaced by the type referred to * If `A` is a reference type, it is replaced by the type referred to * If `P` is cv-qualified, `P` is replaced with cv-unqualified version of itself * If `A` is cv-qualified, `A` is replaced with cv-unqualified version of itself After these adjustments, deduction of `P` from `A` is done following [template argument deduction from a type](template_argument_deduction#Deduction_from_a_type "cpp/language/template argument deduction"). | | | | --- | --- | | If `P` is a function parameter pack, the type `A` of each remaining parameter type of the argument template is compared with the type `P` of the declarator-id of the function parameter pack. Each comparison deduces template arguments for subsequent positions in the template parameter packs expanded by the function parameter pack. If `A` was transformed from a function parameter pack, it is compared with each remaining parameter type of the parameter template. | (since C++11) | If the argument `A` of the transformed template-1 can be used to deduce the corresponding parameter `P` of template-2, but not vice versa, then this `A` is more specialized than `P` with regards to the type(s) that are deduced by this `P/A` pair. If deduction succeeds in both directions, and the original `P` and `A` were reference types, then additional tests are made: * If `A` was lvalue reference and `P` was rvalue reference, `A` is considered to be more specialized than `P` * If `A` was more cv-qualified than `P`, `A` is considered to be more specialized than `P` In all other cases, neither template is more specialized than the other with regards to the type(s) deduced by this `P/A` pair. After considering every `P` and `A` in both directions, if, for each type that was considered, * template-1 is at least as specialized as template-2 for all types * template-1 is more specialized than template-2 for some types * template-2 is not more specialized than template-1 for any types OR is not at least as specialized for any types Then template-1 is more specialized than template-2. If the conditions above are true after switching template order, than template-2 is more specialized than template-1. Otherwise, neither template is more specialized than the other. | | | | --- | --- | | In case of a tie, if one function template has a trailing parameter pack and the other does not, the one with the omitted parameter is considered to be more specialized than the one with the empty parameter pack. | (since C++11) | If, after considering all pairs of overloaded templates, there is one that is unambiguously more specialized than all others, that template's specialization is selected, otherwise compilation fails. In the following examples, the fictitious arguments will be called U1, U2: ``` template<class T> void f(T); // template #1 template<class T> void f(T*); // template #2 template<class T> void f(const T*); // template #3 void m() { const int* p; f(p); // overload resolution picks: #1: void f(T ) [T = const int *] // #2: void f(T*) [T = const int] // #3: void f(const T *) [T = int] // partial ordering: // #1 from transformed #2: void(T) from void(U1*): P=T A=U1*: deduction ok: T=U1* // #2 from transformed #1: void(T*) from void(U1): P=T* A=U1: deduction fails // #2 is more specialized than #1 with regards to T // #1 from transformed #3: void(T) from void(const U1*): P=T, A=const U1*: ok // #3 from transformed #1: void(const T*) from void(U1): P=const T*, A=U1: fails // #3 is more specialized than #1 with regards to T // #2 from transformed #3: void(T*) from void(const U1*): P=T* A=const U1*: ok // #3 from transformed #2: void(const T*) from void(U1*): P=const T* A=U1*: fails // #3 is more specialized than #2 with regards to T // result: #3 is selected // in other words, f(const T*) is more specialized than f(T) or f(T*) } ``` ``` template<class T> void f(T, T*); // #1 template<class T> void f(T, int*); // #2 void m(int* p) { f(0, p); // deduction for #1: void f(T, T*) [T = int] // deduction for #2: void f(T, int*) [T = int] // partial ordering: // #1 from #2: void(T,T*) from void(U1,int*): P1=T, A1=U1: T=U1 // P2=T*, A2=int*: T=int: fails // #2 from #1: void(T,int*) from void(U1,U2*): P1=T A1=U1: T=U1 // P2=int* A2=U2*: fails // neither is more specialized w.r.t T, the call is ambiguous } ``` ``` template<class T> void g(T); // template #1 template<class T> void g(T&); // template #2 void m() { float x; g(x); // deduction from #1: void g(T ) [T = float] // deduction from #2: void g(T&) [T = float] // partial ordering: // #1 from #2: void(T) from void(U1&): P=T, A=U1 (after adjustment), ok // #2 from #1: void(T&) from void(U1): P=T (after adjustment), A=U1: ok // neither is more specialized w.r.t T, the call is ambiguous } ``` ``` template<class T> struct A { A(); }; template<class T> void h(const T&); // #1 template<class T> void h(A<T>&); // #2 void m() { A<int> z; h(z); // deduction from #1: void h(const T &) [T = A<int>] // deduction from #2: void h(A<T> &) [T = int] // partial ordering: // #1 from #2: void(const T&) from void(A<U1>&): P=T A=A<U1>: ok T=A<U1> // #2 from #1: void(A<T>&) from void(const U1&): P=A<T> A=const U1: fails // #2 is more specialized than #1 w.r.t T const A<int> z2; h(z2); // deduction from #1: void h(const T&) [T = A<int>] // deduction from #2: void h(A<T>&) [T = int], but substitution fails // only one overload to choose from, partial ordering not tried, #1 is called } ``` Since in a call context considers only parameters for which there are explicit call arguments, those function parameter packs, (since C++11) ellipsis parameters, and parameters with default arguments, for which there is no explicit call argument, are ignored: ``` template<class T> void f(T); // #1 template<class T> void f(T*, int = 1); // #2 void m(int* ip) { int* ip; f(ip); // calls #2 (T* is more specialized than T) } ``` ``` template<class T> void g(T); // #1 template<class T> void g(T*, ...); // #2 void m(int* ip) { g(ip); // calls #2 (T* is more specialized than T) } ``` ``` template<class T, class U> struct A {}; template<class T, class U> void f(U, A<U, T>* p = 0); // #1 template<class U> void f(U, A<U, U>* p = 0); // #2 void h() { f<int>(42, (A<int, int>*)0); // calls #2 f<int>(42); // error: ambiguous } ``` ``` template<class T> void g(T, T = T()); // #1 template<class T, class... U> void g(T, U...); // #2 void h() { g(42); // error: ambiguous } ``` ``` template<class T, class... U> void f(T, U...); // #1 template<class T> void f(T); // #2 void h(int i) { f(&i); // calls #2 due to the tie-breaker between parameter pack and no parameter // (note: was ambiguous between DR692 and DR1395) } ``` ``` template<class T, class... U> void g(T*, U...); // #1 template<class T> void g(T); // #2 void h(int i) { g(&i); // OK: calls #1 (T* is more specialized than T) } ``` ``` template<class... T> int f(T*...); // #1 template<class T> int f(const T&); // #2 f((int*)0); // OK: selects #2; non-variadic template is more specialized than variadic template // (was ambiguous before DR1395 because deduction failed in both directions) ``` ``` template<class... Args> void f(Args... args); // #1 template<class T1, class... Args> void f(T1 a1, Args... args); // #2 template<class T1, class T2> void f(T1 a1, T2 a2); // #3 f(); // calls #1 f(1, 2, 3); // calls #2 f(1, 2); // calls #3; non-variadic template #3 is more // specialized than the variadic templates #1 and #2 ``` During template argument deduction within the partial ordering process, template parameters don't require to be matched with arguments, if the argument is not used in any of the types considered for partial ordering. ``` template<class T> T f(int); // #1 template<class T, class U> T f(U); // #2 void g() { f<int>(1); // specialization of #1 is explicit: T f(int) [T = int] // specialization of #2 is deduced: T f(U) [T = int, U = int] // partial ordering (only considering the argument type): // #1 from #2: T(int) from U1(U2): fails // #2 from #1: T(U) from U1(int): ok: U=int, T unused // calls #1 } ``` | | | | --- | --- | | Partial ordering of function templates containing template parameter packs is independent of the number of deduced arguments for those template parameter packs. ``` template<class...> struct Tuple {}; template<class... Types> void g(Tuple<Types...>); // #1 template<class T1, class... Types> void g(Tuple<T1, Types...>); // #2 template<class T1, class... Types> void g(Tuple<T1, Types&...>); // #3 g(Tuple<>()); // calls #1 g(Tuple<int, float>()); // calls #2 g(Tuple<int, float&>()); // calls #3 g(Tuple<int>()); // calls #3 ``` | (since C++11) | To compile a call to a function template, the compiler has to decide between non-template overloads, template overloads, and the specializations of the template overloads. ``` template<class T> void f(T); // #1: template overload template<class T> void f(T*); // #2: template overload void f(double); // #3: non-template overload template<> void f(int); // #4: specialization of #1 f('a'); // calls #1 f(new int(1)); // calls #2 f(1.0); // calls #3 f(1); // calls #4 ``` ### Function overloads vs function specializations Note that only non-template and primary template overloads participate in overload resolution. The specializations are not overloads and are not considered. Only after the overload resolution selects the best-matching primary function template, its specializations are examined to see if one is a better match. ``` template<class T> void f(T); // #1: overload for all types template<> void f(int*); // #2: specialization of #1 for pointers to int template<class T> void f(T*); // #3: overload for all pointer types f(new int(1)); // calls #3, even though specialization of #1 would be a perfect match ``` It is important to remember this rule while ordering the header files of a translation unit. For more examples of the interplay between function overloads and function specializations, expand below: --- | | | --- | | | | Consider first some scenarios where the argument-dependent lookup is not employed. For that, we use the call `(f)(t)`. As described in [ADL](adl "cpp/language/adl"), wrapping the function name in parentheses is suppressing the argument-dependent lookup.* Multiple overloads of `f()` declared before the *point-of-reference* (POR) in `g()`. ``` #include <iostream> struct A {}; template<class T> void f(T) { std::cout << "#1\n"; } // overload #1 before f() POR template<class T> void f(T*) { std::cout << "#2\n"; } // overload #2 before f() POR template<class T> void g(T* t) { (f)(t); // f() POR } int main() { A* p = nullptr; g(p); // POR of g() and f() } // Both #1 and #2 are added to the candidate list; // #2 is selected because it is a better match. ``` Output: ``` #2 ``` * A better matching template overload is declared after POR. ``` #include <iostream> struct A {}; template<class T> void f(T) { std::cout << "#1\n"; } // #1 template<class T> void g(T* t) { (f)(t); // f() POR } template<class T> void f(T*) { std::cout << "#2\n"; } // #2 int main() { A* p = nullptr; g(p); // POR of g() and f() } // Only #1 is added to the candidate list; #2 is defined after POR; // therefore, it is not considered for overloading even if it is a better match. ``` Output: ``` #1 ``` * A better matching explicit template specialization is declared after POR. ``` #include <iostream> struct A {}; template<class T> void f(T) { std::cout << "#1\n"; } // #1 template<class T> void g(T* t) { (f)(t); // f() POR } template<> void f<>(A*) { std::cout << "#3\n"; } // #3 int main() { A* p = nullptr; g(p); // POR of g() and f() } // #1 is added to the candidate list; #3 is a better match defined after POR. The // candidate list consists of #1 which is eventually selected. After that, the explicit // specialization #3 of #1 declared after POI is selected because it is a better match. // This behavior is governed by 14.7.3/6 [temp.expl.spec] and has nothing to do with ADL. ``` Output: ``` #3 ``` * A better matching template overload is declared after POR. The best matching explicit template specialization is declared after the better matching overload. ``` #include <iostream> struct A {}; template<class T> void f(T) { std::cout << "#1\n"; } // #1 template<class T> void g(T* t) { (f)(t); // f() POR } template<class T> void f(T*) { std::cout << "#2\n"; } // #2 template<> void f<>(A*) { std::cout << "#3\n"; } // #3 int main() { A* p = nullptr; g(p); // POR of g() and f() } // #1 is the only member of the candidate list and it is eventually selected. // After that, the explicit specialization #3 is skipped because it actually // specializes #2 declared after POR. ``` Output: ``` #1 ``` Let's consider now those cases employing argument-dependent lookup (i.e., we use the more common call format `f(t)`).* A better matching template overload is declared after POR. ``` #include <iostream> struct A {}; template<class T> void f(T) { std::cout << "#1\n"; } // #1 template<class T> void g(T* t) { f(t); // f() POR } template<class T> void f(T*) { std::cout << "#2\n"; } // #2 int main() { A* p = nullptr; g(p); // POR of g() and f() } // #1 is added to the candidate list as a result of the ordinary lookup; // #2 is defined after POR but it is added to the candidate list via ADL lookup. // #2 is selected being the better match. ``` Output: ``` #2 ``` * A better matching template overload is declared after POR. The best matching explicit template specialization is declared before the better matching overload. ``` #include <iostream> struct A {}; template<class T> void f(T) { std::cout << "#1\n"; } // #1 template<class T> void g(T* t) { f(t); // f() POR } template<> void f<>(A*) { std::cout << "#3\n"; } // #3 template<class T> void f(T*) { std::cout << "#2\n"; } // #2 int main() { A* p = nullptr; g(p); // POR of g() and f() } // #1 is added to the candidate list as a result of the ordinary lookup; // #2 is defined after POR but it is added to the candidate list via ADL lookup. // #2 is selected among the primary templates, being the better match. // Since #3 is declared before #2, it is an explicit specialization of #1. // Hence the final selection is #2. ``` Output: ``` #2 ``` * A better matching template overload is declared after POR. The best matching explicit template specialization is declared last. ``` #include <iostream> struct A {}; template<class T> void f(T) { std::cout << "#1\n"; } // #1 template<class T> void g(T* t) { f(t); // f() POR } template<class T> void f(T*) { std::cout << "#2\n"; } // #2 template<> void f<>(A*) { std::cout << "#3\n"; } // #3 int main() { A* p = nullptr; g(p); // POR of g() and f() } // #1 is added to the candidate list as a result of the ordinary lookup; // #2 is defined after POR but it is added to the candidate list via ADL lookup. // #2 is selected among the primary templates, being the better match. // Since #3 is declared after #2, it is an explicit specialization of #2; // therefore, selected as the function to call. ``` Output: ``` #3 ``` Whenever the arguments are some C++ basic types, there are no ADL-associated namespaces. Hence, those scenarios are identical with the non-ADL examples above. | --- For detailed rules on overload resolution, see [overload resolution](overload_resolution "cpp/language/overload resolution"). ### Function template specialization ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 214](https://cplusplus.github.io/CWG/issues/214.html) | C++98 | the exact procedure of partial ordering was not specified | specification added | | [CWG 532](https://cplusplus.github.io/CWG/issues/532.html) | C++98 | the order between a non-static member function templateand a non-member function template was not specified | specification added | | [CWG 581](https://cplusplus.github.io/CWG/issues/581.html) | C++98 | template argument list in an explicit specialization orinstantiation of a constructor template was allowed | forbidden | | [CWG 1321](https://cplusplus.github.io/CWG/issues/1321.html) | C++98 | it was unclear whether same dependent names in thefirst declaration and a redeclaration are equivalent | they are equivalent andthe meaning is same asin the first declaration | | [CWG 1395](https://cplusplus.github.io/CWG/issues/1395.html) | C++11 | deduction failed when A was from a pack,and there was no empty pack tie-breaker | deduction allowed,tie-breaker added | | [CWG 1406](https://cplusplus.github.io/CWG/issues/1406.html) | C++11 | the type of the new first parameter added fora non-static member function template wasnot relevant to the ref-qualifier of that template | the type is an rvaluereference type if theref-qualifier is `&&` | | [CWG 1446](https://cplusplus.github.io/CWG/issues/1446.html) | C++11 | the type of the new first parameter added for a non-static memberfunction template without ref-qualifier was an lvalue referencetype, even if that member function template is compared with afunction template whose first parameter has rvalue reference type | the type is anrvalue referencetype in this case | | [CWG 2373](https://cplusplus.github.io/CWG/issues/2373.html) | C++98 | new first parameters were added to the parameter listsof static member function templates in partial ordering | not added | ### See also * [class template](class_template "cpp/language/class template") * [function declaration](function "cpp/language/function")
programming_docs
cpp consteval specifier (since C++20) `consteval` specifier (since C++20) ==================================== * `consteval` - specifies that a function is an *immediate function*, that is, every call to the function must produce a compile-time constant ### Explanation The `consteval` specifier declares a function or function template to be an *immediate function*, that is, every potentially evaluated call (i.e. call out of an [unevaluated context](expressions#Unevaluated_expressions "cpp/language/expressions")) to the function must (directly or indirectly) produce a compile time [constant expression](constant_expression "cpp/language/constant expression"). An immediate function is a constexpr function, and must satisfy the requirements applicable to [constexpr functions or constexpr constructors](constexpr "cpp/language/constexpr"), as the case may be. Same as `constexpr`, a `consteval` specifier implies `inline`. However, it may not be applied to destructors, allocation functions, or deallocation functions. At most one of the `constexpr`, `consteval`, and `constinit` specifiers is allowed to appear within the same sequence of declaration specifiers. If any declaration of a function or function template contains a `consteval` specifier, then all declarations of that function or function template must contain that specifier. A potentially evaluated invocation of an immediate function whose innermost non-block scope is not a [function parameter scope](scope#Function_parameter_scope "cpp/language/scope") of an immediate function or the true-branch of a [consteval if statement](if#Consteval_if "cpp/language/if") (since C++23) must produce a constant expression; such an invocation is known as an *immediate invocation*. ``` consteval int sqr(int n) { return n*n; } constexpr int r = sqr(100); // OK int x = 100; int r2 = sqr(x); // Error: Call does not produce a constant consteval int sqrsqr(int n) { return sqr(sqr(n)); // Not a constant expression at this point, but OK } constexpr int dblsqr(int n) { return 2*sqr(n); // Error: Enclosing function is not consteval // and sqr(n) is not a constant } ``` An [identifier expression](identifiers#In_expressions "cpp/language/identifiers") that denotes an immediate function may only appear within a subexpression of an immediate invocation or within an *immediate function context* (i.e. a context mentioned above, in which a call to an immediate function needs not to be a constant expression). A pointer or reference to an immediate function can be taken but cannot escape constant expression evaluation: ``` consteval int f() { return 42; } consteval auto g() { return &f; } consteval int h(int (*p)() = g()) { return p(); } constexpr int r = h(); // OK constexpr auto e = g(); // ill-formed: a pointer to an immediate function is // not a permitted result of a constant expression ``` ### Keywords [`consteval`](../keyword/consteval "cpp/keyword/consteval"). ### Example ``` #include <iostream> // This function might be evaluated at compile-time, if the input // is known at compile-time. Otherwise, it is executed at run-time. constexpr unsigned factorial(unsigned n) { return n < 2 ? 1 : n * factorial(n - 1); } // With consteval we have a guarantee that the function will be evaluated at compile-time. consteval unsigned combination(unsigned m, unsigned n) { return factorial(n) / factorial(m) / factorial(n - m); } static_assert(factorial(6) == 720); static_assert(combination(4,8) == 70); int main(int argc, const char*[]) { constexpr unsigned x{factorial(4)}; std::cout << x << '\n'; [[maybe_unused]] unsigned y = factorial(argc); // OK // unsigned z = combination(argc, 7); // error: 'argc' is not a constant expression } ``` Output: ``` 24 ``` ### See also | | | | --- | --- | | [`constexpr` specifier](constexpr "cpp/language/constexpr")(C++11) | specifies that the value of a variable or function can be computed at compile time | | [`constinit` specifier](constinit "cpp/language/constinit")(C++20) | asserts that a variable has static initialization, i.e. [zero initialization](zero_initialization "cpp/language/zero initialization") and [constant initialization](constant_initialization "cpp/language/constant initialization") | | [constant expression](constant_expression "cpp/language/constant expression") | defines an [expression](expressions "cpp/language/expressions") that can be evaluated at compile time | cpp History of C++ History of C++ ============== Early C++ ---------- * 1979: C with Classes first implemented 1. New features: [classes](classes "cpp/language/classes"), [member functions](member_functions "cpp/language/member functions"), [derived classes](derived_class "cpp/language/derived class"), separate compilation, [public and private access control](access "cpp/language/access"), [friends](friend "cpp/language/friend"), type checking of function arguments, [default arguments](default_arguments "cpp/language/default arguments"), [inline functions](inline "cpp/language/inline"), [overloaded assignment operator](copy_assignment "cpp/language/copy assignment"), [constructors](constructor "cpp/language/constructor"), [destructors](destructor "cpp/language/destructor"), `f()` same as `f(void)`, call-function and return-function (synchronization features, not in C++) 2. Libraries: the concurrent task library (not in C++) * 1982: C with Classes reference manual published * 1984: C84 implemented, reference manual published * 1985: Cfront 1.0 1. New features: [virtual functions](virtual "cpp/language/virtual"), function and [operator overloading](operators "cpp/language/operators"), [references](reference "cpp/language/reference"), [`new`](../memory/new/operator_new "cpp/memory/new/operator new") and [`delete`](../memory/new/operator_delete "cpp/memory/new/operator delete") operators, [the keyword `const`](cv "cpp/language/cv"), scope resolution operator 2. Library additions: [complex number](../numeric/complex "cpp/numeric/complex"), `string` (AT&T version), [I/O stream](../header/iostream "cpp/header/iostream") * 1985: The C++ Programming Language, 1st edition * 1986: The "whatis?" paper documenting the remaining design goals, including multiple inheritance, exception handling, and templates. * 1987: C++ support in GCC 1.15.3 * 1989: Cfront 2.0 1. New features: [multiple inheritance](derived_class "cpp/language/derived class"), [pointers to members](pointer "cpp/language/pointer"), [protected access](access "cpp/language/access"), type-safe linkage, [abstract classes](abstract_class "cpp/language/abstract class"), [static](static#Static_member_functions "cpp/language/static") and [const-qualified](member_functions#const-_and_volatile-qualified_member_functions "cpp/language/member functions") member functions, class-specific [`new`](../memory/new/operator_new#Class-specific_overloads "cpp/memory/new/operator new") and [`delete`](../memory/new/operator_delete#Class-specific_overloads "cpp/memory/new/operator delete") 2. Library additions: [I/O manipulators](../io/manip "cpp/io/manip") * 1990: The Annotated C++ Reference Manual This book described the language as designed, including some features that were not yet implemented. It served as the de-facto standard until the ISO. 1. New features: [namespaces](namespace "cpp/language/namespace"), [exception handling](exceptions "cpp/language/exceptions"), [nested classes](nested_types "cpp/language/nested types"), [templates](templates "cpp/language/templates") * 1991: Cfront 3.0 * 1991: The C++ Programming Language, 2nd edition Standard C++ ------------- * 1990: ANSI C++ Committee founded * 1991: ISO C++ Committee founded * 1992: [STL](https://www.rrsd.com/software_development/stl/stl/) implemented in C++ ### C++98/03 period * 1998: **C++98** (ISO/IEC 14882:1998) 1. New features: RTTI ([`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast"), [`typeid`](typeid "cpp/language/typeid")), [covariant return types](virtual#Covariant_return_types "cpp/language/virtual"), [cast operators](cast_operator "cpp/language/cast operator"), [`mutable`](cv "cpp/language/cv"), [`bool`](types#Boolean_type "cpp/language/types"), declarations in conditions, [template instantiations](templates "cpp/language/templates"), [member templates](member_template "cpp/language/member template"), export 2. Library additions: [locales](../locale "cpp/locale"), [`bitset`](../utility/bitset "cpp/utility/bitset"), [`valarray`](../numeric/valarray "cpp/numeric/valarray"), [`auto_ptr`](../memory/auto_ptr "cpp/memory/auto ptr"), [templatized string](../string/basic_string "cpp/string/basic string"), [I/O streams](../io "cpp/io"), and [complex numbers](../numeric/complex "cpp/numeric/complex"). 3. Based on STL: [containers](../container "cpp/container"), [algorithms](../algorithm "cpp/algorithm"), [iterators](../iterator "cpp/iterator"), [function objects](../utility/functional "cpp/utility/functional") * 1998: The C++ Programming Language, 3rd edition * 1999: [Boost](https://www.boost.org) founded by the committee members to produce new high-quality candidate libraries for the standard. * 2003: **C++03** (ISO/IEC 14882:2003) This was a minor revision, intended to be little more than a technical corrigendum. This revision introduces the definition of [value initialization](value_initialization "cpp/language/value initialization"). | Defect Reports fixed in C++03 (92 core, 125 library) | | --- | | * [CWG#1](https://wg21.cmeerw.net/cwg/issue1) * [CWG#20](https://wg21.cmeerw.net/cwg/issue20) * [CWG#21](https://wg21.cmeerw.net/cwg/issue21) * [CWG#22](https://wg21.cmeerw.net/cwg/issue22) * [CWG#24](https://wg21.cmeerw.net/cwg/issue24) * [CWG#25](https://wg21.cmeerw.net/cwg/issue25) * [CWG#30](https://wg21.cmeerw.net/cwg/issue30) * [CWG#32](https://wg21.cmeerw.net/cwg/issue32) * [CWG#33](https://wg21.cmeerw.net/cwg/issue33) * [CWG#35](https://wg21.cmeerw.net/cwg/issue35) * [CWG#38](https://wg21.cmeerw.net/cwg/issue38) * [CWG#40](https://wg21.cmeerw.net/cwg/issue40) * [CWG#41](https://wg21.cmeerw.net/cwg/issue41) * [CWG#43](https://wg21.cmeerw.net/cwg/issue43) * [CWG#48](https://wg21.cmeerw.net/cwg/issue48) * [CWG#49](https://wg21.cmeerw.net/cwg/issue49) * [CWG#51](https://wg21.cmeerw.net/cwg/issue51) * [CWG#52](https://wg21.cmeerw.net/cwg/issue52) * [CWG#53](https://wg21.cmeerw.net/cwg/issue53) * [CWG#56](https://wg21.cmeerw.net/cwg/issue56) * [CWG#59](https://wg21.cmeerw.net/cwg/issue59) * [CWG#64](https://wg21.cmeerw.net/cwg/issue64) * [CWG#65](https://wg21.cmeerw.net/cwg/issue65) * [CWG#67](https://wg21.cmeerw.net/cwg/issue67) * [CWG#68](https://wg21.cmeerw.net/cwg/issue68) * [CWG#69](https://wg21.cmeerw.net/cwg/issue69) * [CWG#73](https://wg21.cmeerw.net/cwg/issue73) * [CWG#74](https://wg21.cmeerw.net/cwg/issue74) * [CWG#75](https://wg21.cmeerw.net/cwg/issue75) * [CWG#76](https://wg21.cmeerw.net/cwg/issue76) * [CWG#80](https://wg21.cmeerw.net/cwg/issue80) * [CWG#83](https://wg21.cmeerw.net/cwg/issue83) * [CWG#84](https://wg21.cmeerw.net/cwg/issue84) * [CWG#85](https://wg21.cmeerw.net/cwg/issue85) * [CWG#89](https://wg21.cmeerw.net/cwg/issue89) * [CWG#90](https://wg21.cmeerw.net/cwg/issue90) * [CWG#93](https://wg21.cmeerw.net/cwg/issue93) * [CWG#94](https://wg21.cmeerw.net/cwg/issue94) * [CWG#98](https://wg21.cmeerw.net/cwg/issue98) * [CWG#100](https://wg21.cmeerw.net/cwg/issue100) * [CWG#101](https://wg21.cmeerw.net/cwg/issue101) * [CWG#103](https://wg21.cmeerw.net/cwg/issue103) * [CWG#105](https://wg21.cmeerw.net/cwg/issue105) * [CWG#108](https://wg21.cmeerw.net/cwg/issue108) * [CWG#116](https://wg21.cmeerw.net/cwg/issue116) * [CWG#120](https://wg21.cmeerw.net/cwg/issue120) * [CWG#121](https://wg21.cmeerw.net/cwg/issue121) * [CWG#123](https://wg21.cmeerw.net/cwg/issue123) * [CWG#126](https://wg21.cmeerw.net/cwg/issue126) * [CWG#127](https://wg21.cmeerw.net/cwg/issue127) * [CWG#128](https://wg21.cmeerw.net/cwg/issue128) * [CWG#131](https://wg21.cmeerw.net/cwg/issue131) * [CWG#134](https://wg21.cmeerw.net/cwg/issue134) * [CWG#135](https://wg21.cmeerw.net/cwg/issue135) * [CWG#137](https://wg21.cmeerw.net/cwg/issue137) * [CWG#142](https://wg21.cmeerw.net/cwg/issue142) * [CWG#145](https://wg21.cmeerw.net/cwg/issue145) * [CWG#147](https://wg21.cmeerw.net/cwg/issue147) * [CWG#148](https://wg21.cmeerw.net/cwg/issue148) * [CWG#149](https://wg21.cmeerw.net/cwg/issue149) * [CWG#151](https://wg21.cmeerw.net/cwg/issue151) * [CWG#152](https://wg21.cmeerw.net/cwg/issue152) * [CWG#153](https://wg21.cmeerw.net/cwg/issue153) * [CWG#159](https://wg21.cmeerw.net/cwg/issue159) * [CWG#161](https://wg21.cmeerw.net/cwg/issue161) * [CWG#163](https://wg21.cmeerw.net/cwg/issue163) * [CWG#164](https://wg21.cmeerw.net/cwg/issue164) * [CWG#166](https://wg21.cmeerw.net/cwg/issue166) * [CWG#171](https://wg21.cmeerw.net/cwg/issue171) * [CWG#173](https://wg21.cmeerw.net/cwg/issue173) * [CWG#176](https://wg21.cmeerw.net/cwg/issue176) * [CWG#178](https://wg21.cmeerw.net/cwg/issue178) * [CWG#179](https://wg21.cmeerw.net/cwg/issue179) * [CWG#181](https://wg21.cmeerw.net/cwg/issue181) * [CWG#183](https://wg21.cmeerw.net/cwg/issue183) * [CWG#185](https://wg21.cmeerw.net/cwg/issue185) * [CWG#187](https://wg21.cmeerw.net/cwg/issue187) * [CWG#188](https://wg21.cmeerw.net/cwg/issue188) * [CWG#190](https://wg21.cmeerw.net/cwg/issue190) * [CWG#193](https://wg21.cmeerw.net/cwg/issue193) * [CWG#194](https://wg21.cmeerw.net/cwg/issue194) * [CWG#202](https://wg21.cmeerw.net/cwg/issue202) * [CWG#206](https://wg21.cmeerw.net/cwg/issue206) * [CWG#210](https://wg21.cmeerw.net/cwg/issue210) * [CWG#213](https://wg21.cmeerw.net/cwg/issue213) * [CWG#217](https://wg21.cmeerw.net/cwg/issue217) * [CWG#227](https://wg21.cmeerw.net/cwg/issue227) * [CWG#235](https://wg21.cmeerw.net/cwg/issue235) * [CWG#241](https://wg21.cmeerw.net/cwg/issue241) * [CWG#249](https://wg21.cmeerw.net/cwg/issue249) * [CWG#250](https://wg21.cmeerw.net/cwg/issue250) * [CWG#304](https://wg21.cmeerw.net/cwg/issue304) * [LWG#1](http://wg21.link/lwg1) * [LWG#3](http://wg21.link/lwg3) * [LWG#5](http://wg21.link/lwg5) * [LWG#7](http://wg21.link/lwg7) * [LWG#8](http://wg21.link/lwg8) * [LWG#9](http://wg21.link/lwg9) * [LWG#11](http://wg21.link/lwg11) * [LWG#13](http://wg21.link/lwg13) * [LWG#14](http://wg21.link/lwg14) * [LWG#15](http://wg21.link/lwg15) * [LWG#16](http://wg21.link/lwg16) * [LWG#17](http://wg21.link/lwg17) * [LWG#18](http://wg21.link/lwg18) * [LWG#19](http://wg21.link/lwg19) * [LWG#20](http://wg21.link/lwg20) * [LWG#21](http://wg21.link/lwg21) * [LWG#22](http://wg21.link/lwg22) * [LWG#24](http://wg21.link/lwg24) * [LWG#25](http://wg21.link/lwg25) * [LWG#26](http://wg21.link/lwg26) * [LWG#27](http://wg21.link/lwg27) * [LWG#28](http://wg21.link/lwg28) * [LWG#29](http://wg21.link/lwg29) * [LWG#30](http://wg21.link/lwg30) * [LWG#31](http://wg21.link/lwg31) * [LWG#32](http://wg21.link/lwg32) * [LWG#33](http://wg21.link/lwg33) * [LWG#34](http://wg21.link/lwg34) * [LWG#35](http://wg21.link/lwg35) * [LWG#36](http://wg21.link/lwg36) * [LWG#37](http://wg21.link/lwg37) * [LWG#38](http://wg21.link/lwg38) * [LWG#39](http://wg21.link/lwg39) * [LWG#40](http://wg21.link/lwg40) * [LWG#41](http://wg21.link/lwg41) * [LWG#42](http://wg21.link/lwg42) * [LWG#46](http://wg21.link/lwg46) * [LWG#47](http://wg21.link/lwg47) * [LWG#48](http://wg21.link/lwg48) * [LWG#50](http://wg21.link/lwg50) * [LWG#51](http://wg21.link/lwg51) * [LWG#52](http://wg21.link/lwg52) * [LWG#53](http://wg21.link/lwg53) * [LWG#54](http://wg21.link/lwg54) * [LWG#55](http://wg21.link/lwg55) * [LWG#56](http://wg21.link/lwg56) * [LWG#57](http://wg21.link/lwg57) * [LWG#59](http://wg21.link/lwg59) * [LWG#60](http://wg21.link/lwg60) * [LWG#61](http://wg21.link/lwg61) * [LWG#62](http://wg21.link/lwg62) * [LWG#63](http://wg21.link/lwg63) * [LWG#64](http://wg21.link/lwg64) * [LWG#66](http://wg21.link/lwg66) * [LWG#68](http://wg21.link/lwg68) * [LWG#69](http://wg21.link/lwg69) * [LWG#70](http://wg21.link/lwg70) * [LWG#71](http://wg21.link/lwg71) * [LWG#74](http://wg21.link/lwg74) * [LWG#75](http://wg21.link/lwg75) * [LWG#78](http://wg21.link/lwg78) * [LWG#79](http://wg21.link/lwg79) * [LWG#80](http://wg21.link/lwg80) * [LWG#83](http://wg21.link/lwg83) * [LWG#86](http://wg21.link/lwg86) * [LWG#90](http://wg21.link/lwg90) * [LWG#106](http://wg21.link/lwg106) * [LWG#108](http://wg21.link/lwg108) * [LWG#110](http://wg21.link/lwg110) * [LWG#112](http://wg21.link/lwg112) * [LWG#114](http://wg21.link/lwg114) * [LWG#115](http://wg21.link/lwg115) * [LWG#119](http://wg21.link/lwg119) * [LWG#122](http://wg21.link/lwg122) * [LWG#124](http://wg21.link/lwg124) * [LWG#125](http://wg21.link/lwg125) * [LWG#126](http://wg21.link/lwg126) * [LWG#127](http://wg21.link/lwg127) * [LWG#129](http://wg21.link/lwg129) * [LWG#132](http://wg21.link/lwg132) * [LWG#133](http://wg21.link/lwg133) * [LWG#134](http://wg21.link/lwg134) * [LWG#137](http://wg21.link/lwg137) * [LWG#139](http://wg21.link/lwg139) * [LWG#141](http://wg21.link/lwg141) * [LWG#142](http://wg21.link/lwg142) * [LWG#144](http://wg21.link/lwg144) * [LWG#146](http://wg21.link/lwg146) * [LWG#147](http://wg21.link/lwg147) * [LWG#148](http://wg21.link/lwg148) * [LWG#150](http://wg21.link/lwg150) * [LWG#151](http://wg21.link/lwg151) * [LWG#152](http://wg21.link/lwg152) * [LWG#154](http://wg21.link/lwg154) * [LWG#155](http://wg21.link/lwg155) * [LWG#156](http://wg21.link/lwg156) * [LWG#158](http://wg21.link/lwg158) * [LWG#159](http://wg21.link/lwg159) * [LWG#160](http://wg21.link/lwg160) * [LWG#161](http://wg21.link/lwg161) * [LWG#164](http://wg21.link/lwg164) * [LWG#168](http://wg21.link/lwg168) * [LWG#169](http://wg21.link/lwg169) * [LWG#170](http://wg21.link/lwg170) * [LWG#172](http://wg21.link/lwg172) * [LWG#173](http://wg21.link/lwg173) * [LWG#174](http://wg21.link/lwg174) * [LWG#175](http://wg21.link/lwg175) * [LWG#176](http://wg21.link/lwg176) * [LWG#181](http://wg21.link/lwg181) * [LWG#189](http://wg21.link/lwg189) * [LWG#193](http://wg21.link/lwg193) * [LWG#195](http://wg21.link/lwg195) * [LWG#199](http://wg21.link/lwg199) * [LWG#208](http://wg21.link/lwg208) * [LWG#209](http://wg21.link/lwg209) * [LWG#210](http://wg21.link/lwg210) * [LWG#211](http://wg21.link/lwg211) * [LWG#212](http://wg21.link/lwg212) * [LWG#217](http://wg21.link/lwg217) * [LWG#220](http://wg21.link/lwg220) * [LWG#222](http://wg21.link/lwg222) * [LWG#223](http://wg21.link/lwg223) * [LWG#224](http://wg21.link/lwg224) * [LWG#227](http://wg21.link/lwg227) | * 2006: Performance TR (ISO/IEC TR 18015:2006) ([ISO Store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=43351)) ([2006 draft](https://www.open-std.org/jtc1/sc22/wg21/docs/TR18015.pdf)) This TR discussed the costs of various C++ abstractions, provided implementation guidance, discussed use of C++ in embedded systems and introduced `<hardware>` interface to C's ISO/IEC TR 18037:2008 `<iohw.h>`. * 2007: Library extension TR1 (ISO/IEC TR 19768:2007) ([ISO store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=43289)) ([2005 draft](https://wg21.link/n1745)). This TR is a C++ library extension, which adds the following to the C++ standard library: 1. From Boost: [`reference_wrapper`](../utility/functional/reference_wrapper "cpp/utility/functional/reference wrapper"), [Smart pointers](../memory#Smart_pointers "cpp/memory"), [Member function](../utility/functional/mem_fn "cpp/utility/functional/mem fn"), [`result_of`](../types/result_of "cpp/types/result of"), [`bind`](../utility/functional/bind "cpp/utility/functional/bind"), [`function`](../utility/functional/function "cpp/utility/functional/function"), [Type Traits](../types "cpp/types"), [Random](../numeric/random "cpp/numeric/random"), Mathematical Special Functions, [`tuple`](../utility/tuple "cpp/utility/tuple"), [`array`](../container/array "cpp/container/array"), [Unordered Containers](../container#Unordered_associative_containers "cpp/container") (including [`hash`](../utility/hash "cpp/utility/hash")), and [Regular Expressions](../regex "cpp/regex"). 2. From C99: mathematical functions from [`<math.h>`](https://en.cppreference.com/w/c/numeric/math "c/numeric/math") that were new in C99, [blank character class](../string/byte/isblank "cpp/string/byte/isblank"), [Floating-point environment](../numeric/fenv "cpp/numeric/fenv"), [`hexfloat`](../io/manip/fixed "cpp/io/manip/fixed") I/O Manipulator, [fixed-size integral types](../types/integer "cpp/types/integer"), the [`long long`](types#Modifiers "cpp/language/types") type, `[va\_copy](../utility/variadic/va_copy "cpp/utility/variadic/va copy")`, the [`snprintf()`](../io/c/snprintf "cpp/io/c/snprintf") and [`vfscanf()`](../io/c/vfscanf "cpp/io/c/vfscanf") families of functions, and the C99 conversion specifies for [`printf()`](../io/c/printf "cpp/io/c/printf") and [`scanf()`](../io/c/scanf "cpp/io/c/scanf") families of functions. All of TR1 except for the special functions was included in C++11, with minor changes. * 2010: Mathematical special functions (ISO/IEC 29124:2010) ([ISO Store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=50511)) ([2010 draft](https://wg21.link/n3060)) This international standard is a C++ standard library extension, which adds the special functions that were part of TR1, but were not included in C++11: elliptic integrals, exponential integral, Laguerre polynomials, Legendre polynomials, Hermite polynomials, Bessel functions, Neumann functions, beta function, and Riemann zeta function. This standard was [merged into C++17](../numeric/special_functions "cpp/numeric/special functions"). ### C++11 period * 2011: **C++11** (ISO/IEC 14882:2011) ([ISO Store](https://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=50372)) ([2012 post-publication draft](https://wg21.link/n3337)). [Main Article: C++11](../11 "cpp/11"). A large number of changes were introduced to both standardize existing practices and improve the abstractions available to the C++ programmers. * 2011: Decimal floating-point TR (ISO/IEC TR 24733:2011) ([ISO Store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=38843)) ([2009 draft](https://wg21.link/n2849)) This TR implements the decimal floating-point types from IEEE 754-2008 Standard for Floating-Point Arithmetic: `std::decimal::decimal32`, `std::decimal::decimal64`, and `std::decimal::decimal128`. * 2012: [The Standard C++ Foundation](https://isocpp.org) founded * 2013: The C++ Programming Language, 4th edition ### C++14 period * 2014: **C++14** ([ISO Store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=64029)) ([ANSI Store](https://webstore.ansi.org/RecordDetail.aspx?sku=INCITS%2fISO%2fIEC+14882%3a2014+(2016))) ([2014 final draft](https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf?raw=true)) [Main Article: C++14](../14 "cpp/14"). Minor revision of the C++ standard. * 2015: Filesystem library TS (ISO/IEC TS 18822:2015) ([ISO Store](https://www.iso.org/iso/catalogue_detail.htm?csnumber=63483)) ([2014 draft](https://wg21.link/n4100)) This TS is an experimental C++ library extension that specifies a filesystem library based on boost.filesystem V3 (with some modifications and extensions). This TS was merged into C++17. * 2015: Extensions for Parallelism TS (ISO/IEC TS 19570:2015) ([ISO Store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=65241)) ([2015 draft](https://wg21.link/n4507)) This TS standardizes parallel and vector-parallel API for all standard library algorithms, as well as adds new algorithms such as `reduce`, `transform_reduce`, or `exclusive_scan`. This TS was merged into C++17. * 2015: Extensions for Transactional Memory TS (ISO/IEC TS 19841:2015) ([ISO Store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=66343)) ([[2015 draft](https://wg21.link/n4514)) This TS extends the C++ core language with synchronized and atomic blocks, as well as transaction-safe functions, which implement transactional memory semantics. * 2015: Extensions for Library Fundamentals TS (ISO/IEC TS 19568:2015) ([ISO Store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=65238)) ([2015 draft](https://wg21.link/n4480)) This TS adds several new components to the C++ standard library: [`optional`](https://en.cppreference.com/w/cpp/experimental/optional "cpp/experimental/optional"), [`any`](https://en.cppreference.com/w/cpp/experimental/any "cpp/experimental/any"), [`string_view`](https://en.cppreference.com/w/cpp/experimental/basic_string_view "cpp/experimental/basic string view"), [`sample`](https://en.cppreference.com/w/cpp/experimental/sample "cpp/experimental/sample"), [`search`](https://en.cppreference.com/w/cpp/experimental/search "cpp/experimental/search"), [`apply`](https://en.cppreference.com/w/cpp/experimental/apply "cpp/experimental/apply"), [polymorphic allocators](https://en.cppreference.com/w/cpp/experimental/lib_extensions#Type-erased_and_polymorphic_allocators "cpp/experimental/lib extensions"), and [variable templates](https://en.cppreference.com/w/cpp/experimental/lib_extensions "cpp/experimental/lib extensions") for type traits. This TS was merged into C++17. * 2015: Extensions for Concepts TS (ISO/IEC TS 19217:2015) ([ISO Store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=64031)) ([2015 draft](https://wg21.link/n4553)) This TS extends the C++ core language with concepts (named type requirements) and constraints (limits on the types allowed in template, function, and variable declarations), which aids metaprogramming and simplifies template instantiation diagnostics, see [concepts](https://en.cppreference.com/w/cpp/experimental/constraints "cpp/experimental/constraints"). This TS was merged into C++20, with some omissions. * 2016: Extensions for Concurrency TS (ISO/IEC TS 19571:2016) ([ISO Store](https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=65242)) ([2015 draft](https://wg21.link/p0159r0)) This TS extends the C++ library to include [several extensions](https://en.cppreference.com/w/cpp/experimental/concurrency "cpp/experimental/concurrency") to `[std::future](../thread/future "cpp/thread/future")`, `[latches](../thread/latch "cpp/thread/latch")` and `[barriers](../thread/barrier "cpp/thread/barrier")`, and atomic smart pointers. ### C++17 period * 2017: **C++17** ([ISO Store](https://www.iso.org/standard/68564.html)) ([ANSI Store](https://webstore.ansi.org/RecordDetail.aspx?sku=INCITS%2fISO%2fIEC+14882%3a2017+(2018))) ([n4659 2017-03-21 final draft](https://wg21.link/n4659)) [Main Article: C++17](../17 "cpp/17"). The major revision of the C++ standard after C++11. * 2017: Extensions for Ranges TS (ISO/IEC TS 21425:2017) ([ISO Store](https://www.iso.org/standard/70910.html)) ([2017 draft](https://wg21.link/n4685)) This TS extends the C++ library to include [ranges](https://en.cppreference.com/w/cpp/experimental/ranges "cpp/experimental/ranges"), a new, more powerful, abstraction to replace iterator pairs, along with range views, sentinel ranges, projections for on-the-fly transformations, new iterator adaptors and algorithms. This extension finally makes it possible to sort a vector with `sort(v);` * 2017: Extensions for Coroutines TS (ISO/IEC TS 22277:2017) ([ISO Store](https://www.iso.org/standard/73008.html)) ([2017 draft](https://wg21.link/n4680)) This TS extends the C++ core language and the standard library to include stackless coroutines (resumable functions). This adds the keywords [`co_await`](../keyword/co_await "cpp/keyword/co await"), [`co_yield`](../keyword/co_yield "cpp/keyword/co yield"), and [`co_return`](../keyword/co_return "cpp/keyword/co return"). * 2018: Extensions for Networking TS (ISO/IEC TS 19216:2018) ([ISO Store](https://www.iso.org/standard/64030.html)) ([2017 draft](https://wg21.link/n4734)) This TS extends the C++ library to include TCP/IP networking based on [boost.asio](https://www.boost.org/doc/libs/1_67_0/doc/html/boost_asio.html). * 2018: Extensions for modules TS (ISO/IEC TS 21544:2018) ([ISO Store](https://www.iso.org/standard/71051.html)) ([2018 draft](https://wg21.link/n4720)) This TS extends the C++ core language to include modules. This adds the special identifiers [`module`](../keyword/module "cpp/keyword/module"), [`import`](../keyword/import "cpp/keyword/import"), and reintroduces the keyword [`export`](../keyword/export "cpp/keyword/export") with a new meaning. * 2018: Extensions for Parallelism version 2 TS (ISO/IEC TS 19570:2018) ([ISO Store](https://www.iso.org/standard/70588.html)) ([2018 draft](https://wg21.link/n4773)) This TS extends the C++ library to include two new execution policies (`unseq` and `vec`), additional parallel algorithms such as `reduction_plus` or `for_loop_strided`, task blocks for forking and joining parallel tasks, SIMD types and operations on those types. ### C++20 period * 2020: **C++20** ([ISO Store](https://www.iso.org/standard/79358.html)) (final draft [n4860 2020-03-31](https://wg21.link/n4860)) [Main Article: C++20](../20 "cpp/20"). The major revision of the C++ standard after C++17. * 2021: Reflection TS (ISO/IEC TS 23619:2021) ([ISO store](https://www.iso.org/standard/76425.html)) ([2020 draft](https://wg21.link/n4856)) This TS extends C++ with the facilities to inspect program entities such as variables, enumerations, classes and their members, lambdas and their captures, etc. ### Future development * [Experimental technical specifications](https://en.cppreference.com/w/cpp/experimental "cpp/experimental") * 2023: **C++23** latest draft [n4910 (2022-03-17)](https://wg21.link/n4910) [Main Article: C++23](../23 "cpp/23"). The next major revision of the C++ standard. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/history "c/language/history") for History of C | ### External links * [A History of C++: 1979-1991](https://www.stroustrup.com/hopl2.pdf) * [Evolving a language in and for the real world: C++ 1991-2006](https://www.stroustrup.com/hopl-almost-final.pdf) * [Thriving in a crowded and changing world: C++ 2006-2020](https://www.stroustrup.com/hopl20main-p5-p-bfc9cd4--final.pdf) * [Standard C++ foundation](https://isocpp.org) * [C++ on Wikipedia](https://en.wikipedia.org/wiki/C%2B%2B#History "enwiki:C++") * [C++ Standards Committee](https://www.open-std.org/jtc1/sc22/wg21/)
programming_docs
cpp constinit specifier (since C++20) constinit specifier (since C++20) ================================= * `constinit` - asserts that a variable has static initialization, i.e. [zero initialization](zero_initialization "cpp/language/zero initialization") and [constant initialization](constant_initialization "cpp/language/constant initialization"), otherwise the program is ill-formed. ### Explanation The `constinit` specifier declares a variable with static or thread [storage duration](storage_duration "cpp/language/storage duration"). If a variable is declared with `constinit`, its [initializing declaration](initialization "cpp/language/initialization") must be applied with `constinit`. If a variable declared with `constinit` has dynamic initialization, the program is ill-formed. If no `constinit` declaration is reachable at the point of the initializing declaration, the program is ill-formed, no diagnostic required. `constinit` cannot be used together with `constexpr` or `consteval`. When the declared variable is a reference, `constinit` is equivalent to `constexpr`. When the declared variable is an object, `constexpr` mandates that the object must have static initialization and constant destruction and makes the object const-qualified, however, `constinit` does not mandate constant destruction and const-qualification. As a result, an object of a type which has constexpr constructors and no constexpr destructor (e.g. `[std::shared\_ptr](http://en.cppreference.com/w/cpp/memory/shared_ptr)<T>`) might be declared with `constinit` but not `constexpr`. ``` const char *g() { return "dynamic initialization"; } constexpr const char *f(bool p) { return p ? "constant initializer" : g(); } constinit const char *c = f(true); // OK // constinit const char *d = f(false); // error ``` `constinit` can also be used in a non-initializing declaration to tell the compiler that a `thread_local` variable is already initialized, [reducing overhead](storage_duration#Static_local_variables "cpp/language/storage duration") that would otherwise be incurred by a hidden guard variable. ``` extern thread_local constinit int x; int f() { return x; } // no check of a guard variable needed ``` ### Keywords [`constinit`](../keyword/constinit "cpp/keyword/constinit"). ### Example ### See also | | | | --- | --- | | [`consteval` specifier](consteval "cpp/language/consteval")(C++20) | specifies that a function is an *immediate function*, that is, every call to the function must be in a constant evaluation | | [`constexpr` specifier](constexpr "cpp/language/constexpr")(C++11) | specifies that the value of a variable or function can be computed at compile time | | [constant expression](constant_expression "cpp/language/constant expression") | defines an [expression](expressions "cpp/language/expressions") that can be evaluated at compile time | | [constant initialization](constant_initialization "cpp/language/constant initialization") | sets the initial values of the [static](storage_duration "cpp/language/storage duration") variables to a compile-time constant | | [zero initialization](zero_initialization "cpp/language/zero initialization") | sets the initial value of an object to zero | cpp cv (const and volatile) type qualifiers cv (const and volatile) type qualifiers ======================================= Appear in any type specifier, including decl-specifier-seq of [declaration grammar](declarations "cpp/language/declarations"), to specify constness or volatility of the object being declared or of the type being named. * `const` - defines that the type is *constant*. * `volatile` - defines that the type is *volatile*. ### Explanation For any type `T` (including incomplete types), other than [function type](functions "cpp/language/functions") or [reference type](reference "cpp/language/reference"), there are three more distinct types in the C++ type system: const-qualified `T`, volatile-qualified `T`, and const-volatile-qualified `T`. Note: [array types](array "cpp/language/array") are considered to have the same cv-qualification as their element types. When an object is first created, the cv-qualifiers used (which could be part of decl-specifier-seq or part of a declarator in a [declaration](declarations "cpp/language/declarations"), or part of type-id in a [new-expression](new "cpp/language/new")) determine the constness or volatility of the object, as follows: * ***const object*** - an object whose type is const-qualified, or a non-mutable subobject of a const object. Such object cannot be modified: attempt to do so directly is a compile-time error, and attempt to do so indirectly (e.g., by modifying the const object through a reference or pointer to non-const type) results in undefined behavior. * ***volatile object*** - an object whose type is volatile-qualified, or a subobject of a volatile object, or a mutable subobject of a const-volatile object. Every access (read or write operation, member function call, etc.) made through a glvalue expression of volatile-qualified type is treated as a visible side-effect for the [purposes of optimization](as_if "cpp/language/as if") (that is, within a single thread of execution, volatile accesses cannot be optimized out or reordered with another visible side effect that is [sequenced-before](eval_order "cpp/language/eval order") or sequenced-after the volatile access. This makes volatile objects suitable for communication with a [signal handler](../utility/program/signal "cpp/utility/program/signal"), but not with another thread of execution, see `[std::memory\_order](../atomic/memory_order "cpp/atomic/memory order")`). Any attempt to refer to a volatile object through a [glvalue](value_category#glvalue "cpp/language/value category") of non-volatile type (e.g. through a reference or pointer to non-volatile type) results in undefined behavior. * ***const volatile object*** - an object whose type is const-volatile-qualified, a non-mutable subobject of a const volatile object, a const subobject of a volatile object, or a non-mutable volatile subobject of a const object. Behaves as both a const object and as a volatile object. Each cv-qualifier (`const` and `volatile`) can appear at most once in any cv-qualifier sequence. For example, `const const` and `volatile const volatile` are not valid cv-qualifier sequences. ### `mutable` specifier * `mutable` - permits modification of the class member declared mutable even if the containing object is declared const. May appear in the declaration of a non-static [class members](data_members "cpp/language/data members") of non-reference non-const type: ``` class X { mutable const int* p; // OK mutable int* const q; // ill-formed mutable int& r; // ill-formed }; ``` Mutable is used to specify that the member does not affect the externally visible state of the class (as often used for mutexes, memo caches, lazy evaluation, and access instrumentation). ``` class ThreadsafeCounter { mutable std::mutex m; // The "M&M rule": mutable and mutex go together int data = 0; public: int get() const { std::lock_guard<std::mutex> lk(m); return data; } void inc() { std::lock_guard<std::mutex> lk(m); ++data; } }; ``` ### Conversions There is partial ordering of cv-qualifiers by the order of increasing restrictions. The type can be said *more* or *less* cv-qualified than: * *unqualified* < `const` * *unqualified* < `volatile` * *unqualified* < `const volatile` * `const` < `const volatile` * `volatile` < `const volatile` References and pointers to cv-qualified types may be [implicitly converted](implicit_cast#Qualification_conversions "cpp/language/implicit cast") to references and pointers to *more cv-qualified* types. In particular, the following conversions are allowed: * reference/pointer to *unqualified* type can be converted to reference/pointer to `const` * reference/pointer to *unqualified* type can be converted to reference/pointer to `volatile` * reference/pointer to *unqualified* type can be converted to reference/pointer to `const volatile` * reference/pointer to `const` type can be converted to reference/pointer to `const volatile` * reference/pointer to `volatile` type can be converted to reference/pointer to `const volatile` Note: [additional restrictions](implicit_cast#Qualification_conversions "cpp/language/implicit cast") are imposed on multi-level pointers. To convert a reference or a pointer to a cv-qualified type to a reference or pointer to a *less cv-qualified* type, [const\_cast](const_cast "cpp/language/const cast") must be used. ### Keywords [`const`](../keyword/const "cpp/keyword/const"), [`volatile`](../keyword/volatile "cpp/keyword/volatile"), [`mutable`](../keyword/mutable "cpp/keyword/mutable"). ### Notes The `const` qualifier used on a declaration of a non-local non-volatile non-[template](variable_template "cpp/language/variable template") (since C++14)non-[inline](inline "cpp/language/inline") (since C++17) variable that is not declared `extern` gives it [internal linkage](storage_duration#Linkage "cpp/language/storage duration"). This is different from C where const file scope variables have external linkage. The C++ language grammar treats `mutable` as a [storage-class-specifier](storage_duration "cpp/language/storage duration"), rather than a type qualifier, but it does not affect storage class or linkage. | | | | --- | --- | | Some uses of volatile are deprecated:* lvalue of volatile type as operand of built-in [increment/decrement](operator_incdec "cpp/language/operator incdec") operators; * lvalue of volatile type as left operand of built-in [direct/compound assigment](operator_assignment "cpp/language/operator assignment") operators other than some bitwise compound assignment operators, unless the direct assigment expression appears in an [unevaluated context](expressions#Unevaluated_expressions "cpp/language/expressions") or is a [discarded-value expression](expressions#Discarded-value_expressions "cpp/language/expressions"); * volatile object type as function parameter type or return type; * volatile qualifier in [structured binding](structured_binding "cpp/language/structured binding") declaration. | (since C++20) | ### Example ``` int main() { int n1 = 0; // non-const object const int n2 = 0; // const object int const n3 = 0; // const object (same as n2) volatile int n4 = 0; // volatile object const struct { int n1; mutable int n2; } x = {0, 0}; // const object with mutable member n1 = 1; // ok, modifiable object // n2 = 2; // error: non-modifiable object n4 = 3; // ok, treated as a side-effect // x.n1 = 4; // error: member of a const object is const x.n2 = 4; // ok, mutable member of a const object isn't const const int& r1 = n1; // reference to const bound to non-const object // r1 = 2; // error: attempt to modify through reference to const const_cast<int&>(r1) = 2; // ok, modifies non-const object n1 const int& r2 = n2; // reference to const bound to const object // r2 = 2; // error: attempt to modify through reference to const // const_cast<int&>(r2) = 2; // undefined behavior: attempt to modify const object n2 } ``` Output: ``` # typical machine code produced on an x86_64 platform # (only the code that contributes to observable side-effects is emitted) main: movl $0, -4(%rsp) # volatile int n4 = 0; movl $3, -4(%rsp) # n4 = 3; xorl %eax, %eax # return 0 (implicit) ret ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1428](https://cplusplus.github.io/CWG/issues/1428.html) | C++98 | the definition of *const object* was based on declaration | based on object type | | [CWG 1528](https://cplusplus.github.io/CWG/issues/1528.html) | C++98 | there was no requirement on the number of occurencesof each cv-qualifier in the same cv-qualifier sequence | at most once foreach cv-qualifier | | [CWG 1799](https://cplusplus.github.io/CWG/issues/1799.html) | C++98 | `mutable` could be applied to data members not declared`const`, but the members' types may still be const-qualified | cannot apply `mutable` to datamembers of const-qualified types | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/const "c/language/const") for `const` qualifier | | [C documentation](https://en.cppreference.com/w/c/language/volatile "c/language/volatile") for `volatile` qualifier | cpp Default comparisons (since C++20) Default comparisons (since C++20) ================================= Provides a way to request the compiler to generate consistent comparison operators for a class. ### Syntax | | | | | --- | --- | --- | | return-type class-name`::operator`op`(` `const` class-name `&` `) const` `&`(optional) `= default;` | (1) | | | `friend` return-type `operator`op`(` `const` class-name `&``,` `const` class-name `&` `) = default;` | (2) | | | `friend` return-type `operator`op`(` class-name`,` class-name `) = default;` | (3) | | | | | | | --- | --- | --- | | op | - | a comparison operator (`<=>`, `==`, `!=`, `<`, `>`, `<=`, or `>=`) | | return-type | - | return type of the operator function. Must be * [`auto`](auto "cpp/language/auto") or one of [three comparison category types](#Custom_comparisons_and_comparison_categories) if op is `<=>`, * otherwise, `bool` | ### Explanation 1) Declare the defaulted comparison function as a member function. 2) Declare the defaulted comparison function as a non-member function. 3) Declare the defaulted comparison function as a non-member function. Arguments are passed by value. The three-way comparison function (whether defaulted or not) is called whenever values are compared using `<`, `>`, `<=`, `>=`, or `<=>` and overload resolution selects this overload. The equality comparison function (whether defaulted or not) is called whenever values are compared using `==` or `!=` and overload resolution selects this overload. Like defaulted special member functions, a defaulted comparison function is defined if [odr-used](definition#ODR-use "cpp/language/definition") or [needed for constant evaluation](constant_expression#Functions_and_variables_needed_for_constant_evaluation "cpp/language/constant expression"). ### Defaulted comparisons #### Defaulted three-way comparison The default `operator<=>` performs lexicographical comparison by successively comparing the base (left-to-right depth-first) and then non-static member (in declaration order) subobjects of `T` to compute `<=>`, recursively expanding array members (in order of increasing subscript), and stopping early when a not-equal result is found, that is: ``` for /*each base or member subobject o of T*/ if (auto cmp = static_cast<R>(compare(lhs.o, rhs.o)); cmp != 0) return cmp; return static_cast<R>(strong_ordering::equal); ``` It is unspecified whether virtual base subobjects are compared more than once. If the declared return type is `auto`, then the actual return type is the common comparison category of the base and member subobject and member array elements to be compared (see [`std::common_comparison_category`](../utility/compare/common_comparison_category "cpp/utility/compare/common comparison category")). This makes it easier to write cases where the return type non-trivially depends on the members, such as: ``` template<class T1, class T2> struct P { T1 x1; T2 x2; friend auto operator<=>(const P&, const P&) = default; }; ``` Let `R` be the return type, each pair of subobjects `a`, `b` is compared as follows: * If `a <=> b` is usable, the result of comparison is `static_cast<R>(a <=> b)`. * Otherwise, if overload resolution for `operator<=>` is performed for `a <=> b` and at least one candidate is found, the comparison is not defined (`operator<=>` is defined as deleted). * Otherwise, if `R` is not a comparison category type (see below), or either `a == b` or `a < b` is not usable, the comparison is not defined (`operator<=>` is defined as deleted). * Otherwise, if `R` is `[std::strong\_ordering](http://en.cppreference.com/w/cpp/utility/compare/strong_ordering)`, the result is ``` a == b ? R::equal : a < b ? R::less : R::greater ``` * Otherwise, if `R` is `[std::weak\_ordering](http://en.cppreference.com/w/cpp/utility/compare/weak_ordering)`, the result is ``` a == b ? R::equivalent : a < b ? R::less : R::greater ``` * Otherwise (`R` is `[std::partial\_ordering](http://en.cppreference.com/w/cpp/utility/compare/partial_ordering)`), the result is ``` a == b ? R::equivalent : a < b ? R::less : b < a ? R::greater : R::unordered ``` Per the rules for any `operator<=>` overload, a defaulted `<=>` overload will also allow the type to be compared with `<`, `<=`, `>`, and `>=`. If `operator<=>` is defaulted and `operator==` is not declared at all, then `operator==` is implicitly defaulted. ``` #include <compare> struct Point { int x; int y; auto operator<=>(const Point&) const = default; // ... non-comparison functions ... }; // compiler generates all six two-way comparison operators #include <iostream> #include <set> int main() { Point pt1{1, 1}, pt2{1, 2}; std::set<Point> s; // ok s.insert(pt1); // ok std::cout << std::boolalpha << (pt1 == pt2) << ' ' // false; operator== is implicitly defaulted. << (pt1 != pt2) << ' ' // true << (pt1 < pt2) << ' ' // true << (pt1 <= pt2) << ' ' // true << (pt1 > pt2) << ' ' // false << (pt1 >= pt2) << ' ';// false } ``` #### Defaulted equality comparison A class can define `operator==` as defaulted, with a return value of `bool`. This will generate an equality comparison of each base class and member subobject, in their declaration order. Two objects are equal if the values of their base classes and members are equal. The test will short-circuit if an inequality is found in members or base classes earlier in declaration order. Per the rules for `operator==`, this will also allow inequality testing: ``` struct Point { int x; int y; bool operator==(const Point&) const = default; // ... non-comparison functions ... }; // compiler generates element-wise equality testing #include <iostream> int main() { Point pt1{3, 5}, pt2{2, 5}; std::cout << std::boolalpha << (pt1 != pt2) << '\n' // true << (pt1 == pt1) << '\n'; // true struct [[maybe_unused]] { int x{}, y{}; } p, q; // if (p == q) { } // Error: 'operator==' is not defined } ``` #### Other defaulted comparison operators Any of the four relational operators can be explicitly defaulted. A defaulted relational operator must have the return type `bool`. Such operator will be deleted if overload resolution over `x <=> y` (considering also `operator<=>` with reversed order of parameters) fails, or if this `operator@` is not applicable to the result of that `x <=> y`. Otherwise, the defaulted `operator@` calls `x <=> y @ 0` if an `operator<=>` with the original order of parameters was selected by overload resolution, or `0 @ y <=> x` otherwise: ``` struct HasNoRelational {}; struct C { friend HasNoRelational operator<=>(const C&, const C&); bool operator<(const C&) = default; // ok, function is deleted }; ``` Similarly, `operator!=` can be defaulted. It is deleted if overload resolution over `x == y` (considering also `operator==` with reversed order of parameters) fails, or if the result of `x == y` does not have type `bool`. The defaulted `operator!=` calls `!(x == y)` or `!(y == x)` as selected by overload resolution. Defaulting the relational operators can be useful in order to create functions whose addresses may be taken. For other uses, it is sufficient to provide only `operator<=>` and `operator==`. ### Custom comparisons and comparison categories When the default semantics are not suitable, such as when the members must be compared out of order, or must use a comparison that's different from their natural comparison, then the programmer can write `operator<=>` and let the compiler generate the appropriate two-way comparison operators. The kind of two-way comparison operators generated depends on the return type of the user-defined `operator<=>`. There are three available return types: | Return type | Equivalent values are.. | Incomparable values are.. | | --- | --- | --- | | [`std::strong_ordering`](../utility/compare/strong_ordering "cpp/utility/compare/strong ordering") | indistinguishable | not allowed | | [`std::weak_ordering`](../utility/compare/weak_ordering "cpp/utility/compare/weak ordering") | distinguishable | not allowed | | [`std::partial_ordering`](../utility/compare/partial_ordering "cpp/utility/compare/partial ordering") | distinguishable | allowed | #### Strong ordering An example of a custom `operator<=>` that returns [`std::strong_ordering`](../utility/compare/strong_ordering "cpp/utility/compare/strong ordering") is an operator that compares every member of a class, except in order that is different from the default (here: last name first). ``` #include <compare> #include <string> struct Base { std::string zip; auto operator<=>(const Base&) const = default; }; struct TotallyOrdered : Base { std::string tax_id; std::string first_name; std::string last_name; public: // custom operator<=> because we want to compare last names first: std::strong_ordering operator<=>(const TotallyOrdered& that) const { if (auto cmp = (Base&)(*this) <=> (Base&)that; cmp != 0) return cmp; if (auto cmp = last_name <=> that.last_name; cmp != 0) return cmp; if (auto cmp = first_name <=> that.first_name; cmp != 0) return cmp; return tax_id <=> that.tax_id; } // ... non-comparison functions ... }; // compiler generates all four relational operators #include <cassert> #include <set> int main() { TotallyOrdered to1{"a","b","c","d"}, to2{"a","b","d","c"}; std::set<TotallyOrdered> s; // ok s.insert(to1); // ok assert(to2 <= to1); // ok, single call to <=> } ``` Note: an operator that returns a [`std::strong_ordering`](../utility/compare/strong_ordering "cpp/utility/compare/strong ordering") should compare every member, because if any member is left out, substitutability can be compromised: it becomes possible to distinguish two values that compare equal. #### Weak ordering An example of a custom `operator<=>` that returns [`std::weak_ordering`](../utility/compare/weak_ordering "cpp/utility/compare/weak ordering") is an operator that compares string members of a class in case-insensitive manner: this is different from the default comparison (so a custom operator is required) and it's possible to distinguish two strings that compare equal under this comparison. ``` class CaseInsensitiveString { std::string s; public: std::weak_ordering operator<=>(const CaseInsensitiveString& b) const { return case_insensitive_compare(s.c_str(), b.s.c_str()); } std::weak_ordering operator<=>(const char* b) const { return case_insensitive_compare(s.c_str(), b); } // ... non-comparison functions ... }; // Compiler generates all four relational operators CaseInsensitiveString cis1, cis2; std::set<CaseInsensitiveString> s; // ok s.insert(/*...*/); // ok if (cis1 <= cis2) { /*...*/ } // ok, performs one comparison operation // Compiler also generates all eight heterogeneous relational operators if (cis1 <= "xyzzy") { /*...*/ } // ok, performs one comparison operation if ("xyzzy" >= cis1) { /*...*/ } // ok, identical semantics ``` Note that this example demonstrates the effect a heterogeneous `operator<=>` has: it generates heterogeneous comparisons in both directions. #### Partial ordering Partial ordering is an ordering that allows incomparable (unordered) values, such as NaN values in floating-point ordering, or, in this example, persons that are not related: ``` class PersonInFamilyTree { // ... public: std::partial_ordering operator<=>(const PersonInFamilyTree& that) const { if (this->is_the_same_person_as ( that)) return partial_ordering::equivalent; if (this->is_transitive_child_of( that)) return partial_ordering::less; if (that. is_transitive_child_of(*this)) return partial_ordering::greater; return partial_ordering::unordered; } // ... non-comparison functions ... }; // compiler generates all four relational operators PersonInFamilyTree per1, per2; if (per1 < per2) { /*...*/ } // ok, per2 is an ancestor of per1 else if (per1 > per2) { /*...*/ } // ok, per1 is an ancestor of per2 else if (std::is_eq(per1 <=> per2)) { /*...*/ } // ok, per1 is per2 else { /*...*/ } // per1 and per2 are unrelated if (per1 <= per2) { /*...*/ } // ok, per2 is per1 or an ancestor of per1 if (per1 >= per2) { /*...*/ } // ok, per1 is per2 or an ancestor of per2 if (std::is_neq(per1 <=> per2)) { /*...*/ } // ok, per1 is not per2 ``` ### See also * [overload resolution](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution") in a call to an overloaded operator * Built-in [three-way comparison operator](operator_comparison#Three-way_comparison "cpp/language/operator comparison") * [Operator overloading](operators#Comparison_operators "cpp/language/operators") for comparison operators
programming_docs
cpp Alternative operator representations Alternative operator representations ==================================== C++ (and C) source code may be written in any non-ASCII 7-bit character set that includes the [ISO 646:1983](https://en.wikipedia.org/wiki/ISO_646 "enwiki:ISO 646") invariant character set. However, several C++ operators and punctuators require characters that are outside of the ISO 646 codeset: `{, }, [, ], #, \, ^, |, ~`. To be able to use character encodings where some or all of these symbols do not exist (such as the German [DIN 66003](http://de.wikipedia.org/wiki/DIN_66003)), C++ defines the following alternatives composed of ISO 646 compatible characters. ### Alternative tokens There are alternative spellings for several operators and other tokens that use non-ISO646 characters. In all respects of the language, each alternative token behaves exactly the same as its primary token, except for its spelling (the [stringification operator](../preprocessor/replace "cpp/preprocessor/replace") can make the spelling visible). The two-letter alternative tokens are sometimes called "digraphs". | Primary | Alternative | | --- | --- | | `&&` | [`and`](../keyword/and "cpp/keyword/and") | | `&=` | [`and_eq`](../keyword/and_eq "cpp/keyword/and eq") | | `&` | [`bitand`](../keyword/bitand "cpp/keyword/bitand") | | `|` | [`bitor`](../keyword/bitor "cpp/keyword/bitor") | | `~` | [`compl`](../keyword/compl "cpp/keyword/compl") | | `!` | [`not`](../keyword/not "cpp/keyword/not") | | `!=` | [`not_eq`](../keyword/not_eq "cpp/keyword/not eq") | | `||` | [`or`](../keyword/or "cpp/keyword/or") | | `|=` | [`or_eq`](../keyword/or_eq "cpp/keyword/or eq") | | `^` | [`xor`](../keyword/xor "cpp/keyword/xor") | | `^=` | [`xor_eq`](../keyword/xor_eq "cpp/keyword/xor eq") | | `{` | `<%` | | `}` | `%>` | | `[` | `<:` | | `]` | `:>` | | `#` | `%:` | | `##` | `%:%:` | When the parser encounters the character sequence `<::` and the subsequent character is neither `:` nor `>`, the `<` is treated as a preprocessing token by itself and not as the first character of the alternative token `<:`. Thus `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<::[std::string](http://en.cppreference.com/w/cpp/string/basic_string)>` won't be wrongly treated as `[std::vector](http://en.cppreference.com/w/cpp/container/vector)[:[std::string](http://en.cppreference.com/w/cpp/string/basic_string)>`. ### Notes The characters `&` and `!` are invariant under ISO-646, but alternatives are provided for the tokens that use these characters anyway to accomodate even more restrictive historical charsets. There is no alternative spelling (such as `eq`) for the equality operator `==` because the character `=` was present in all supported charsets. ### Compatibility with C The same words are defined in the C programming language in the include file `<iso646.h>` as macros. Because in C++ these are built into the language, the C++ version of `<iso646.h>`, as well as `<ciso646>`, does not define anything. ### Example The following example demonstrates the use of several alternative tokens. ``` %:include <iostream> struct X <% compl X() <%%> // destructor X() <%%> X(const X bitand) = delete; // copy constructor bool operator not_eq(const X bitand other) <% return this not_eq bitand other; %> %>; int main(int argc, char* argv<::>) <% // lambda with reference-capture: auto greet = <:bitand:>(const char* name) <% std::cout << "Hello " << name << " from " << argv<:0:> << '\n'; %>; if (argc > 1 and argv<:1:> not_eq nullptr) <% greet(argv<:1:>); %> else <% greet("Anon"); %> %> ``` Possible output: ``` Hello Anon from ./a.out ``` ### Trigraphs (removed in C++17) The following three-character groups (trigraphs) are [parsed before comments and string literals are recognized](translation_phases "cpp/language/translation phases"), and each appearance of a trigraph is replaced by the corresponding primary character: | Primary | Trigraph | | --- | --- | | `{` | `??<` | | } | `??>` | | `[` | `??(` | | `]` | `??)` | | `#` | `??=` | | `\` | `??/` | | `^` | `??'` | | `|` | `??!` | | `~` | `??-` | Because trigraphs are processed early, a comment such as `// Will the next line be executed?????/` will effectively comment out the following line, and the string literal such as `"Enter date ??/??/??"` is parsed as `"Enter date \\??"`. ### Keywords [`and`](../keyword/and "cpp/keyword/and"), [`and_eq`](../keyword/and_eq "cpp/keyword/and eq"), [`bitand`](../keyword/bitand "cpp/keyword/bitand"), [`bitor`](../keyword/bitor "cpp/keyword/bitor"), [`compl`](../keyword/compl "cpp/keyword/compl"), [`not`](../keyword/not "cpp/keyword/not"), [`not_eq`](../keyword/not_eq "cpp/keyword/not eq"), [`or`](../keyword/or "cpp/keyword/or"), [`or_eq`](../keyword/or_eq "cpp/keyword/or eq"), [`xor`](../keyword/xor "cpp/keyword/xor"), [`xor_eq`](../keyword/xor_eq "cpp/keyword/xor eq"). ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1104](https://cplusplus.github.io/CWG/issues/1104.html) | C++98 | the alternative token `<:` caused `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<::[std::string](http://en.cppreference.com/w/cpp/string/basic_string)>`to be treated as `[std::vector](http://en.cppreference.com/w/cpp/container/vector)[:[std::string](http://en.cppreference.com/w/cpp/string/basic_string)>` | add an additional lexingrule to address this case | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/operator_alternative "c/language/operator alternative") for Alternative operators and tokens | cpp Member templates Member templates ================ Template declarations ([class](class_template "cpp/language/class template"), [function](function_template "cpp/language/function template"), and [variables](variable_template "cpp/language/variable template") (since C++14)) can appear inside a [member specification](class "cpp/language/class") of any class, struct, or union that aren't [local classes](class#Local_classes "cpp/language/class"). ``` #include <algorithm> #include <iostream> #include <string> #include <vector> struct Printer { // generic functor std::ostream& os; Printer(std::ostream& os) : os(os) {} template<typename T> void operator()(const T& obj) { os << obj << ' '; } // member template }; int main() { std::vector<int> v = {1,2,3}; std::for_each(v.begin(), v.end(), Printer(std::cout)); std::string s {"abc"}; std::ranges::for_each(s, Printer(std::cout)); } ``` Output: ``` 1 2 3 a b c ``` Partial specializations of member template may appear both at class scope and at enclosing namespace scope. Explicit specializations may appear in any scope in which the primary template may appear. ``` struct A { template<class T> struct B; // primary member template template<class T> struct B<T*> { }; // OK: partial specialization // template<> struct B<int*> { }; // OK via CWG 727: full specialization }; template<> struct A::B<int*> { }; // OK template<class T> struct A::B<T&> { }; // OK ``` If the enclosing class declaration is, in turn, a class template, when a member template is defined outside of the class body, it takes two sets of template parameters: one for the enclosing class, and another one for itself: ``` template<typename T1> struct string { // member template function template<typename T2> int compare(const T2&); // constructors can be templates too template<typename T2> string(const std::basic_string<T2>& s) { /*...*/ } }; // out of class definition of string<T1>::compare<T2> template<typename T1> // for the enclosing class template template<typename T2> // for the member template int string<T1>::compare(const T2& s) { /* ... */ } ``` ### Member function templates Destructors and copy constructors cannot be templates. If a template constructor is declared which could be instantiated with the type signature of a [copy constructor](copy_constructor "cpp/language/copy constructor"), the implicitly-declared copy constructor is used instead. A member function template cannot be virtual, and a member function template in a derived class cannot override a virtual member function from the base class. ``` class Base { virtual void f(int); }; struct Derived : Base { // this member template does not override Base::f template <class T> void f(T); // non-template member override can call the template: void f(int i) override { f<>(i); } }; ``` A non-template member function and a template member function with the same name may be declared. In case of conflict (when some template specialization matches the non-template function signature exactly), the use of that name and type refers to the non-template member unless an explicit template argument list is supplied. ``` template<typename T> struct A { void f(int); // non-template member template<typename T2> void f(T2); // member template }; //template member definition template<typename T> template<typename T2> void A<T>::f(T2) { // some code } int main() { A<char> ac; ac.f('c'); // calls template function A<char>::f<char>(char) ac.f(1); // calls non-template function A<char>::f(int) ac.f<>(1); // calls template function A<char>::f<int>(int) } ``` An out-of-class definition of a member function template must be *equivalent* to the declaration inside the class (see [function template overloading](function_template#Function_template_overloading "cpp/language/function template") for the definition of equivalency), otherwise it is considered to be an overload. ``` struct X { template<class T> T good(T n); template<class T> T bad(T n); }; template<class T> struct identity { using type = T; }; // OK: equivalent declaration template<class V> V X::good(V n) { return n; } // Error: not equivalent to any of the declarations inside X template<class T> T X::bad(typename identity<T>::type n) { return n; } ``` ### Conversion function templates A user-defined [conversion function](cast_operator "cpp/language/cast operator") can be a template. ``` struct A { template<typename T> operator T*(); // conversion to pointer to any type }; // out-of-class definition template<typename T> A::operator T*() {return nullptr;} // explicit specialization for char* template<> A::operator char*() {return nullptr;} // explicit instantiation template A::operator void*(); int main() { A a; int* ip = a.operator int*(); // explicit call to A::operator int*() } ``` During [overload resolution](overload_resolution "cpp/language/overload resolution"), specializations of conversion function templates are not found by [name lookup](lookup "cpp/language/lookup"). Instead, all visible conversion function templates are considered, and every specialization produced by [template argument deduction](template_argument_deduction "cpp/language/template argument deduction") (which has special rules for conversion function templates) is used as if found by name lookup. Using-declarations in derived classes cannot refer to specializations of template conversion functions from base classes. | | | | --- | --- | | A user-defined conversion function template cannot have a deduced return type: ``` struct S { operator auto() const { return 10; } // OK template<class T> operator auto() const { return 42; } // error }; ``` | (since C++14) | | | | | --- | --- | | Member variable templates A variable template declaration may appear at class scope, in which case it declares a static data member template. See [variable templates](variable_template "cpp/language/variable template") for details. | (since C++14) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1878](https://cplusplus.github.io/CWG/issues/1878.html) | C++14 | operator auto was technically allowed | operator auto forbidden | cpp sizeof... operator (since C++11) sizeof... operator (since C++11) ================================ Queries the number of elements in a [parameter pack](parameter_pack "cpp/language/parameter pack"). ### Syntax | | | | | --- | --- | --- | | `sizeof...(` parameter-pack `)` | | | Returns a constant of type `[std::size\_t](../types/size_t "cpp/types/size t")`. ### Explanation Returns the number of elements in a [parameter pack](parameter_pack "cpp/language/parameter pack"). ### Keywords [`sizeof`](../keyword/sizeof "cpp/keyword/sizeof"). ### Example ``` #include <array> #include <iostream> #include <type_traits> template<typename... Ts> constexpr auto make_array(Ts&&... ts) { using CT = std::common_type_t<Ts...>; return std::array<CT, sizeof...(Ts)>{std::forward<CT>(ts)...}; } int main() { std::array<double, 4ul> arr = make_array(1, 2.71f, 3.14, '*'); std::cout << "arr = { "; for (auto s{arr.size()}; double elem : arr) std::cout << elem << (--s ? ", " : " "); std::cout << "}\n"; } ``` Output: ``` arr = { 1, 2.71, 3.14, 42 } ``` ### See also * [sizeof](sizeof "cpp/language/sizeof") cpp Class template argument deduction (CTAD) (since C++17) Class template argument deduction (CTAD) (since C++17) ====================================================== In order to instantiate a [class template](class_template "cpp/language/class template"), every template argument must be known, but not every template argument has to be specified. In the following contexts the compiler will deduce the template arguments from the type of the initializer: * any [declaration](declarations "cpp/language/declarations") that specifies initialization of a variable and variable template, whose declared type is the class template (possibly cv-qualified): ``` std::pair p(2, 4.5); // deduces to std::pair<int, double> p(2, 4.5); std::tuple t(4, 3, 2.5); // same as auto t = std::make_tuple(4, 3, 2.5); std::less l; // same as std::less<void> l; ``` * [new-expressions](new "cpp/language/new"): ``` template<class T> struct A { A(T, T); }; auto y = new A{1, 2}; // allocated type is A<int> ``` * [function-style cast](explicit_cast "cpp/language/explicit cast") expressions: ``` auto lck = std::lock_guard(mtx); // deduces to std::lock_guard<std::mutex> std::copy_n(vi1, 3, std::back_insert_iterator(vi2)); // deduces to std::back_insert_iterator<T>, // where T is the type of the container vi2 std::for_each(vi.begin(), vi.end(), Foo([&](int i) {...})); // deduces to Foo<T>, // where T is the unique lambda type ``` | | | | --- | --- | | * the type of a [non-type template parameter](template_parameters#Non-type_template_parameter "cpp/language/template parameters"): ``` template<class T> struct X { constexpr X(T) {} auto operator<=>(const X&) const = default; }; template<X x> struct Y {}; Y<0> y; // OK, Y<X<int>(0)> ``` | (since C++20) | ### Deduction for class templates #### Implicitly-generated deduction guides When, in a function-style cast or in a variable's declaration, the type specifier consists solely of the name of a primary class template `C` (i.e., there is no accompanying template argument list), candidates for deduction are formed as follows: * If `C` is defined, for each constructor (or constructor template) `Ci` declared in the named primary template, a fictional function template `Fi`, is constructed, such that + template parameters of `Fi` are the template parameters of `C` followed (if `Ci` is a constructor template) by the template parameters of `Ci` (default template arguments are included too) + the function parameters of `Fi` are the constructor parameters + the return type of `Fi` is `C` followed by the template parameters of the class template enclosed in `<>` * If `C` is not defined or does not declare any constructors, an additional fictional function template is added, derived as above from a hypothetical constructor `C()` * In any case, an additional fictional function template derived as above from a hypothetical constructor `C(C)` is added, called the copy deduction candidate. | | | | --- | --- | | * In addition, if * `C` is defined and satisfies the requirements of an [aggregate type](aggregate_initialization "cpp/language/aggregate initialization") with the assumption that any dependent base class has no virtual functions or virtual base classes, * there are no user-defined deduction guides for `C`, and * the variable is initialized from a non-empty list of initializers arg1, arg2, ..., argn (which may use [designated initializer](aggregate_initialization#Designated_initializer "cpp/language/aggregate initialization")), an aggregate deduction candidate may be added. The parameter list of the aggregate deduction candidate is produced from the aggregate element types, as follows: * Let `ei` be the (possibly recursive) aggregate element (public base/class member/array element) that would be initialized from `argi`, where * brace elision is only considered for members with non-dependent type or with array type of non-dependent bound, * if `C` (or its element that is itself an aggregate) has a base that is a [pack expansion](parameter_pack "cpp/language/parameter pack"): + if the pack expansion is a trailing aggregate element, it is considered to match all remaining elements of the initializer list; + otherwise, the pack is considered to be empty. * If there's no such `ei`, the aggregate deduction candidate is not added. * Otherwise, determine the parameter list `T1, T2, ..., Tn` of the aggregate deduction candidate as follows: + If `ei` is an array and `argi` is either a braced-init-list or a string literal, `Ti` is rvalue reference to the type of `ei`. + Otherwise, `Ti` is the type of `ei`. + If a pack was skipped because it is a non-trailing aggregate element, an additional parameter pack of the form `Pj ...` is inserted in its original aggregate element position. (This will generally cause deduction to fail.) + If a pack is a trailing aggregate element, the trailing sequence of parameters corresponding to it is replaced by a single parameter of the form `Tn ...`. The aggregate deduction candidate is a fictional function template derived as above from a hypothetical constructor `C(T1, T2, ..., Tn)`. During template argument deduction for the aggregate deduction candidate, the number of elements in a trailing parameter pack is only deduced from the number of remaining function arguments if it is not otherwise deduced. ``` template<class T> struct A { T t; struct { long a, b; } u; }; A a{1, 2, 3}; // aggregate deduction candidate: // template<class T> // A<T> F(T, long, long); template<class... Args> struct B : std::tuple<Args...>, Args... {}; B b{std::tuple<std::any, std::string>{}, std::any{}}; // aggregate deduction candidate: // template<class... Args> // B<Args...> F(std::tuple<Args...>, Args...); // type of b is deduced as B<std::any, std::string> ``` | (since C++20) | [Template argument deduction](template_argument_deduction "cpp/language/template argument deduction") and [overload resolution](overload_resolution "cpp/language/overload resolution") is then performed for initialization of a fictional object of hypothetical class type, whose constructor signatures match the guides (except for return type) for the purpose of forming an overload set, and the initializer is provided by the context in which class template argument deduction was performed, except that the first phase of [list-initialization](overload_resolution#List-initialization "cpp/language/overload resolution") (considering initializer-list constructors) is omitted if the initializer list consists of a single expression of type (possibly cv-qualified) `U`, where `U` is a specialization of `C` or a class derived from a specialization of `C`. These fictional constructors are public members of the hypothetical class type. They are explicit if the guide was formed from an explicit constructor. If overload resolution fails, the program is ill-formed. Otherwise, the return type of the selected `F` template specialization becomes the deduced class template specialization. ``` template<class T> struct UniquePtr { UniquePtr(T* t); }; UniquePtr dp{new auto(2.0)}; // One declared constructor: // C1: UniquePtr(T*); // Set of implicitly-generated deduction guides: // F1: template<class T> // UniquePtr<T> F(T *p); // F2: template<class T> // UniquePtr<T> F(UniquePtr<T>); // copy deduction candidate // imaginary class to initialize: // struct X // { // template<class T> // X(T *p); // from F1 // // template<class T> // X(UniquePtr<T>); // from F2 // }; // direct-initialization of an X object // with "new double(2.0)" as the initializer // selects the constructor that corresponds to the guide F1 with T = double // For F1 with T=double, the return type is UniquePtr<double> // result: // UniquePtr<double> dp{new auto(2.0)} ``` Or, for a more complex example (note: "`S::N`" would not compile: scope resolution qualifiers are not something that can be deduced): ``` template<class T> struct S { template<class U> struct N { N(T); N(T, U); template<class V> N(V, U); }; }; S<int>::N x{2.0, 1}; // the implicitly-generated deduction guides are (note that T is already known to be int) // F1: template<class U> // S<int>::N<U> F(int); // F2: template<class U> // S<int>::N<U> F(int, U); // F3: template<class U, class V> // S<int>::N<U> F(V, U); // F4: template<class U> // S<int>::N<U> F(S<int>::N<U>); (copy deduction candidate) // Overload resolution for direct-list-init with "{2.0, 1}" as the initializer // chooses F3 with U=int and V=double. // The return type is S<int>::N<int> // result: // S<int>::N<int> x{2.0, 1}; ``` #### User-defined deduction guides The syntax of a user-defined deduction guide is the syntax of a function declaration with a trailing return type, except that it uses the name of a class template as the function name: | | | | | --- | --- | --- | | explicit-specifier(optional) template-name `(` parameter-declaration-clause `) ->` simple-template-id `;` | | | User-defined deduction guides must name a class template and must be introduced within the same semantic scope of the class template (which could be namespace or enclosing class) and, for a member class template, must have the same access, but deduction guides do not become members of that scope. A deduction guide is not a function and does not have a body. Deduction guides are not found by name lookup and do not participate in overload resolution except for the [overload resolution against other deduction guides](overload_resolution#Best_viable_function "cpp/language/overload resolution") when deducing class template arguments. Deduction guides cannot be redeclared in the same translation unit for the same class template. ``` // declaration of the template template<class T> struct container { container(T t) {} template<class Iter> container(Iter beg, Iter end); }; // additional deduction guide template<class Iter> container(Iter b, Iter e) -> container<typename std::iterator_traits<Iter>::value_type>; // uses container c(7); // OK: deduces T=int using an implicitly-generated guide std::vector<double> v = {/* ... */}; auto d = container(v.begin(), v.end()); // OK: deduces T=double container e{5, 6}; // Error: there is no std::iterator_traits<int>::value_type ``` The fictional constructors for the purpose of overload resolution (described above) are explicit if they correspond to an implicitly-generated deduction guide formed from an explicit constructor or to a user-defined deduction guide that is declared [explicit](explicit "cpp/language/explicit"). As always, such constructors are ignored in copy-initialization context: ``` template<class T> struct A { explicit A(const T&, ...) noexcept; // #1 A(T&&, ...); // #2 }; int i; A a1 = {i, i}; // error: cannot deduce from rvalue reference in #2, // and #1 is explicit, and not considered in copy-initialization. A a2{i, i}; // OK, #1 deduces to A<int> and also initializes A a3{0, i}; // OK, #2 deduces to A<int> and also initializes A a4 = {0, i}; // OK, #2 deduces to A<int> and also initializes template<class T> A(const T&, const T&) -> A<T&>; // #3 template<class T> explicit A(T&&, T&&) -> A<T>; // #4 A a5 = {0, 1}; // error: #3 deduces to A<int&> // and #1 & #2 result in same parameter constructors. A a6{0, 1}; // OK, #4 deduces to A<int> and #2 initializes A a7 = {0, i}; // error: #3 deduces to A<int&> A a8{0, i}; // error: #3 deduces to A<int&> ``` Using a member typedef or alias template in a constructor or constructor template's parameter list does not, by itself, render the corresponding parameter of the implicitly generated guide a non-deduced context. ``` template<class T> struct B { template<class U> using TA = T; template<class U> B(U, TA<U>); // #1 }; // Implicit deduction guide generated from #1 is the equivalent of // template<class T, class U> // B(U, T) -> B<T>; // rather than // template<class T, class U> // B(U, typename B<T>::template TA<U>) -> B<T>; // which would not have been deducible B b{(int*)0, (char*)0}; // OK, deduces B<char*> ``` | | | | --- | --- | | Deduction for alias templates When a function-style cast or declaration of a variable uses the name of an alias template `A` without an argument list as the type specifier, where `A` is defined as an alias of `B<ArgList>`, the scope of `B` is non-dependent, and `B` is either a class template or a similarly-defined alias template, deduction will proceed in the same way as for class templates, except that the guides are instead generated from the guides of `B`, as follows:* For each guide `f` of `B`, deduce the template arguments of the return type of `f` from `B<ArgList>` using [template argument deduction](template_argument_deduction "cpp/language/template argument deduction"), except that deduction does not fail if some arguments are not deduced. * Substitute the result of above deduction into `f`, if substitution fails, no guide is produced; otherwise, let `g` denote the result of substitution, a guide `f'` is formed, such that + The parameter types and the return type of `f'` are the same as `g` + If `f` is a template, `f'` is a function template whose template parameter list consists of all the template parameters of `A` (including their default template arguments) that appear in the above deductions or (recursively) in their default template arguments, followed by the template parameters of `f` that were not deduced (including their default template arguments); otherwise (`f` is not a template), `f'` is a function + The associated [constraints](constraints "cpp/language/constraints") of `f'` are the conjunction of the associated constraints of `g` and a constraint that is satisfied if and only if the arguments of `A` are deducible from the result type ``` template<class T> class unique_ptr { /* ... */ }; template<class T> class unique_ptr<T[]> { /* ... */ }; template<class T> unique_ptr(T*) -> unique_ptr<T>; // #1 template<class T> unique_ptr(T*) -> unique_ptr<T[]>; // #2 template<class T> concept NonArray = !std::is_array_v<T>; template<NonArray A> using unique_ptr_nonarray = unique_ptr<A>; template<class A> using unique_ptr_array = unique_ptr<A[]>; // generated guide for unique_ptr_nonarray: // from #1 (deduction of unique_ptr<T> from unique_ptr<A> yields T = A): // template<class A> // requires(argument_of_unique_ptr_nonarray_is_deducible_from<unique_ptr<A>>) // auto F(A*) -> unique_ptr<A>; // from #2 (deduction of unique_ptr<T[]> from unique_ptr<A> yields nothing): // template<class T> // requires(argument_of_unique_ptr_nonarray_is_deducible_from<unique_ptr<T[]>>) // auto F(T*) -> unique_ptr<T[]>; // where argument_of_unique_ptr_nonarray_is_deducible_from can be defined as // template<class> // class AA; // template<NonArray A> // class AA<unique_ptr_nonarray<A>> {}; // template<class T> // concept argument_of_unique_ptr_nonarray_is_deducible_from = // requires { sizeof(AA<T>); }; // generated guide for unique_ptr_array: // from #1 (deduction of unique_ptr<T> from unique_ptr<A[]> yields T = A[]): // template<class A> // requires(argument_of_unique_ptr_array_is_deducible_from<unique_ptr<A[]>>) // auto F(A(*)[]) -> unique_ptr<A[]>; // from #2 (deduction of unique_ptr<T[]> from unique_ptr<A[]> yields T = A): // template<class A> // requires(argument_of_unique_ptr_array_is_deducible_from<unique_ptr<A[]>>) // auto F(A*) -> unique_ptr<A[]>; // where argument_of_unique_ptr_array_is_deducible_from can be defined as // template<class> // class BB; // template<class A> // class BB<unique_ptr_array<A>> {}; // template<class T> // concept argument_of_unique_ptr_array_is_deducible_from = // requires { sizeof(BB<T>); }; // Use: unique_ptr_nonarray p(new int); // deduced to unique_ptr<int> // deduction guide generated from #1 returns unique_ptr<int> // deduction guide generated from #2 returns unique_ptr<int[]>, which is ignored because // argument_of_unique_ptr_nonarray_is_deducible_from<unique_ptr<int[]>> is unsatisfied unique_ptr_array q(new int[42]); // deduced to unique_ptr<int[]> // deduction guide generated from #1 fails (cannot deduce A in A(*)[] from new int[42]) // deduction guide generated from #2 returns unique_ptr<int[]> ``` | (since C++20) | ### Notes Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place. ``` std::tuple t1(1, 2, 3); // OK: deduction std::tuple<int, int, int> t2(1, 2, 3); // OK: all arguments are provided std::tuple<> t3(1, 2, 3); // Error: no matching constructor in tuple<>. // No deduction performed. std::tuple<int> t4(1, 2, 3); // Error ``` | | | | --- | --- | | Class template argument deduction of aggregates typically requires user-defined deduction guides: ``` template<class A, class B> struct Agg { A a; B b; }; // implicitly-generated guides are formed from default, copy, and move constructors template<class A, class B> Agg(A a, B b) -> Agg<A, B>; // ^ This deduction guide can be implicitly generated in C++20 Agg agg{1, 2.0}; // deduced to Agg<int, double> from the user-defined guide template<class... T> array(T&&... t) -> array<std::common_type_t<T...>, sizeof...(T)>; auto a = array{1, 2, 5u}; // deduced to array<unsigned, 3> from the user-defined guide ``` | (until C++20) | User-defined deduction guides do not have to be templates: ``` template<class T> struct S { S(T); }; S(char const*) -> S<std::string>; S s{"hello"}; // deduced to S<std::string> ``` Within the scope of a class template, the name of the template without a parameter list is an injected class name, and can be used as a type. In that case, class argument deduction does not happen and template parameters must be supplied explicitly: ``` template<class T> struct X { X(T) {} template<class Iter> X(Iter b, Iter e) {} template<class Iter> auto foo(Iter b, Iter e) { return X(b, e); // no deduction: X is the current X<T> } template<class Iter> auto bar(Iter b, Iter e) { return X<typename Iter::value_type>(b, e); // must specify what we want } auto baz() { return ::X(0); // not the injected-class-name; deduced to be X<int> } }; ``` In [overload resolution](overload_resolution#Best_viable_function "cpp/language/overload resolution"), partial ordering takes precedence over whether a function template is generated from a user-defined deduction guide: if the function template generated from the constructor is more specialized than the one generated from the user-defined deduction guide, the one generated from the constructor is chosen. Because the copy deduction candidate is typically more specialized than a wrapping constructor, this rule means that copying is generally preferred over wrapping. ``` template<class T> struct A { A(T, int*); // #1 A(A<T>&, int*); // #2 enum { value }; }; template<class T, int N = T::value> A(T&&, int*) -> A<T>; //#3 A a{1, 0}; // uses #1 to deduce A<int> and initializes with #1 A b{a, 0}; // uses #2 (more specialized than #3) to deduce A<int> and initializes with #2 ``` When earlier tiebreakers, including partial ordering, failed to distinguish between two candidate function templates, the following rules apply: * A function template generated from a user-defined deduction guide is preferred over one implicitly generated from a constructor or constructor template. * The copy deduction candidate is preferred over all other function templates implicitly generated from a constructor or constructor template. * A function template implicitly generated from a non-template constructor is preferred over a function template implicitly generated from a constructor template. ``` template<class T> struct A { using value_type = T; A(value_type); // #1 A(const A&); // #2 A(T, T, int); // #3 template<class U> A(int, T, U); // #4 }; // #5, the copy deduction candidate A(A); A x(1, 2, 3); // uses #3, generated from a non-template constructor template<class T> A(T) -> A<T>; // #6, less specialized than #5 A a(42); // uses #6 to deduce A<int> and #1 to initialize A b = a; // uses #5 to deduce A<int> and #2 to initialize template<class T> A(A<T>) -> A<A<T>>; // #7, as specialized as #5 A b2 = a; // uses #7 to deduce A<A<int>> and #1 to initialize ``` An rvalue reference to a cv-unqualified template parameter is not a [forwarding reference](template_argument_deduction "cpp/language/template argument deduction") if that parameter is a class template parameter: ``` template<class T> struct A { template<class U> A(T&&, U&&, int*); // #1: T&& is not a forwarding reference // U&& is a forwarding reference A(T&&, int*); // #2: T&& is not a forwarding reference }; template<class T> A(T&&, int*) -> A<T>; // #3: T&& is a forwarding reference int i, *ip; A a{i, 0, ip}; // error, cannot deduce from #1 A a0{0, 0, ip}; // uses #1 to deduce A<int> and #1 to initialize A a2{i, ip}; // uses #3 to deduce A<int&> and #2 to initialize ``` When initializing from a single argument of a type that is a specialization of the class template at issue, copying deduction is generally preferred over wrapping by default: ``` std::tuple t1{1}; //std::tuple<int> std::tuple t2{t1}; //std::tuple<int>, not std::tuple<std::tuple<int>> std::vector v1{1, 2}; // std::vector<int> std::vector v2{v1}; // std::vector<int>, not std::vector<std::vector<int>> (P0702R1) std::vector v3{v1, v2}; // std::vector<std::vector<int>> ``` Outside the special case for copying vs. wrapping, the strong preference for initializer-list constructors in list-initialization remains intact. ``` std::vector v1{1, 2}; // std::vector<int> std::vector v2(v1.begin(), v1.end()); // std::vector<int> std::vector v3{v1.begin(), v1.end()}; // std::vector<std::vector<int>::iterator> ``` Before class template argument deduction was introduced, a common approach to avoiding explicitly specifying arguments is to use a function template: ``` std::tuple p1{1, 1.0}; //std::tuple<int, double>, using deduction auto p2 = std::make_tuple(1, 1.0); //std::tuple<int, double>, pre-C++17 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 2376](https://cplusplus.github.io/CWG/issues/2376.html) | C++17 | CTAD would be performed even if the type of the variable declared isdifferent from the class template whose arguments will be deduced | do not performCTAD in this case | | [P0702R1](https://wg21.link/P0702R1) | C++17 | an initializer-list constructor can pre-empt thecopy deduction candidate, resulting in wrapping | initializer-list phaseskipped when copying |
programming_docs
cpp Destructors Destructors =========== A destructor is a special [member function](member_functions "cpp/language/member functions") that is called when the [lifetime of an object](lifetime "cpp/language/lifetime") ends. The purpose of the destructor is to free the resources that the object may have acquired during its lifetime. | | | | --- | --- | | A destructor must not be a [coroutine](coroutines "cpp/language/coroutines"). | (since C++20) | ### Syntax | | | | | --- | --- | --- | | `~` class-name `();` | (1) | | | `virtual` `~` class-name `();` | (2) | | | decl-specifier-seq(optional) `~` class-name `() = default;` | (3) | (since C++11) | | decl-specifier-seq(optional) `~` class-name `() = delete;` | (4) | (since C++11) | | attr(optional) decl-specifier-seq(optional) id-expression `(` `void`(optional) `)` except(optional) attr(optional) requires-clause(optional)`;` | (5) | | 1) Typical declaration of a prospective (since C++20) destructor 2) Virtual destructor is usually required in a base class 3) Forcing a destructor to be generated by the compiler 4) Disabling the implicit destructor 5) Formal syntax of a prospective (since C++20) destructor declaration | | | | | --- | --- | --- | | decl-specifier-seq | - | `friend`, `inline`, `virtual`, `constexpr`, `consteval` (since C++20) | | id-expression | - | within a class definition, the symbol `~` followed by the class-name. Within a class template, the symbol `~` followed by the name of the current instantiation of the template. At namespace scope or in a [friend](friend "cpp/language/friend") declaration within a different class, *nested-name-specifier* followed by the symbol `~` followed by the class-name which is the same class as the one named by the nested-name-specifier. In any case, the name must be the actual name of the class or template, and not a typedef. The entire id-expression may be surrounded by parentheses which do not change its meaning. | | attr | - | (since C++11) optional sequence of any number of [attributes](attributes "cpp/language/attributes") | | except | - | exception specification as in any [function declaration](function "cpp/language/function") | | | | --- | --- | | Except that if no exception specification is explicitly provided, the exception specification is considered to be one that would be used by the implicitly-declared destructor (see below). In most cases, this is `noexcept(true)`. Thus a throwing destructor must be explicitly declared `noexcept(false)`. | (since C++11) | | | requires-clause | - | (since C++20) requires-clause that declares the associated [constraints](constraints "cpp/language/constraints") for the prospective destructor, which must be satisfied in order for the prospective destructor to be selected as the destructor | ### Explanation The destructor is called whenever an object's [lifetime](lifetime "cpp/language/lifetime") ends, which includes. * [program termination](../utility/program/exit "cpp/utility/program/exit"), for objects with static [storage duration](storage_duration "cpp/language/storage duration") | | | | --- | --- | | * thread exit, for objects with thread-local storage duration | (since C++11) | * end of scope, for objects with automatic storage duration and for temporaries whose life was extended by binding to a reference * [delete-expression](delete "cpp/language/delete"), for objects with dynamic storage duration * end of the full [expression](expressions "cpp/language/expressions"), for nameless temporaries * [stack unwinding](throw "cpp/language/throw"), for objects with automatic storage duration when an exception escapes their block, uncaught. The destructor may also be called directly, e.g. to destroy an object that was constructed using [placement-new](new "cpp/language/new") or through an allocator member function such as [`std::allocator::destroy()`](../memory/allocator/destroy "cpp/memory/allocator/destroy"), to destroy an object that was constructed through the allocator. Note that calling a destructor directly for an ordinary object, such as a local variable, invokes undefined behavior when the destructor is called again, at the end of scope. In generic contexts, the destructor call syntax can be used with an object of non-class type; this is known as pseudo-destructor call: see [member access operator](operator_member_access#Built-in_member_access_operators "cpp/language/operator member access"). | | | | --- | --- | | Prospective destructor A class may have one or more prospective destructors, one of which is selected as the destructor for the class. In order to determine which prospective destructor is the destructor, at the end of the definition of the class, [overload resolution](overload_resolution "cpp/language/overload resolution") is performed among prospective destructors declared in the class with an empty argument list. If the overload resolution fails, the program is ill-formed. Destructor selection does not [odr-use](definition#One_Definition_Rule "cpp/language/definition") the selected destructor, and the selected destructor may be deleted. All prospective destructors are special member functions. If no user-declared prospective destructor is provided for class `T`, the compiler will always declare one (see below), and the implicitly declared prospective destructor is also the destructor for `T`. | (since C++20) | ### Implicitly-declared destructor If no user-declared prospective (since C++20) destructor is provided for a [class type](class "cpp/language/class") (`struct`, `class`, or `union`), the compiler will always declare a destructor as an `inline public` member of its class. As with any implicitly-declared special member function, the exception specification of the implicitly-declared destructor is non-throwing unless the destructor of any potentially-constructed base or member is [potentially-throwing](noexcept_spec "cpp/language/noexcept spec") (since C++17)implicit definition would directly invoke a function with a different exception specification (until C++17). In practice, implicit destructors are `noexcept` unless the class is "poisoned" by a base or member whose destructor is `noexcept(false)`. ### Deleted implicitly-declared destructor The implicitly-declared or explicitly defaulted destructor for class `T` is undefined (until C++11)defined as *deleted* (since C++11) if any of the following is true: * `T` has a non-static data member that cannot be destructed (has deleted or inaccessible destructor) * `T` has direct or virtual base class that cannot be destructed (has deleted or inaccessible destructors) | | | | --- | --- | | * `T` is a union and has a variant member with non-trivial destructor. | (since C++11) | * The implicitly-declared destructor is virtual (because the base class has a virtual destructor) and the lookup for the deallocation function (`[operator delete](http://en.cppreference.com/w/cpp/memory/new/operator_delete)()`) results in a call to ambiguous, deleted, or inaccessible function. | | | | --- | --- | | An explicitly defaulted prospective destructor for `T` is defined as deleted if it is not the destructor for `T`. | (since C++20) | ### Trivial destructor The destructor for class `T` is trivial if all of the following is true: * The destructor is not user-provided (meaning, it is either implicitly declared, or explicitly defined as defaulted on its first declaration) * The destructor is not virtual (that is, the base class destructor is not virtual) * All direct base classes have trivial destructors * All non-static data members of class type (or array of class type) have trivial destructors A trivial destructor is a destructor that performs no action. Objects with trivial destructors don't require a delete-expression and may be disposed of by simply deallocating their storage. All data types compatible with the C language (POD types) are trivially destructible. ### Implicitly-defined destructor If an implicitly-declared destructor is not deleted, it is implicitly defined (that is, a function body is generated and compiled) by the compiler when it is [odr-used](definition#ODR-use "cpp/language/definition"). This implicitly-defined destructor has an empty body. If this satisfies the requirements of a [constexpr destructor](constexpr "cpp/language/constexpr"), the generated destructor is `constexpr`. (since C++20). ### Destruction sequence For both user-defined or implicitly-defined destructors, after executing the body of the destructor and destroying any automatic objects allocated within the body, the compiler calls the destructors for all non-static non-variant data members of the class, in reverse order of declaration, then it calls the destructors of all direct non-virtual base classes in [reverse order of construction](initializer_list#Initialization_order "cpp/language/initializer list") (which in turn call the destructors of their members and their base classes, etc), and then, if this object is of most-derived class, it calls the destructors of all virtual bases. Even when the destructor is called directly (e.g. `obj.~Foo();`), the return statement in `~Foo()` does not return control to the caller immediately: it calls all those member and base destructors first. ### Virtual destructors Deleting an object through pointer to base invokes undefined behavior unless the destructor in the base class is [virtual](virtual "cpp/language/virtual"): ``` class Base { public: virtual ~Base() {} }; class Derived : public Base {}; Base* b = new Derived; delete b; // safe ``` A common guideline is that a destructor for a base class must be [either public and virtual or protected and nonvirtual](http://www.gotw.ca/publications/mill18.htm). ### Pure virtual destructors A prospective (since C++20) destructor may be declared [pure virtual](abstract_class "cpp/language/abstract class"), for example in a base class which needs to be made abstract, but has no other suitable functions that could be declared pure virtual. A pure virtual destructor must have a definition, since all base class destructors are always called when the derived class is destroyed: ``` class AbstractBase { public: virtual ~AbstractBase() = 0; }; AbstractBase::~AbstractBase() {} class Derived : public AbstractBase {}; // AbstractBase obj; // compiler error Derived obj; // OK ``` ### Exceptions As any other function, a destructor may terminate by throwing an [exception](exceptions "cpp/language/exceptions") (this usually requires it to be explicitly declared `noexcept(false)`) (since C++11), however if this destructor happens to be called during [stack unwinding](throw#Stack_unwinding "cpp/language/throw"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called instead. Although `[std::uncaught\_exception](../error/uncaught_exception "cpp/error/uncaught exception")` may sometimes be used to detect stack unwinding in progress, it is generally considered bad practice to allow any destructor to terminate by throwing an exception. This functionality is nevertheless used by some libraries, such as [SOCI](https://github.com/SOCI/soci) and [Galera 3](http://galeracluster.com/downloads/), which rely on the ability of the destructors of nameless temporaries to throw exceptions at the end of the full expression that constructs the temporary. [`std::experimental::scope_success`](https://en.cppreference.com/w/cpp/experimental/scope_success "cpp/experimental/scope success") in Library fundamental TS v3 may have [a potentially-throwing destructor](https://en.cppreference.com/w/cpp/experimental/scope_success/%7Escope_success "cpp/experimental/scope success/~scope success"), which throws an exception when the scope is exited normally and the exit function throws an exception. ### Example ``` #include <iostream> struct A { int i; A(int num) : i(num) { std::cout << "ctor a" << i << '\n'; } ~A() { std::cout << "dtor a" << i << '\n'; } }; A a0(0); int main() { A a1(1); A* p; { // nested scope A a2(2); p = new A(3); } // a2 out of scope delete p; // calls the destructor of a3 } ``` Output: ``` ctor a0 ctor a1 ctor a2 ctor a3 dtor a2 dtor a3 dtor a1 dtor a0 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 193](https://cplusplus.github.io/CWG/issues/193.html) | C++98 | whether automatic objects in a destructor aredestroyed before or after the destruction of theclass's base and member subobjects was unspecified | they are destroyedbefore destroyingthose subobjects | | [CWG 344](https://cplusplus.github.io/CWG/issues/344.html) | C++98 | the declarator syntax of destructor was defective (had thesame problem as [CWG issue 194](https://cplusplus.github.io/CWG/issues/194.html) and [CWG issue 263](https://cplusplus.github.io/CWG/issues/263.html) | changed the syntax to a specializedfunction declarator syntax | | [CWG 1241](https://cplusplus.github.io/CWG/issues/1241.html) | C++98 | static members might be destroyedright after destructor execution | only destroy non-static members | | [CWG 2180](https://cplusplus.github.io/CWG/issues/2180.html) | C++98 | a destructor for class `X` calls the destructorsfor X's virtual direct base classes | those destructors are not called | ### See also * [copy elision](copy_elision "cpp/language/copy elision") * [`new`](new "cpp/language/new") * [`delete`](delete "cpp/language/delete") cpp Value categories Value categories ================ Each C++ [expression](expressions "cpp/language/expressions") (an operator with its operands, a literal, a variable name, etc.) is characterized by two independent properties: a *[type](type "cpp/language/type")* and a *value category*. Each expression has some non-reference type, and each expression belongs to exactly one of the three primary value categories: *prvalue*, *xvalue*, and *lvalue*. * a glvalue (“generalized” lvalue) is an expression whose evaluation determines the identity of an object or function; * a prvalue (“pure” rvalue) is an expression whose evaluation * computes the value of an operand of a built-in operator (such prvalue has no *result object*), or * initializes an object (such prvalue is said to have a *result object*). The result object may be a variable, an object created by [new-expression](new "cpp/language/new"), a temporary created by [temporary materialization](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion"), or a member thereof. Note that non-`void` [discarded](expressions#Discarded-value_expressions "cpp/language/expressions") expressions have a result object (the materialized temporary). Also, every class and array prvalue has a result object except when it is the operand of [decltype](decltype "cpp/language/decltype"); * an xvalue (an “eXpiring” value) is a glvalue that denotes an object whose resources can be reused; * an lvalue (so-called, historically, because lvalues could appear on the left-hand side of an assignment expression) is a glvalue that is not an xvalue; * an rvalue (so-called, historically, because rvalues could appear on the right-hand side of an assignment expression) is a prvalue or an xvalue. Note: this taxonomy went through significant changes with past C++ standard revisions, see [History](#History) below for details. ### Primary categories #### lvalue The following expressions are *lvalue expressions*: * the name of a variable, a function, a [template parameter object](template_parameters#Non-type_template_parameter "cpp/language/template parameters") (since C++20), or a data member, regardless of type, such as `[std::cin](http://en.cppreference.com/w/cpp/io/cin)` or `[std::endl](http://en.cppreference.com/w/cpp/io/manip/endl)`. Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression; * a function call or an overloaded operator expression, whose return type is lvalue reference, such as `[std::getline](http://en.cppreference.com/w/cpp/string/basic_string/getline)([std::cin](http://en.cppreference.com/w/cpp/io/cin), str)`, `[std::cout](http://en.cppreference.com/w/cpp/io/cout) << 1`, `str1 = str2`, or `++it`; * `a = b`, `a += b`, `a %= b`, and all other built-in [assignment and compound assignment](operator_assignment "cpp/language/operator assignment") expressions; * `++a` and `--a`, the built-in [pre-increment and pre-decrement](operator_incdec#Built-in_prefix_operators "cpp/language/operator incdec") expressions; * `*p`, the built-in [indirection](operator_member_access#Built-in_indirection_operator "cpp/language/operator member access") expression; * `a[n]` and `p[n]`, the built-in [subscript](operator_member_access#Built-in_subscript_operator "cpp/language/operator member access") expressions, where one operand in `a[n]` is an array lvalue (since C++11); * `a.m`, the [member of object](operator_member_access#Built-in_member_access_operators "cpp/language/operator member access") expression, except where `m` is a member enumerator or a non-static member function, or where `a` is an rvalue and `m` is a non-static data member of object type; * `p->m`, the built-in [member of pointer](operator_member_access#Built-in_member_access_operators "cpp/language/operator member access") expression, except where `m` is a member enumerator or a non-static member function; * `a.*mp`, the [pointer to member of object](operator_member_access#Built-in_pointer-to-member_access_operators "cpp/language/operator member access") expression, where `a` is an lvalue and `mp` is a pointer to data member; * `p->*mp`, the built-in [pointer to member of pointer](operator_member_access#Built-in_pointer-to-member_access_operators "cpp/language/operator member access") expression, where `mp` is a pointer to data member; * `a, b`, the built-in [comma](operator_other#Built-in_comma_operator "cpp/language/operator other") expression, where `b` is an lvalue; * `a ? b : c`, the [ternary conditional](operator_other#Conditional_operator "cpp/language/operator other") expression for certain `b` and `c` (e.g., when both are lvalues of the same type, but see [definition](operator_other#Conditional_operator "cpp/language/operator other") for detail); * a [string literal](string_literal "cpp/language/string literal"), such as `"Hello, world!"`; * a cast expression to lvalue reference type, such as `static_cast<int&>(x)`; | | | | --- | --- | | * a function call or an overloaded operator expression, whose return type is rvalue reference to function; * a cast expression to rvalue reference to function type, such as `static_cast<void (&&)(int)>(x)`. | (since C++11) | Properties: * Same as glvalue (below). * Address of an lvalue may be taken by built-in address-of operator: `&++i`[[1]](#cite_note-1) and `&[std::endl](http://en.cppreference.com/w/cpp/io/manip/endl)` are valid expressions. * A modifiable lvalue may be used as the left-hand operand of the built-in assignment and compound assignment operators. * An lvalue may be used to [initialize an lvalue reference](reference_initialization "cpp/language/reference initialization"); this associates a new name with the object identified by the expression. #### prvalue The following expressions are *prvalue expressions*: * a [literal](expressions#Literals "cpp/language/expressions") (except for [string literal](string_literal "cpp/language/string literal")), such as `42`, `true` or `nullptr`; * a function call or an overloaded operator expression, whose return type is non-reference, such as `str.substr(1, 2)`, `str1 + str2`, or `it++`; * `a++` and `a--`, the built-in [post-increment and post-decrement](operator_incdec#Built-in_postfix_operators "cpp/language/operator incdec") expressions; * `a + b`, `a % b`, `a & b`, `a << b`, and all other built-in [arithmetic](operator_arithmetic "cpp/language/operator arithmetic") expressions; * `a && b`, `a || b`, `!a`, the built-in [logical](operator_logical "cpp/language/operator logical") expressions; * `a < b`, `a == b`, `a >= b`, and all other built-in [comparison](operator_comparison "cpp/language/operator comparison") expressions; * `&a`, the built-in [address-of](operator_member_access#Built-in_address-of_operator "cpp/language/operator member access") expression; * `a.m`, the [member of object](operator_member_access#Built-in_member_access_operators "cpp/language/operator member access") expression, where `m` is a member enumerator or a non-static member function[[2]](#cite_note-pmfc-2), or where `a` is an rvalue and `m` is a non-static data member of non-reference type (until C++11); * `p->m`, the built-in [member of pointer](operator_member_access#Built-in_member_access_operators "cpp/language/operator member access") expression, where `m` is a member enumerator or a non-static member function[[2]](#cite_note-pmfc-2); * `a.*mp`, the [pointer to member of object](operator_member_access#Built-in_pointer-to-member_access_operators "cpp/language/operator member access") expression, where `mp` is a pointer to member function[[2]](#cite_note-pmfc-2), or where `a` is an rvalue and `mp` is a pointer to data member (until C++11); * `p->*mp`, the built-in [pointer to member of pointer](operator_member_access#Built-in_pointer-to-member_access_operators "cpp/language/operator member access") expression, where `mp` is a pointer to member function[[2]](#cite_note-pmfc-2); * `a, b`, the built-in [comma](operator_other#Built-in_comma_operator "cpp/language/operator other") expression, where `b` is an rvalue; * `a ? b : c`, the [ternary conditional](operator_other#Conditional_operator "cpp/language/operator other") expression for certain `b` and `c` (see [definition](operator_other#Conditional_operator "cpp/language/operator other") for detail); * a cast expression to non-reference type, such as `static_cast<double>(x)`, `[std::string](http://en.cppreference.com/w/cpp/string/basic_string){}`, or `(int)42`; * the [`this`](this "cpp/language/this") pointer; * an [enumerator](enum "cpp/language/enum"); * non-type [template parameter](template_parameters "cpp/language/template parameters") unless its type is a class or (since C++20) an lvalue reference type; | | | | --- | --- | | * a [lambda expression](lambda "cpp/language/lambda"), such as `[](int x){ return x * x; }`; | (since C++11) | | * a [requires-expression](constraints "cpp/language/constraints"), such as `requires (T i) { typename T::type; }`; * a specialization of a [concept](constraints "cpp/language/constraints"), such as `[std::equality\_comparable](http://en.cppreference.com/w/cpp/concepts/equality_comparable)<int>`. | (since C++20) | Properties: * Same as rvalue (below). * A prvalue cannot be [polymorphic](object#Polymorphic_objects "cpp/language/object"): the [dynamic type](type#Dynamic_type "cpp/language/type") of the object it denotes is always the type of the expression. * A non-class non-array prvalue cannot be [cv-qualified](cv "cpp/language/cv"), unless it is [materialized](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion") in order to be [bound to a reference](reference_initialization "cpp/language/reference initialization") to a cv-qualified type (since C++17). (Note: a function call or cast expression may result in a prvalue of non-class cv-qualified type, but the cv-qualifier is generally immediately stripped out.) * A prvalue cannot have [incomplete type](type#Incomplete_type "cpp/language/type") (except for type `void`, see below, or when used in [`decltype` specifier](decltype "cpp/language/decltype")) * A prvalue cannot have [abstract class type](abstract_class "cpp/language/abstract class") or an array thereof. #### xvalue The following expressions are *xvalue expressions*: * a function call or an overloaded operator expression, whose return type is rvalue reference to object, such as `std::move(x)`; * `a[n]`, the built-in [subscript](operator_member_access#Built-in_subscript_operator "cpp/language/operator member access") expression, where one operand is an array rvalue; * `a.m`, the [member of object](operator_member_access#Built-in_member_access_operators "cpp/language/operator member access") expression, where `a` is an rvalue and `m` is a non-static data member of non-reference type; * `a.*mp`, the [pointer to member of object](operator_member_access#Built-in_pointer-to-member_access_operators "cpp/language/operator member access") expression, where `a` is an rvalue and `mp` is a pointer to data member; * `a ? b : c`, the [ternary conditional](operator_other#Conditional_operator "cpp/language/operator other") expression for certain `b` and `c` (see [definition](operator_other#Conditional_operator "cpp/language/operator other") for detail); * a cast expression to rvalue reference to object type, such as `static_cast<char&&>(x)`; | | | | --- | --- | | * any expression that designates a temporary object, after [temporary materialization](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion"). | (since C++17) | Properties: * Same as rvalue (below). * Same as glvalue (below). In particular, like all rvalues, xvalues bind to rvalue references, and like all glvalues, xvalues may be [polymorphic](object#Polymorphic_objects "cpp/language/object"), and non-class xvalues may be [cv-qualified](cv "cpp/language/cv"). ### Mixed categories #### glvalue A *glvalue expression* is either lvalue or xvalue. Properties: * A glvalue may be implicitly converted to a prvalue with lvalue-to-rvalue, array-to-pointer, or function-to-pointer [implicit conversion](implicit_conversion "cpp/language/implicit conversion"). * A glvalue may be [polymorphic](object#Polymorphic_objects "cpp/language/object"): the [dynamic type](type#Dynamic_type "cpp/language/type") of the object it identifies is not necessarily the static type of the expression. * A glvalue can have [incomplete type](type#Incomplete_type "cpp/language/type"), where permitted by the expression. #### rvalue An *rvalue expression* is either prvalue or xvalue. Properties: * Address of an rvalue cannot be taken by built-in address-of operator: `&int()`, `&i++`[[3]](#cite_note-3), `&42`, and `&std::move(x)` are invalid. * An rvalue can't be used as the left-hand operand of the built-in assignment or compound assignment operators. * An rvalue may be used to [initialize a const lvalue reference](reference_initialization "cpp/language/reference initialization"), in which case the lifetime of the object identified by the rvalue is [extended](reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization") until the scope of the reference ends. | | | | --- | --- | | * An rvalue may be used to [initialize an rvalue reference](reference_initialization "cpp/language/reference initialization"), in which case the lifetime of the object identified by the rvalue is [extended](reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization") until the scope of the reference ends. * When used as a function argument and when [two overloads](overload_resolution "cpp/language/overload resolution") of the function are available, one taking rvalue reference parameter and the other taking lvalue reference to const parameter, an rvalue binds to the rvalue reference overload (thus, if both copy and move constructors are available, an rvalue argument invokes the [move constructor](move_constructor "cpp/language/move constructor"), and likewise with copy and move assignment operators). | (since C++11) | ### Special categories #### Pending member function call The expressions `a.mf` and `p->mf`, where `mf` is a [non-static member function](member_functions "cpp/language/member functions"), and the expressions `a.*pmf` and `p->*pmf`, where `pmf` is a [pointer to member function](pointer#Pointers_to_member_functions "cpp/language/pointer"), are classified as prvalue expressions, but they cannot be used to initialize references, as function arguments, or for any purpose at all, except as the left-hand argument of the function call operator, e.g. `(p->*pmf)(args)`. #### Void expressions Function call expressions returning `void`, cast expressions to `void`, and [throw-expressions](throw "cpp/language/throw") are classified as prvalue expressions, but they cannot be used to initialize references or as function arguments. They can be used in discarded-value contexts (e.g. on a line of its own, as the left-hand operand of the comma operator, etc.) and in the `return` statement in a function returning `void`. In addition, throw-expressions may be used as the second and the third operands of the [conditional operator ?:](operator_other "cpp/language/operator other"). | | | | --- | --- | | Void expressions have no *result object*. | (since C++17) | #### Bit fields An expression that designates a [bit field](bit_field "cpp/language/bit field") (e.g. `a.m`, where `a` is an lvalue of type `struct A { int m: 3; }`) is a glvalue expression: it may be used as the left-hand operand of the assignment operator, but its address cannot be taken and a non-const lvalue reference cannot be bound to it. A const lvalue reference or rvalue reference can be initialized from a bit-field glvalue, but a temporary copy of the bit-field will be made: it won't bind to the bit field directly. ### History #### CPL The programming language [CPL](https://en.wikipedia.org/wiki/CPL_(programming_language) "enwiki:CPL (programming language)") was first to introduce value categories for expressions: all CPL expressions can be evaluated in "right-hand mode", but only certain kinds of expression are meaningful in "left-hand mode". When evaluated in right-hand mode, an expression is regarded as being a rule for the computation of a value (the right-hand value, or *rvalue*). When evaluated in left-hand mode an expression effectively gives an address (the left-hand value, or *lvalue*). "Left" and "Right" here stood for "left of assignment" and "right of assignment". #### C The C programming language followed a similar taxonomy, except that the role of assignment was no longer significant: C expressions are categorized between "lvalue expressions" and others (functions and non-object values), where "lvalue" means an expression that identifies an object, a "locator value"[[4]](#cite_note-4). #### C++98 Pre-2011 C++ followed the C model, but restored the name "rvalue" to non-lvalue expressions, made functions into lvalues, and added the rule that references can bind to lvalues, but only references to const can bind to rvalues. Several non-lvalue C expressions became lvalue expressions in C++. #### C++11 With the introduction of move semantics in C++11, value categories were redefined to characterize two independent properties of expressions[[5]](#cite_note-5): * *has identity*: it's possible to determine whether the expression refers to the same entity as another expression, such as by comparing addresses of the objects or the functions they identify (obtained directly or indirectly); * *can be moved from*: [move constructor](move_constructor "cpp/language/move constructor"), [move assignment operator](move_assignment "cpp/language/move assignment"), or another function overload that implements move semantics can bind to the expression. In C++11, expressions that: * have identity and cannot be moved from are called *lvalue* expressions; * have identity and can be moved from are called *xvalue* expressions; * do not have identity and can be moved from are called *prvalue* ("pure rvalue") expressions; * do not have identity and cannot be moved from are not used[[6]](#cite_note-6). The expressions that have identity are called "glvalue expressions" (glvalue stands for "generalized lvalue"). Both lvalues and xvalues are glvalue expressions. The expressions that can be moved from are called "rvalue expressions". Both prvalues and xvalues are rvalue expressions. #### C++17 In C++17, [copy elision](copy_elision "cpp/language/copy elision") was made mandatory in some situations, and that required separation of prvalue expressions from the temporary objects initialized by them, resulting in the system we have today. Note that, in contrast with the C++11 scheme, prvalues are no longer moved from. ### Footnotes 1. Assuming `i` has built-in type or the pre-increment operator is [overloaded](operators "cpp/language/operators") to return by lvalue reference. 2. Special rvalue category, see [pending member function call](#Pending_member_function_call). 3. Assuming `i` has built-in type or the postincrement operator is not [overloaded](operators "cpp/language/operators") to return by lvalue reference. 4. "A difference of opinion within the C community centered around the meaning of lvalue, one group considering an lvalue to be any kind of object locator, another group holding that an lvalue is meaningful on the left side of an assigning operator. The C89 Committee adopted the definition of lvalue as an object locator." -- ANSI C Rationale, 6.3.2.1/10. 5. ["New" Value Terminology](http://www.stroustrup.com/terminology.pdf) by Bjarne Stroustrup, 2010. 6. const prvalues (only allowed for class types) and const xvalues do not bind to T&& overloads, but they bind to the const T&& overloads, which are also classified as "move constructor" and "move assignment operator" by the standard, satisfying the definition of "can be moved from" for the purpose of this classification. However, such overloads cannot modify their arguments and are not used in practice; in their absence const prvalues and const xvalues bind to const T& overloads. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 616](https://cplusplus.github.io/CWG/issues/616.html) | C++11 | member access and member access throughpointer to member of an rvalue resulted in prvalue | reclassified as xvalue | | [CWG 1059](https://cplusplus.github.io/CWG/issues/1059.html) | C++11 | array prvalues could not be cv-qualified | allowed | | [CWG 1213](https://cplusplus.github.io/CWG/issues/1213.html) | C++11 | subscripting an array rvalue resulted in lvalue | reclassified as xvalue | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/value_category "c/language/value category") for value categories | ### External links * David Mazières, 2021 - [C++ value categories and decltype demystified](https://www.scs.stanford.edu/~dm/blog/decltype.html)
programming_docs
cpp Logical operators Logical operators ================= Returns the result of a boolean operation. | Operator name | Syntax | [Over​load​able](operators "cpp/language/operators") | Prototype examples (for `class T`) | | --- | --- | --- | --- | | Inside class definition | Outside class definition | | negation | `not a` `!a`. | Yes | `bool T::operator!() const;` | `bool operator!(const T &a);` | | AND | `a and b` `a && b`. | Yes | `bool T::operator&&(const T2 &b) const;` | `bool operator&&(const T &a, const T2 &b);` | | inclusive OR | `a or b` `a || b`. | Yes | `bool T::operator||(const T2 &b) const;` | `bool operator||(const T &a, const T2 &b);` | | **Notes*** The keyword-like forms (`and`,`or`,`not`) and the symbol-like forms (`&&`,`||`,`!`) can be used interchangeably (See [alternative representations](operator_alternative "cpp/language/operator alternative")) * All built-in operators return `bool`, and most [user-defined overloads](operators "cpp/language/operators") also return `bool` so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including `void`). * Builtin operators `&&` and `||` perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like regular function calls and always evaluate both operands | ### Explanation The logic operator expressions have the form. | | | | | --- | --- | --- | | `!` rhs | (1) | | | lhs `&&` rhs | (2) | | | lhs `||` rhs | (3) | | 1) Logical NOT 2) Logical AND 3) Logical inclusive OR If the operand is not `bool`, it is converted to `bool` using [contextual conversion to bool](implicit_conversion "cpp/language/implicit conversion"): it is only well-formed if the declaration `bool t(arg)` is well-formed, for some invented temporary `t`. The result is a `bool` prvalue. For the built-in logical NOT operator, the result is `true` if the operand is `false`. Otherwise, the result is `false`. For the built-in logical AND operator, the result is `true` if both operands are `true`. Otherwise, the result is `false`. This operator is [short-circuiting](https://en.wikipedia.org/wiki/Short-circuit_evaluation "enwiki:Short-circuit evaluation"): if the first operand is `false`, the second operand is not evaluated. For the built-in logical OR operator, the result is `true` if either the first or the second operand (or both) is `true`. This operator is short-circuiting: if the first operand is `true`, the second operand is not evaluated. Note that [bitwise logic operators](operator_arithmetic "cpp/language/operator arithmetic") do not perform short-circuiting. ### Results | | | | | --- | --- | --- | | `a` | `true` | `false` | | `!a` | `false` | `true` | | `and` | `a` | | --- | --- | | `true` | `false` | | `b` | `true` | `true` | `false` | | `false` | `false` | `false` | | `or` | `a` | | --- | --- | | `true` | `false` | | `b` | `true` | `true` | `true` | | `false` | `true` | `false` | In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), the following built-in function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` bool operator!(bool) ``` | | | | ``` bool operator&&(bool, bool) ``` | | | | ``` bool operator||(bool, bool) ``` | | | ### Example ``` #include <iostream> #include <sstream> #include <string> int main() { int n = 2; int* p = &n; // pointers are convertible to bool if( p && *p == 2 // "*p" is safe to use after "p &&" || !p && n != 2 ) // || has lower precedence than && std::cout << "true\n"; // streams are also convertible to bool std::stringstream cin; cin << "3...\n" << "2...\n" << "1...\n" << "quit"; std::cout << "Enter 'quit' to quit.\n"; for(std::string line; std::cout << "> " && std::getline(cin, line) && line != "quit"; ) std::cout << line << '\n'; } ``` Output: ``` true Enter 'quit' to quit. > 3... > 2... > 1... > ``` ### Standard library Because the short-circuiting properties of `operator&&` and `operator||` do not apply to overloads, and because types with boolean semantics are uncommon, only two standard library classes overload these operators: | | | | --- | --- | | [operator!](../numeric/valarray/operator_arith "cpp/numeric/valarray/operator arith") | applies a unary arithmetic operator to each element of the valarray (public member function of `std::valarray<T>`) | | [operator&&operator||](../numeric/valarray/operator_arith3 "cpp/numeric/valarray/operator arith3") | applies binary operators to each element of two valarrays, or a valarray and a value (function template) | | [operator!](../io/basic_ios/operator- "cpp/io/basic ios/operator!") | checks if an error has occurred (synonym of `[fail()](../io/basic_ios/fail "cpp/io/basic ios/fail")`) (public member function of `std::basic_ios<CharT,Traits>`) | ### See also [Operator precedence](operator_precedence "cpp/language/operator precedence"). [Operator overloading](operators "cpp/language/operators"). | Common operators | | --- | | [assignment](operator_assignment "cpp/language/operator assignment") | [incrementdecrement](operator_incdec "cpp/language/operator incdec") | [arithmetic](operator_arithmetic "cpp/language/operator arithmetic") | **logical** | [comparison](operator_comparison "cpp/language/operator comparison") | [memberaccess](operator_member_access "cpp/language/operator member access") | [other](operator_other "cpp/language/operator other") | | `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b a <=> b`. | `a[b] *a &a a->b a.b a->*b a.*b`. | `a(...) a, b a ? b : c`. | | Special operators | | [`static_cast`](static_cast "cpp/language/static cast") converts one type to another related type [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") converts within inheritance hierarchies [`const_cast`](const_cast "cpp/language/const cast") adds or removes [cv](cv "cpp/language/cv") qualifiers [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") converts type to unrelated type [C-style cast](explicit_cast "cpp/language/explicit cast") converts one type to another by a mix of `static_cast`, `const_cast`, and `reinterpret_cast` [`new`](new "cpp/language/new") creates objects with dynamic storage duration [`delete`](delete "cpp/language/delete") destructs objects previously created by the new expression and releases obtained memory area [`sizeof`](sizeof "cpp/language/sizeof") queries the size of a type [`sizeof...`](sizeof... "cpp/language/sizeof...") queries the size of a [parameter pack](parameter_pack "cpp/language/parameter pack") (since C++11) [`typeid`](typeid "cpp/language/typeid") queries the type information of a type [`noexcept`](noexcept "cpp/language/noexcept") checks if an expression can throw an exception (since C++11) [`alignof`](alignof "cpp/language/alignof") queries alignment requirements of a type (since C++11). | | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/operator_logical "c/language/operator logical") for Logical operators | cpp Overload resolution Overload resolution =================== In order to compile a function call, the compiler must first perform [name lookup](lookup "cpp/language/lookup"), which, for functions, may involve [argument-dependent lookup](adl "cpp/language/adl"), and for function templates may be followed by [template argument deduction](template_argument_deduction "cpp/language/template argument deduction"). If these steps produce more than one *candidate function*, then *overload resolution* is performed to select the function that will actually be called. In general, the candidate function whose parameters match the arguments most closely is the one that is called. For other contexts where overloaded function names can appear, see [Address of an overloaded function](overloaded_address "cpp/language/overloaded address"). If a function cannot be selected by overload resolution (e.g. it is a [templated entity](templates#Templated_entity "cpp/language/templates") with a failed [constraint](constraints "cpp/language/constraints")), it cannot be named or otherwise used. ### Details Before overload resolution begins, the functions selected by name lookup and template argument deduction are combined to form the set of *candidate functions* (the exact criteria depend on the context in which overload resolution takes place, see below). For function templates, [template argument deduction](template_argument_deduction "cpp/language/template argument deduction") and checking of any explicit template arguments are performed to find the template argument values (if any) that can be used in this case: * if both succeeds, the template arguments are used to synthesize declarations of the corresponding function template specializations, which are added to the candidate set, and such specializations are treated just like non-template functions except where specified otherwise in the tie-breaker rules; * if argument deduction fails or the synthesized function template specialization would be ill-formed, no such function is added to the candidate set. If a name refers to one or more function templates and also to a set of overloaded non-template functions, those functions and the specializations generated from the templates are all candidates. | | | | --- | --- | | If a constructor template or conversion function template has a [conditional explicit specifier](explicit "cpp/language/explicit") which happens to be [value-dependent](dependent_name#Value-dependent_expressions "cpp/language/dependent name"), after deduction, if the context requires a candidate that is not explicit and the generated specialization is explicit, it is removed from the candidate set. | (since C++20) | | | | | --- | --- | | Defaulted [move constructor](move_constructor "cpp/language/move constructor") and [move assignment](move_assignment "cpp/language/move assignment") that are defined as deleted are never included in the list of candidate functions. | (since C++11) | Inherited copy and move constructors are not included in the list of candidate functions when constructing a derived class object. #### Implicit object parameter If any candidate function is a [member function](member_functions "cpp/language/member functions") (static or non-static) that does not have an [explicit object parameter](member_functions#Explicit_object_parameter "cpp/language/member functions") (since C++23), but not a constructor, it is treated as if it has an extra parameter (*implicit object parameter*) which represents the object for which they are called and appears before the first of the actual parameters. Similarly, the object on which a member function is being called is prepended to the argument list as the *implied object argument*. For member functions of class `X`, the type of the implicit object parameter is affected by cv-qualifications and ref-qualifications of the member function as described in [member functions](member_functions "cpp/language/member functions"). The user-defined conversion functions are considered to be members of the *implied object argument* for the purpose of determining the type of the *implicit object parameter*. The member functions introduced by a using-declaration into a derived class are considered to be members of the derived class for the purpose of defining the type of the *implicit* object parameter*.* For the static member functions, the *implicit object parameter* is considered to match any object: its type is not examined and no conversion sequence is attempted for it. For the rest of overload resolution, the *implied object argument* is indistinguishable from other arguments, but the following special rules apply to the *implicit object parameter*: 1) user-defined conversions cannot be applied to the implicit object parameter 2) rvalues can be bound to non-const implicit object parameter (unless this is for a ref-qualified member function) (since C++11) and do not affect the ranking of the implicit conversions. ``` struct B { void f(int); }; struct A { operator B&(); }; A a; a.B::f(1); // Error: user-defined conversions cannot be applied // to the implicit object parameter static_cast<B&>(a).f(1); // OK ``` ### Candidate functions The set of candidate functions and the list of arguments is prepared in a unique way for each of the contexts where overload resolution is used: #### Call to a named function If `E` in a [function call expression](operator_other#Built-in_function_call_operator "cpp/language/operator other") `E(args)` names a set of overloaded functions and/or function templates (but not callable objects), the following rules are followed: * If the expression `E` has the form `PA->B` or `A.B` (where A has class type cv T), then `B` is [looked up](lookup "cpp/language/lookup") as a member function of `T`. The function declarations found by that lookup are the candidate functions. The argument list for the purpose of overload resolution has the implied object argument of type cv T. * If the expression `E` is a [primary expression](expressions#Primary_expressions "cpp/language/expressions"), the name is [looked up](lookup "cpp/language/lookup") following normal rules for function calls (which may involve [ADL](adl "cpp/language/adl")). The function declarations found by this lookup are (due to the way lookup works) either: a) all non-member functions (in which case the argument list for the purpose of overload resolution is exactly the argument list used in the function call expression) b) all member functions of some class `T`, in which case, if [this](this "cpp/language/this") is in scope and is a pointer to `T` or to a derived class of `T`, `*this` is used as the implied object argument. Otherwise (if `this` is not in scope or does not point to `T`), a fake object of type `T` is used as the implied object argument, and if overload resolution subsequently selects a non-static member function, the program is ill-formed. #### Call to a class object If `E` in a [function call expression](operator_other#Built-in_function_call_operator "cpp/language/operator other") `E(args)` has class type cv `T`, then. * The function-call operators of T are obtained by ordinary [lookup](lookup "cpp/language/lookup") of the name `operator()` in the context of the expression `(E).operator()`, and every declaration found is added to the set of candidate functions. * For each non-explicit [user-defined conversion function](cast_operator "cpp/language/cast operator") in `T` or in a base of `T` (unless hidden), whose cv-qualifiers are the same or greater than `T`'s cv-qualifiers, and where the conversion function converts to: * pointer-to-function * reference-to-pointer-to-function * reference-to-function then a *surrogate call function* with a unique name whose first parameter is the result of the conversion, the remaining parameters are the parameter-list accepted by the result of the conversion, and the return type is the return type of the result of the conversion, is added to the set of candidate functions. If this surrogate function is selected by the subsequent overload resolution, then the user-defined conversion function will be called and then the result of the conversion will be called. In any case, the argument list for the purpose of overload resolution is the argument list of the function call expression preceded by the implied object argument `E` (when matching against the surrogate function, the user-defined conversion will automatically convert the implied object argument to the first argument of the surrogate function). ``` int f1(int); int f2(float); struct A { using fp1 = int(*)(int); operator fp1() { return f1; } // conversion function to pointer to function using fp2 = int(*)(float); operator fp2() { return f2; } // conversion function to pointer to function } a; int i = a(1); // calls f1 via pointer returned from conversion function ``` #### Call to an overloaded operator If at least one of the arguments to an operator in an expression has a class type or an enumeration type, both [builtin operators](expressions#Operators "cpp/language/expressions") and [user-defined operator overloads](operators "cpp/language/operators") participate in overload resolution, with the set of candidate functions selected as follows: For a unary operator `@` whose argument has type `T1` (after removing cv-qualifications), or binary operator `@` whose left operand has type `T1` and right operand of type `T2` (after removing cv-qualifications), the following sets of candidate functions are prepared: 1) *member candidates*: if `T1` is a complete class or a class currently being defined, the set of member candidates is the result of [qualified name lookup](lookup "cpp/language/lookup") of `T1::operator@`. In all other cases, the set of member candidates is empty. 2) *non-member candidates*: For the operators where [operator overloading](operators "cpp/language/operators") permits non-member forms, all declarations found by [unqualified name lookup](lookup "cpp/language/lookup") of `operator@` in the context of the expression (which may involve [ADL](adl "cpp/language/adl")), except that member function declarations are ignored and do not prevent the lookup from continuing into the next enclosing scope. If both operands of a binary operator or the only operand of a unary operator has enumeration type, the only functions from the lookup set that become non-member candidates are the ones whose parameter has that enumeration type (or reference to that enumeration type) 3) *built-in candidates*: For `operator,`, the unary `operator&`, and the `operator->`, the set of built-in candidates is empty. For other operators built-in candidates are the ones listed in [built-in operator pages](expressions#Operators "cpp/language/expressions") as long as all operands can be implicitly converted to their parameters. If any built-in candidate has the same parameter list as a non-member candidate that isn't a function template specialization, it is not added to the list of built-in candidates. When the built-in assignment operators are considered, the conversions from their left-hand arguments are restricted: user-defined conversions are not considered. | | | | --- | --- | | 4) *rewritten candidates*: * For the four relational operator expressions `x<y`, `x<=y`, `x>y`, and `x>=y`, all member, non-member, and built-in `operator<=>`'s found are added to the set. * For the four relational operator expressions `x<y`, `x<=y`, `x>y`, and `x>=y` as well as the three-way comparison expression `x<=>y`, a synthesized candidate with the order of the two parameters reversed is added for each member, non-member, and built-in `operator<=>`'s found. * For `x!=y`, all member, non-member, and built-in `operator==`'s found are added to the set, unless there's a matching `operator!=`. * For equality operator expressions `x==y` and `x!=y`, a synthesized candidate with the order of the two parameters reversed is added for each member, non-member, and built-in `operator==`'s found, unless there's a matching `operator!=`. In all cases, rewritten candidates are not considered in the context of the rewritten expression. For all other operators, the rewritten candidate set is empty. | (since C++20) | The set of candidate functions to be submitted for overload resolution is a union of the sets above. The argument list for the purpose of overload resolution consists of the operands of the operator except for `operator->`, where the second operand is not an argument for the function call (see [member access operator](operator_member_access#Built-in_member_access_operators "cpp/language/operator member access")). ``` struct A { operator int(); // user-defined conversion }; A operator+(const A&, const A&); // non-member user-defined operator void m() { A a, b; a + b; // member-candidates: none // non-member candidates: operator+(a, b) // built-in candidates: int(a) + int(b) // overload resolution chooses operator+(a, b) } ``` If the overload resolution selects a built-in candidate, the [user-defined conversion sequence](implicit_cast "cpp/language/implicit cast") from an operand of class type is not allowed to have a second standard conversion sequence: the user-defined conversion function must give the expected operand type directly: ``` struct Y { operator int*(); }; // Y is convertible to int* int *a = Y() + 100.0; // error: no operator+ between pointer and double ``` For `operator,`, the unary `operator&`, and `operator->`, if there are no viable functions (see below) in the set of candidate functions, then the operator is reinterpreted as a built-in. | | | | --- | --- | | If a rewritten `operator<=>` candidate is selected by overload resolution for an operator `@`, `x @ y` is interpreted as the rewritten expression: `0 @ (y <=> x)` if the selected candidate is a synthesized candidate with reversed order of parameters, or `(x <=> y) @ 0` otherwise, using the selected rewritten `operator<=>` candidate. If a rewritten `operator==` candidate is selected by overload resolution for an operator `@` (which is either `==` or `!=`), its return type must be (possibly cv-qualified) `bool`, and `x @ y` is interpreted as the rewritten expression: `y == x` or `!(y == x)` if the selected candidate is a synthesized candidate with reversed order of parameters, or `!(x == y)` otherwise, using the selected rewritten `operator==` candidate. Overload resolution in this case has a final tiebreaker preferring non-rewritten candidates to rewritten candidates, and preferring non-synthesized rewritten candidates to synthesized rewritten candidates. This lookup with the reversed arguments order makes it possible to write just `operator<=>([std::string](http://en.cppreference.com/w/cpp/string/basic_string), const char\*)` and `operator==([std::string](http://en.cppreference.com/w/cpp/string/basic_string), const char\*)` to generate all comparisons between `[std::string](http://en.cppreference.com/w/cpp/string/basic_string)` and `const char*`, both ways. See [default comparisons](default_comparisons "cpp/language/default comparisons") for more detail. | (since C++20) | #### Initialization by constructor When an object of class type is [direct-initialized](direct_initialization "cpp/language/direct initialization") or [default-initialized](default_initialization "cpp/language/default initialization") outside a [copy-initialization](copy_initialization "cpp/language/copy initialization") context, the candidate functions are all constructors of the class being initialized. The argument list is the expression list of the initializer. When an object of class type is copy-initialized from an object of the same or derived class type, or default-initialized in a copy-initialization context, the candidate functions are all [converting constructors](converting_constructor "cpp/language/converting constructor") of the class being initialized. The argument list is the expression of the initializer. #### Copy-initialization by conversion If [copy-initialization](copy_initialization "cpp/language/copy initialization") of an object of class type requires that a user-defined conversion is called to convert the initializer expression of type cv `S` to the type cv `T` of the object being initialized, the following functions are candidate functions: * all [converting constructors](converting_constructor "cpp/language/converting constructor") of `T` * the non-explicit conversion functions from `S` and its base classes (unless hidden) to `T` or class derived from `T` or a reference to such. If this copy-initialization is part of the direct-initialization sequence of *cv* `T` (initializing a reference to be bound to the first parameter of a constructor that takes a reference to cv `T`), then explicit conversion functions are also considered. Either way, the argument list for the purpose of overload resolution consists of a single argument which is the initializer expression, which will be compared against the first argument of the constructor or against the implicit object argument of the conversion function. #### Non-class initialization by conversion When initialization of an object of non-class type cv1 `T` requires a [user-defined conversion function](cast_operator "cpp/language/cast operator") to convert from an initializer expression of class type cv `S`, the following functions are candidates: * the non-explicit user-defined conversion functions of `S` and its base classes (unless hidden) that produce type `T` or a type convertible to `T` by a [standard conversion sequence](implicit_cast "cpp/language/implicit cast"), or a reference to such type. cv qualifiers on the returned type are ignored for the purpose of selecting candidate functions. * if this is [direct-initialization](direct_initialization "cpp/language/direct initialization"), the explicit user-defined conversion functions of `S` and its base classes (unless hidden) that produce type `T` or a type convertible to `T` by a [qualification conversion](implicit_cast "cpp/language/implicit cast"), or a reference to such type, are also considered. Either way, the argument list for the purpose of overload resolution consists of a single argument which is the initializer expression, which will be compared against the implicit object argument of the conversion function. #### Reference initialization by conversion During [reference initialization](reference_initialization "cpp/language/reference initialization"), where the reference to cv1 `T` is bound to the lvalue or rvalue result of a conversion from the initializer expression from the class type cv2 `S`, the following functions are selected for the candidate set: * the non-explicit user-defined conversion functions of `S` and its base classes (unless hidden) to the type * (when initializing lvalue reference or rvalue reference to function) lvalue reference to cv2 `T2` * (when initializing rvalue reference or lvalue reference to function) cv2 `T2` or rvalue reference to cv2 `T2` where cv2 T2 is reference-compatible with cv1 T * for direct initializaton, the explicit user-defined conversion functions are also considered if T2 is the same type as T or can be converted to type T with a qualification conversion. Either way, the argument list for the purpose of overload resolution consists of a single argument which is the initializer expression, which will be compared against the implicit object argument of the conversion function. #### List-initialization When an object of non-aggregate class type `T` is [list-initialized](list_initialization "cpp/language/list initialization"), two-phase overload resolution takes place. * at phase 1, the candidate functions are all initializer-list constructors of `T` and the argument list for the purpose of overload resolution consists of a single initializer list argument * if overload resolution fails at phase 1, phase 2 is entered, where the candidate functions are all constructors of `T` and the argument list for the purpose of overload resolution consists of the individual elements of the initializer list. If the initializer list is empty and `T` has a default constructor, phase 1 is skipped. In copy-list-initialization, if phase 2 selects an explicit constructor, the initialization is ill-formed (as opposed to all over copy-initializations where explicit constructors are not even considered). ### Viable functions Given the set of candidate functions, constructed as described above, the next step of overload resolution is examining arguments and parameters to reduce the set to the set of *viable functions*. To be included in the set of viable functions, the candidate function must satisfy the following: 1) If there are `M` arguments, the candidate function that has exactly `M` parameters is viable 2) If the candidate function has less than `M` parameters, but has an [ellipsis parameter](variadic_arguments "cpp/language/variadic arguments"), it is viable. 3) If the candidate function has more than `M` parameters and the `M+1`'st parameter and all parameters that follow have default arguments, it is viable. For the rest of overload resolution, the parameter list is truncated at M. | | | | --- | --- | | 4) If the function has an associated [constraint](constraints "cpp/language/constraints"), it must be satisfied | (since C++20) | 5) For every argument there must be at least one implicit conversion sequence that converts it to the corresponding parameter. 6) If any parameter has reference type, reference binding is accounted for at this step: if an rvalue argument corresponds to non-const lvalue reference parameter or an lvalue argument corresponds to rvalue reference parameter, the function is not viable. User-defined conversions (both converting constructors and user-defined conversion functions) are prohibited from taking part in implicit conversion sequence where it would make it possible to apply more than one user-defined conversion. Specifically, they are not considered if the target of the conversion is the first parameter of a constructor or the implicit object parameter of a user-defined conversion function, and that constructor/user-defined conversion is a candidate for. * [copy-initialization of a class by user-defined conversion](#Copy-initialization_by_conversion), * [initialization of a non-class type by a conversion function](#Non-class_initialization_by_conversion), * [initialization by conversion function for direct reference binding](#Reference_initialization_by_conversion), * [initialization by constructor](#Initialization_by_constructor) during the second (direct-initialization) step of class [copy-initialization](copy_initialization "cpp/language/copy initialization"), * initialization by list-initialization where the initializer list has exactly one element that is itself an initializer list, and the target is the first parameter of a constructor of class X, and the conversion is to X or reference to (possibly cv-qualified) X ``` struct A { A(int); }; struct B { B(A); }; B b{ {0} }; // list-init of B // candidates: B(const B&), B(B&&), B(A) // {0} -> B&& not viable: would have to call B(A) // {0} -> const B&: not viable: would have to bind to rvalue, would have to call B(A) // {0} -> A viable. Calls A(int): user-defined conversion to A is not banned ``` ### Best viable function For each pair of viable function `F1` and `F2`, the implicit conversion sequences from the `i`-th argument to `i`-th parameter are ranked to determine which one is better (except the first argument, the *implicit object argument* for static member functions has no effect on the ranking). `F1` is determined to be a better function than `F2` if implicit conversions for all arguments of F1 are *not worse* than the implicit conversions for all arguments of F2, and. 1) there is at least one argument of F1 whose implicit conversion is *better* than the corresponding implicit conversion for that argument of F2 2) or, if not that, (only in context of non-class initialization by conversion), the standard conversion sequence from the return type of F1 to the type being initialized is *better* than the standard conversion sequence from the return type of F2 | | | | --- | --- | | 3) or, if not that, (only in context of initialization by conversion function for direct reference binding of a reference to function type), the return type of F1 is the same kind of reference (lvalue or rvalue) as the reference being initialized, and the return type of F2 is not | (since C++11) | 4) or, if not that, F1 is a non-template function while F2 is a template specialization 5) or, if not that, F1 and F2 are both template specializations and F1 is *more specialized* according to the [partial ordering rules for template specializations](function_template#Function_template_overloading "cpp/language/function template") | | | | --- | --- | | 6) or, if not that, F1 and F2 are non-template functions with the same parameter-type-lists, and F1 is more constrained than F2 according to the [partial ordering of constraints](constraints "cpp/language/constraints") | (since C++20) | | | | | --- | --- | | 7) or, if not that, F1 is a constructor for a class D, F2 is a constructor for a base class B of D, and for all arguments the corresponding parameters of F1 and F2 have the same type: ``` struct A { A(int = 0); }; struct B: A { using A::A; B(); }; B b; // OK, B::B() ``` | (since C++11) | | | | | --- | --- | | 8) or, if not that, F2 is a rewritten candidate and F1 is not, 9) or, if not that, F1 and F2 are both rewritten candidates, and F2 is a synthesized rewritten candidate with reversed order of parameters and F1 is not, | (since C++20) | | | | | --- | --- | | 10) or, if not that, F1 is generated from a [user-defined deduction-guide](deduction_guide "cpp/language/deduction guide") and F2 is not 11) or, if not that, F1 is the [copy deduction candidate](deduction_guide "cpp/language/deduction guide") and F2 is not 12) or, if not that, F1 is generated from a non-template constructor and F2 is generated from a constructor template: ``` template<class T> struct A { using value_type = T; A(value_type); // #1 A(const A&); // #2 A(T, T, int); // #3 template<class U> A(int, T, U); // #4 }; // #5 is A(A), the copy deduction candidate A x (1, 2, 3); // uses #3, generated from a non-template constructor template<class T> A(T) -> A<T>; // #6, less specialized than #5 A a (42); // uses #6 to deduce A<int> and #1 to initialize A b = a; // uses #5 to deduce A<int> and #2 to initialize template<class T> A(A<T>) -> A<A<T>>; // #7, as specialized as #5 A b2 = a; // uses #7 to deduce A<A<int>> and #1 to initialize ``` | (since C++17) | These pair-wise comparisons are applied to all viable functions. If exactly one viable function is better than all others, overload resolution succeeds and this function is called. Otherwise, compilation fails. ``` void Fcn(const int*, short); // overload #1 void Fcn(int*, int); // overload #2 int i; short s = 0; void f() { Fcn(&i, 1L); // 1st argument: &i -> int* is better than &i -> const int* // 2nd argument: 1L -> short and 1L -> int are equivalent // calls Fcn(int*, int) Fcn(&i, 'c'); // 1st argument: &i -> int* is better than &i -> const int* // 2nd argument: 'c' -> int is better than 'c' -> short // calls Fcn(int*, int) Fcn(&i, s); // 1st argument: &i -> int* is better than &i -> const int* // 2nd argument: s -> short is better than s -> int // no winner, compilation error } ``` If the best viable function resolves to a function for which multiple declarations were found, and if any two of these declarations inhabit different scopes and specify a default argument that made the function viable, the program is ill-formed. ``` namespace A { extern "C" void f(int = 5); } namespace B { extern "C" void f(int = 5); } using A::f; using B::f; void use() { f(3); // OK, default argument was not used for viability f(); // error: found default argument twice } ``` ### Ranking of implicit conversion sequences The argument-parameter implicit conversion sequences considered by overload resolution correspond to [implicit conversions](implicit_conversion "cpp/language/implicit conversion") used in [copy initialization](copy_initialization "cpp/language/copy initialization") (for non-reference parameters), except that when considering conversion to the implicit object parameter or to the left-hand side of assignment operator, conversions that create temporary objects are not considered. Each [type of standard conversion sequence](implicit_conversion "cpp/language/implicit conversion") is assigned one of three ranks: 1) **Exact match**: no conversion required, lvalue-to-rvalue conversion, qualification conversion, function pointer conversion, (since C++17) user-defined conversion of class type to the same class 2) **Promotion**: integral promotion, floating-point promotion 3) **Conversion**: integral conversion, floating-point conversion, floating-integral conversion, pointer conversion, pointer-to-member conversion, boolean conversion, user-defined conversion of a derived class to its base The rank of the standard conversion sequence is the worst of the ranks of the standard conversions it holds (there may be up to [three conversions](implicit_conversion "cpp/language/implicit conversion")). Binding of a reference parameter directly to the argument expression is either Identity or a derived-to-base Conversion: ``` struct Base {}; struct Derived : Base {} d; int f(Base&); // overload #1 int f(Derived&); // overload #2 int i = f(d); // d -> Derived& has rank Exact Match // d -> Base& has rank Conversion // calls f(Derived&) ``` Since ranking of conversion sequences operates with types and value categories only, a [bit field](bit_field "cpp/language/bit field") can bind to a reference argument for the purpose of ranking, but if that function gets selected, it will be ill-formed. 1) A standard conversion sequence is always *better* than a user-defined conversion sequence or an ellipsis conversion sequence. 2) A user-defined conversion sequence is always *better* than an [ellipsis conversion](variadic_arguments "cpp/language/variadic arguments") sequence 3) A standard conversion sequence `S1` is *better* than a standard conversion sequence `S2` if a) `S1` is a subsequence of `S2`, excluding lvalue transformations. The identity conversion sequence is considered a subsequence of any other conversion b) Or, if not that, the rank of `S1` is better than the rank of `S2` c) or, if not that, both `S1` and `S2` are binding to a reference parameter to something other than the implicit object parameter of a ref-qualified member function, and `S1` binds an rvalue reference to an rvalue while `S2` binds an lvalue reference to an rvalue ``` int i; int f1(); int g(const int&); // overload #1 int g(const int&&); // overload #2 int j = g(i); // lvalue int -> const int& is the only valid conversion int k = g(f1()); // rvalue int -> const int&& better than rvalue int -> const int& ``` d) or, if not that, both `S1` and `S2` are binding to a reference parameter and `S1` binds an lvalue reference to function while `S2` binds an rvalue reference to function. ``` int f(void(&)()); // overload #1 int f(void(&&)()); // overload #2 void g(); int i1 = f(g); // calls #1 ``` e) or, if not that, both `S1` and `S2` are binding to a reference parameters only different in top-level cv-qualification, and `S1`'s type is *less* cv-qualified than `S2`'s. ``` int f(const int &); // overload #1 int f(int &); // overload #2 (both references) int g(const int &); // overload #1 int g(int); // overload #2 int i; int j = f(i); // lvalue i -> int& is better than lvalue int -> const int& // calls f(int&) int k = g(i); // lvalue i -> const int& ranks Exact Match // lvalue i -> rvalue int ranks Exact Match // ambiguous overload: compilation error ``` f) Or, if not that, S1 and S2 only differ in qualification conversion, and | | | | --- | --- | | the cv-qualification of the result of `S1` is a proper subset of the cv-qualification of the result of `S2`, and S1 is not the [deprecated string literal array-to-pointer conversion](string_literal#Notes "cpp/language/string literal") (until C++11). | (until C++20) | | the result of `S1` can be converted to the result of `S2` by a qualification conversion. | (since C++20) | ``` int f(const int*); int f(int*); int i; int j = f(&i); // &i -> int* is better than &i -> const int*, calls f(int*) ``` 4) A user-defined conversion sequence `U1` is *better* than a user-defined conversion sequence `U2` if they call the same constructor/user-defined conversion function or initialize the same class with aggregate-initialization, and in either case the second standard conversion sequence in `U1` is better than the second standard conversion sequence in `U2` ``` struct A { operator short(); // user-defined conversion function } a; int f(int); // overload #1 int f(float); // overload #2 int i = f(a); // A -> short, followed by short -> int (rank Promotion) // A -> short, followed by short -> float (rank Conversion) // calls f(int) ``` 5) A list-initialization sequence `L1` is *better* than list-initialization sequence `L2` if `L1` initializes an `[std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)` parameter, while `L2` does not. ``` void f1(int); // #1 void f1(std::initializer_list<long>); // #2 void g1() { f1({42}); } // chooses #2 void f2(std::pair<const char*, const char*>); // #3 void f2(std::initializer_list<std::string>); // #4 void g2() { f2({"foo", "bar"}); } // chooses #4 ``` | | | | --- | --- | | 6) A list-initialization sequence `L1` is *better* than list-initialization sequence `L2` if the corresponding parameters are references to arrays, and L1 converts to type "array of N1 T," L2 converts to type "array of N2 T", and N1 is smaller than N2. | (since C++11)(until C++20) | | 6) A list-initialization sequence `L1` is *better* than list-initialization sequence `L2` if the corresponding parameters are references to arrays, and L1 and L2 convert to arrays of same element type, and either * the number of elements N1 initialized by L1 is less than the number of elements N2 initialized by L2, or * N1 is equal to N2 and L2 converts to an array of unknown bound and L1 does not. ``` void f(int (&&)[] ); // overload #1 void f(double (&&)[] ); // overload #2 void f(int (&&)[2]); // overload #3 f({1}); // #1: Better than #2 due to conversion, better than #3 due to bounds f({1.0}); // #2: double -> double is better than double -> int f({1.0, 2.0}); // #2: double -> double is better than double -> int f({1, 2}); // #3: -> int[2] is better than -> int[], // and int -> int is better than int -> double ``` | (since C++20) | If two conversion sequences are indistinguishable because they have the same rank, the following additional rules apply: 1) Conversion that involves pointer to bool or pointer-to-member to bool is worse than the one that doesn't. | | | | --- | --- | | 2) Conversion that promotes an [enumeration](enum "cpp/language/enum") whose underlying type is fixed to its underlying type is better than one that promotes to the promoted underlying type, if the two types are different. ``` enum num : char { one = '0' }; std::cout << num::one; // '0', not 48 ``` | (since C++11) | 3) Conversion that converts pointer-to-derived to pointer-to-base is better than the conversion of pointer-to-derived to pointer-to-void, and conversion of pointer-to-base to void is better than pointer-to-derived to void. 4) If `Mid` is derived (directly or indirectly) from `Base`, and `Derived` is derived (directly or indirectly) from `Mid` a) `Derived*` to `Mid*` is better than `Derived*` to `Base*` b) `Derived` to `Mid&` or `Mid&&` is better than `Derived` to `Base&` or `Base&&` c) `Base::*` to `Mid::*` is better than `Base::*` to `Derived::*` d) `Derived` to `Mid` is better than `Derived` to `Base` e) `Mid*` to `Base*` is better than `Derived*` to `Base*` f) `Mid` to `Base&` or `Base&&` is better than `Derived` to `Base&` or `Base&&` g) `Mid::*` to `Derived::*` is better than `Base::*` to `Derived::*` h) `Mid` to `Base` is better than `Derived` to `Base` Ambiguous conversion sequences are ranked as user-defined conversion sequences because multiple conversion sequences for an argument can exist only if they involve different user-defined conversions: ``` class B; class A { A (B&);}; // converting constructor class B { operator A (); }; // user-defined conversion function class C { C (B&); }; // converting constructor void f(A) {} // overload #1 void f(C) {} // overload #2 B b; f(b); // B -> A via ctor or B -> A via function (ambiguous conversion) // b -> C via ctor (user-defined conversion) // the conversions for overload #1 and for overload #2 // are indistinguishable; compilation fails ``` ### Implicit conversion sequence in list-initialization In [list initialization](list_initialization "cpp/language/list initialization"), the argument is a braced-init-list, which isn't an expression, so the implicit conversion sequence into the parameter type for the purpose of overload resolution is decided by the following special rules: * If the parameter type is some aggregate `X` and the initializer list consists of exactly one element of same or derived class (possibly cv-qualified), the implicit conversion sequence is the one required to convert the element to the parameter type. * Otherwise, if the parameter type is a reference to character array and the initializer list has a single element that is an appropriately-typed string literal, the implicit conversion sequence is the identity conversion. * Otherwise, if the parameter type is `[std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)<X>`, and there is an non-narrowing implicit conversion from every element of the initializer list to `X`, the implicit conversion sequence for the purpose of overload resolution is the worst conversion necessary. If the braced-init-list is empty, the conversion sequence is the identity conversion. ``` struct A { A(std::initializer_list<double>); // #1 A(std::initializer_list<complex<double>>); // #2 A(std::initializer_list<std::string>); // #3 }; A a{1.0, 2.0}; // selects #1 (rvalue double -> double: identity conv) void g(A); g({"foo", "bar"}); // selects #3 (lvalue const char[4] -> std::string: user-def conv) ``` * Otherwise, if the parameter type is "array of N T" (this only happens for references to arrays), the initializer list must have N or less elements, and the worst implicit conversion necessary to convert every element of the list (or the empty pair of braces `{}` if the list is shorter than N) to `T` is the one used. | | | | --- | --- | | * Otherwise, if the parameter type is "array of unknown bound of T" (this only happens for references to arrays), the worst implicit conversion necessary to convert every element of the list to `T` is the one used. | (since C++20) | ``` typedef int IA[3]; void h(const IA&); void g(int (&&)[]); h({1, 2, 3}); // int->int identity conversion g({1, 2, 3}); // same as above since C++20 ``` * Otherwise, if the parameter type is a non-aggregate class type `X`, overload resolution picks the constructor C of X to initialize from the argument initializer list + If C is not an initializer-list constructor and the initializer list has a single element of possibly cv-qualified X, the implicit conversion sequence has Exact Match rank. If the initializer list has a single element of possibly cv-qualified type derived from X, the implicit conversion sequence has Conversion rank. (note the difference from aggregates: aggregates initialize directly from single-element init lists before considering [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization"), non-aggregates consider initializer\_list constructors before any other constructors) + otherwise, the implicit conversion sequence is a user-defined conversion sequence with the second standard conversion sequence an identity conversion. If multiple constructors are viable but none is better than the others, the implicit conversion sequence is the ambiguous conversion sequence. ``` struct A { A(std::initializer_list<int>); }; void f(A); struct B { B(int, double); }; void g(B); g({'a', 'b'}); // calls g(B(int, double)), user-defined conversion // g({1.0, 1,0}); // error: double->int is narrowing, not allowed in list-init void f(B); // f({'a', 'b'}); // f(A) and f(B) both user-defined conversions ``` * Otherwise, if the parameter type is an aggregate which can be initialized from the initializer list according by [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization"), the implicit conversion sequence is a user-defined conversion sequence with the second standard conversion sequence an identity conversion. ``` struct A { int m1; double m2;}; void f(A); f({'a', 'b'}); // calls f(A(int, double)), user-defined conversion ``` * Otherwise, if the parameter is a reference, reference initialization rules apply ``` struct A { int m1; double m2; }; void f(const A&); f({'a', 'b'}); // temporary created, f(A(int, double)) called. User-defined conversion ``` * Otherwise, if the parameter type is not a class and the initializer list has one element, the implicit conversion sequence is the one required to convert the element to the parameter type * Otherwise, if the parameter type is not a class type and if the initializer list has no elements, the implicit conversion sequence is the identity conversion. | | | | --- | --- | | If the argument is a designated initializer list, a conversion is only possible if the parameter has an aggregate type that can be initialized from that initializer list according to the rules for [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization"), in which case the implicit conversion sequence is a user-defined conversion sequence whose second standard conversion sequence is an identity conversion. If, after overload resolution, the order of declaration of the aggregate's members does not match for the selected overload, the initialization of the parameter will be ill-formed. ``` struct A { int x, y; }; struct B { int y, x; }; void f(A a, int); // #1 void f(B b, ...); // #2 void g(A a); // #3 void g(B b); // #4 void h() { f({.x = 1, .y = 2}, 0); // OK; calls #1 f({.y = 2, .x = 1}, 0); // error: selects #1, initialization of a fails // due to non-matching member order g({.x = 1, .y = 2}); // error: ambiguous between #3 and #4 } ``` | (since C++20) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1](https://cplusplus.github.io/CWG/issues/1.html) | C++98 | the behavior was unspecified when the same function with possiblydifferent default arguments (from different scopes) is selected | the program is ill-formed in this case | | [CWG 83](https://cplusplus.github.io/CWG/issues/83.html) | C++98 | the conversion sequence from a string literal to `char*` was betterthan that to `const char*` even though the former is deprecated | the rank of the deprecated conversionis lowered (it was removed in C++11) | | [CWG 162](https://cplusplus.github.io/CWG/issues/162.html) | C++98 | it was invalid if the overload set named by `F` containsa non-static member function in the case of `&F(args)` | only invalid if overload resolution selectsa non-static member function in this case | | [CWG 280](https://cplusplus.github.io/CWG/issues/280.html) | C++98 | surrogate call functions were not added tothe set of candidate functions for conversionfunctions declared in inaccessible base classes | removed the accessibility constraint, theprogram is ill-formed if a surrogate callfunction is selected and the correspondingconversion function cannot be called | | [CWG 415](https://cplusplus.github.io/CWG/issues/415.html) | C++98 | when a function template is selected as a candidate, itsspecializations were instantiated using template argument deduction | no instantiation will occur in this case,their declarations will be synthesized | | [CWG 495](https://cplusplus.github.io/CWG/issues/495.html) | C++98 | when the implicit conversions for arguments are equallygood, a non-template conversion function was alwaysbetter than a conversion function template, even if thelatter may have a better standard conversion sequence | standard conversion sequences arecompared before specialization levels | | [CWG 1307](https://cplusplus.github.io/CWG/issues/1307.html) | C++11 | overload resolution based on size of arrays was not specified | a shorter array is better when possible | | [CWG 1328](https://cplusplus.github.io/CWG/issues/1328.html) | C++11 | the determination of the candidate functions whenbinding a reference to a conversion result was not clear | made clear | | [CWG 1374](https://cplusplus.github.io/CWG/issues/1374.html) | C++98 | qualification conversion was checked before referencebinding when comparing standard conversion sequences | reversed | | [CWG 1385](https://cplusplus.github.io/CWG/issues/1385.html) | C++11 | a non-explicit user-defined conversion function declared witha ref-qualifier did not have a corresponding surrogate function | it has a correspondingsurrogate function | | [CWG 1467](https://cplusplus.github.io/CWG/issues/1467.html) | C++11 | same-type list-initialization of aggregates and arrays was omitted | initialization defined | | [CWG 1601](https://cplusplus.github.io/CWG/issues/1601.html) | C++11 | conversion from enum to its underlying typedid not prefer the fixed underlying type | fixed type is preferred towhat it promotes to | | [CWG 1608](https://cplusplus.github.io/CWG/issues/1608.html) | C++98 | the set of member candidates of a unary operator `@` whose argumenthas type `T1` was empty if `T1` is a class currently being defined | the set is the result of qualified namelookup of `T1::operator@` in this case | | [CWG 1687](https://cplusplus.github.io/CWG/issues/1687.html) | C++98 | when a built-in candidate is selected by overload resolution,the operands would undergo conversion without restriction | only convert class type operands,and disabled the secondstandard conversion sequence | | [CWG 2052](https://cplusplus.github.io/CWG/issues/2052.html) | C++98 | ill-formed synthesized function template specializations couldbe added to the candidate set, making the program ill-formed | they are not addedto the candidate set | | [CWG 2137](https://cplusplus.github.io/CWG/issues/2137.html) | C++11 | initializer list constructors lost to copyconstructors when list-initializing X from {X} | non-aggregates considerinitializer lists first | | [CWG 2273](https://cplusplus.github.io/CWG/issues/2273.html) | C++11 | there was no tiebreaker betweeninherited and non-inherited constructors | non-inherited constructor wins | ### References * C++20 standard (ISO/IEC 14882:2020): + 12.4 Overload resolution [over.match] * C++17 standard (ISO/IEC 14882:2017): + 16.3 Overload resolution [over.match] * C++14 standard (ISO/IEC 14882:2014): + 13.3 Overload resolution [over.match] * C++11 standard (ISO/IEC 14882:2011): + 13.3 Overload resolution [over.match] * C++03 standard (ISO/IEC 14882:2003): + 13.3 Overload resolution [over.match] ### See also * [Name lookup](lookup "cpp/language/lookup") * [Argument-dependent lookup](adl "cpp/language/adl") * [Template argument deduction](template_argument_deduction "cpp/language/template argument deduction") * [SFINAE](sfinae "cpp/language/sfinae")
programming_docs
cpp Enumeration declaration Enumeration declaration ======================= An *enumeration* is a distinct type whose value is restricted to a range of values (see below for details), which may include several explicitly named constants ("*enumerators*"). The values of the constants are values of an integral type known as the *underlying type* of the enumeration. An enumeration is (re)declared using the following syntax: | | | | | --- | --- | --- | | enum-key attr(optional) enum-head-name(optional) enum-base(optional)`{` enumerator-list(optional) `}` | (1) | | | enum-key attr(optional) enum-head-name(optional) enum-base(optional)`{` enumerator-list `, }` | (2) | | | enum-key attr(optional) enum-head-name enum-base(optional) `;` | (3) | (since C++11) | 1) *enum-specifier*, which appears in decl-specifier-seq of the [declaration](declarations "cpp/language/declarations") syntax: defines the enumeration type and its enumerators. 2) A trailing comma can follow the enumerator-list. 3) *Opaque enum declaration*: defines the enumeration type but not its enumerators: after this declaration, the type is a complete type and its size is known. | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | enum-key | - | | | | | --- | --- | | `enum`. | (until C++11) | | one of `enum`, `enum class`, or `enum struct`. | (since C++11) | | | attr | - | (since C++11) optional sequence of any number of [attributes](attributes "cpp/language/attributes") | | enum-head-name | - | | | | | --- | --- | | the name of the enumeration that's being declared, it can be omitted. | (until C++11) | | the name of the enumeration that's being declared, optionally preceded by a nested-name-specifier: sequence of names and scope-resolution operators `::`, ending with scope-resolution operator. It can only be omitted in unscoped non-opaque enumeration declarations. nested-name-specifier may only appear if the enumeration name is present and this declaration is a redeclaration. For opaque enumeration declarations, nested-name-specifier can only appear before the name of the enumeration in [explicit specialization declarations](template_specialization "cpp/language/template specialization"). If nested-name-specifier is present, the *enum-specifier* cannot refer to an enumeration merely inherited or introduced by a [using-declaration](using_declaration "cpp/language/using declaration"), and the *enum-specifier* can only appear in a namespace enclosing the previous declaration. In such cases, nested-name-specifier cannot begin with a [decltype](decltype "cpp/language/decltype") specifier. | (since C++11) | | | enum-base | - | (since C++11) colon (`:`), followed by a type-specifier-seq that names an integral type (if it is cv-qualified, qualifications are ignored) that will serve as the fixed underlying type for this enumeration type | | enumerator-list | - | comma-separated list of enumerator definitions, each of which is either simply an identifier, which becomes the name of the enumerator, or an identifier with an initializer: identifier `=` constexpr. In either case, the identifier can be directly followed by an optional [attribute specifier sequence](attributes "cpp/language/attributes"). (since C++17) | There are two distinct kinds of enumerations: *unscoped enumeration* (declared with the enum-key `enum`) and *scoped enumeration* (declared with the enum-key `enum class` or `enum struct`). ### Unscoped enumerations | | | | | --- | --- | --- | | `enum` name(optional) `{` enumerator `=` constexpr `,` enumerator `=` constexpr `,` ... `}` | (1) | | | `enum` name(optional) `:` type `{` enumerator `=` constexpr `,` enumerator `=` constexpr `,` ... `}` | (2) | (since C++11) | | `enum` name `:` type `;` | (3) | (since C++11) | 1) Declares an unscoped enumeration type whose underlying type is not fixed (in this case, the underlying type is an implementation-defined integral type that can represent all enumerator values; this type is not larger than `int` unless the value of an enumerator cannot fit in an `int` or `unsigned int`. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0. If no integral type can represent all the enumerator values, the enumeration is ill-formed). 2) Declares an unscoped enumeration type whose underlying type is fixed. 3) Opaque enum declaration for an unscoped enumeration must specify the name and the underlying type. Each enumerator becomes a named constant of the enumeration's type (that is, name), visible in the enclosing scope, and can be used whenever constants are required. ``` enum Color { red, green, blue }; Color r = red; switch(r) { case red : std::cout << "red\n"; break; case green: std::cout << "green\n"; break; case blue : std::cout << "blue\n"; break; } ``` Each enumerator is associated with a value of the underlying type. When initializers are provided in the enumerator-list, the values of enumerators are defined by those initializers. If the first enumerator does not have an initializer, the associated value is zero. For any other enumerator whose definition does not have an initializer, the associated value is the value of the previous enumerator plus one. ``` enum Foo { a, b, c = 10, d, e = 1, f, g = f + c }; //a = 0, b = 1, c = 10, d = 11, e = 1, f = 2, g = 12 ``` Values of unscoped enumeration type are [implicitly-convertible](implicit_conversion#Integral_promotion "cpp/language/implicit conversion") to integral types. If the underlying type is not fixed, the value is convertible to the first type from the following list able to hold their entire value range: `int`, `unsigned int`, `long`, `unsigned long`, `long long`, or `unsigned long long`, extended integer types with higher conversion rank (in rank order, signed given preference over unsigned) (since C++11). If the underlying type is fixed, the values can be converted to their underlying type (preferred in [overload resolution](overload_resolution "cpp/language/overload resolution")), which can then be [promoted](implicit_conversion#Integral_promotion "cpp/language/implicit conversion"). ``` enum color { red, yellow, green = 20, blue }; color col = red; int n = blue; // n == 21 ``` Values of integer, floating-point, and enumeration types can be converted by [`static_cast`](static_cast "cpp/language/static cast") or [explicit cast](explicit_cast "cpp/language/explicit cast"), to any enumeration type. If the underlying type is not fixed and the source value is out of range, the behavior is undefined. (The source value, as converted to the enumeration's underlying type if floating-point, is in range if it would fit in the smallest bit field large enough to hold all enumerators of the target enumeration.) Otherwise, the result is the same as the result of [implicit conversion](implicit_conversion "cpp/language/implicit conversion") to the underlying type. Note that the value after such conversion may not necessarily equal any of the named enumerators defined for the enumeration. ``` enum access_t { read = 1, write = 2, exec = 4 }; // enumerators: 1, 2, 4 range: 0..7 access_t rwe = static_cast<access_t>(7); assert((rwe & read) && (rwe & write) && (rwe & exec)); access_t x = static_cast<access_t>(8.0); // undefined behavior since CWG1766 access_t y = static_cast<access_t>(8); // undefined behavior since CWG1766 enum foo { a = 0, b = UINT_MAX }; // range: [0, UINT_MAX] foo x = foo(-1); // undefined behavior since CWG1766, // even if foo's underlying type is unsigned int ``` The name of an unscoped enumeration may be omitted: such declaration only introduces the enumerators into the enclosing scope: ``` enum { a, b, c = 0, d = a + 2 }; // defines a = 0, b = 1, c = 0, d = 2 ``` When an unscoped enumeration is a class member, its enumerators may be accessed using class member access operators `.` and `->`: ``` struct X { enum direction { left = 'l', right = 'r' }; }; X x; X* p = &x; int a = X::direction::left; // allowed only in C++11 and later int b = X::left; int c = x.left; int d = p->left; ``` | | | | --- | --- | | In the [declaration specifiers](declarations#Specifiers "cpp/language/declarations") of a [member declaration](class#Member_specification "cpp/language/class"), the sequence `enum`. enum-head-name `:` is always parsed as a part of enumeration declaration: ``` struct S { enum E1 : int {}; enum E1 : int {}; // error: redeclaration of enumeration, // NOT parsed as a zero-length bit-field of type enum E1 }; enum E2 { e1 }; void f() { false ? new enum E2 : int(); // OK: 'int' is NOT parsed as the underlying type } ``` | (since C++11) | ### Scoped enumerations | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | --- | --- | --- | | `enum` `struct|class` name `{` enumerator `=` constexpr `,` enumerator `=` constexpr `,` ... `}` | (1) | | | `enum` `struct|class` name `:` type `{` enumerator `=` constexpr `,` enumerator `=` constexpr `,` ... `}` | (2) | | | `enum` `struct|class` name `;` | (3) | | | `enum` `struct|class` name `:` type `;` | (4) | | 1) declares a scoped enumeration type whose underlying type is `int` (the keywords `class` and `struct` are exactly equivalent) 2) declares a scoped enumeration type whose underlying type is type 3) opaque enum declaration for a scoped enumeration whose underlying type is `int` 4) opaque enum declaration for a scoped enumeration whose underlying type is type Each enumerator becomes a named constant of the enumeration's type (that is, name), which is contained within the scope of the enumeration, and can be accessed using scope resolution operator. There are no implicit conversions from the values of a scoped enumerator to integral types, although [`static_cast`](static_cast "cpp/language/static cast") may be used to obtain the numeric value of the enumerator. ``` enum class Color { red, green = 20, blue }; Color r = Color::blue; switch(r) { case Color::red : std::cout << "red\n"; break; case Color::green: std::cout << "green\n"; break; case Color::blue : std::cout << "blue\n"; break; } // int n = r; // error: no implicit conversion from scoped enum to int int n = static_cast<int>(r); // OK, n = 21 ``` | (since C++11) | | | | | --- | --- | | An enumeration can be initialized from an integer without a cast, using [list initialization](list_initialization "cpp/language/list initialization"), if all of the following are true:* the initialization is direct-list-initialization * the initializer list has only a single element * the enumeration is either scoped or unscoped with underlying type fixed * the conversion is non-narrowing This makes it possible to introduce new integer types (e.g. `SafeInt`) that enjoy the same existing calling conventions as their underlying integer types, even on ABIs that penalize passing/returning structures by value. ``` enum byte : unsigned char {}; // byte is a new integer type; see also std::byte (C++17) byte b{42}; // OK as of C++17 (direct-list-initialization) byte c = {42}; // error byte d = byte{42}; // OK as of C++17; same value as b byte e{-1}; // error struct A { byte b; }; A a1 = {{42}}; // error (copy-list-initialization of a constructor parameter) A a2 = {byte{42}}; // OK as of C++17 void f(byte); f({42}); // error (copy-list-initialization of a function parameter) enum class Handle : std::uint32_t { Invalid = 0 }; Handle h{42}; // OK as of C++17 ``` | (since C++17) | | | | | | | | --- | --- | --- | --- | --- | | Using-enum-declaration | | | | | --- | --- | --- | | `using` `enum` nested-name-specifier(optional) name `;` | | (since C++20) | where nested-name-specifier(optional) name must not name a [dependent type](dependent_name#Dependent_types "cpp/language/dependent name") and must name an enumeration type. A using-enum-declaration introduces the enumerator names of the named enumeration as if by a [using-declaration](using_declaration "cpp/language/using declaration") for each enumerator. When in class scope, a using-enum-declaration adds the enumerators of the named enumeration as members to the scope, making them accessible for member lookup. ``` enum class fruit { orange, apple }; struct S { using enum fruit; // OK: introduces orange and apple into S }; void f() { S s; s.orange; // OK: names fruit::orange S::orange; // OK: names fruit::orange } ``` Two using-enum-declarations that introduce two enumerators of the same name conflict. ``` enum class fruit { orange, apple }; enum class color { red, orange }; void f() { using enum fruit; // OK // using enum color; // error: color::orange and fruit::orange conflict } ``` | (since C++20) | ### Notes Although the conversion from an out-of-range to an enumeration without fixed underlying type is made undefined behavior by the resolution of [CWG issue 1766](https://cplusplus.github.io/CWG/issues/1766.html), currently no compiler performs the required diagnostic for it in constant evaluation. ### Example ``` #include <iostream> #include <cstdint> // enum that takes 16 bits enum smallenum: std::int16_t { a, b, c }; // color may be red (value 0), yellow (value 1), green (value 20), or blue (value 21) enum color { red, yellow, green = 20, blue }; // altitude may be altitude::high or altitude::low enum class altitude: char { high = 'h', low = 'l', // trailing comma only allowed after CWG518 }; // the constant d is 0, the constant e is 1, the constant f is 3 enum { d, e, f = e + 2 }; // enumeration types (both scoped and unscoped) can have overloaded operators std::ostream& operator<<(std::ostream& os, color c) { switch(c) { case red : os << "red"; break; case yellow: os << "yellow"; break; case green : os << "green"; break; case blue : os << "blue"; break; default : os.setstate(std::ios_base::failbit); } return os; } std::ostream& operator<<(std::ostream& os, altitude al) { return os << static_cast<char>(al); } // The scoped enum (C++11) can be partially emulated in earlier C++ revisions: enum struct E11 { x, y }; // since C++11 struct E98 { enum { x, y }; }; // OK in pre-C++11 namespace N98 { enum { x, y }; } // OK in pre-C++11 struct S98 { static const int x = 0, y = 1; }; // OK in pre-C++11 void emu() { std::cout << (static_cast<int>(E11::y) + E98::y + N98::y + S98::y) << '\n'; // 4 } namespace cxx20 { enum class long_long_long_name { x, y }; void using_enum_demo() { std::cout << "C++20 `using enum`: __cpp_using_enum == "; switch (auto rnd = []{return long_long_long_name::x;}; rnd()) { #if defined(__cpp_using_enum) using enum long_long_long_name; case x: std::cout << __cpp_using_enum << "; x\n"; break; case y: std::cout << __cpp_using_enum << "; y\n"; break; #else case long_long_long_name::x: std::cout << "?; x\n"; break; case long_long_long_name::y: std::cout << "?; y\n"; break; #endif } } } int main() { color col = red; altitude a; a = altitude::low; std::cout << "col = " << col << '\n' << "a = " << a << '\n' << "f = " << f << '\n'; cxx20::using_enum_demo(); } ``` Possible output: ``` col = red a = l f = 3 C++20 `using enum`: __cpp_using_enum == 201907; x ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 377](https://cplusplus.github.io/CWG/issues/377.html) | C++98 | the behavior was unspecified when no integraltype can represent all the enumerator values | the enumeration is ill-formed in this case | | [CWG 518](https://cplusplus.github.io/CWG/issues/518.html) | C++98 | a trailing comma was not allowed after the enumerator list | allowed | | [CWG 1514](https://cplusplus.github.io/CWG/issues/1514.html) | C++11 | an redefinition of enumeration with fixed underlying typecould be parsed as a bit-field in a class member declaration | always parsed as a redefinition | | [CWG 1638](https://cplusplus.github.io/CWG/issues/1638.html) | C++11 | grammar of opaque enumeration declarationprohibited use for template specializations | nested-name-specifierpermitted | | [CWG 1766](https://cplusplus.github.io/CWG/issues/1766.html) | C++98 | casting an out-of-range value to an enumerationwithout fixed underlying type had an unspecified result | the behavior is undefined | | [CWG 1966](https://cplusplus.github.io/CWG/issues/1966.html) | C++11 | the resolution of [CWG issue 1514](https://cplusplus.github.io/CWG/issues/1514.html) made the `:`of a conditional expression part of enum-base | only apply the resolution tomember declaration specifiers | | [CWG 2156](https://cplusplus.github.io/CWG/issues/2156.html) | C++11 | enum definitions could defineenumeration types by using-declarations | prohibited | | [CWG 2157](https://cplusplus.github.io/CWG/issues/2157.html) | C++11 | the resolution of [CWG issue 1966](https://cplusplus.github.io/CWG/issues/1966.html) didnot cover qualified enumeration names | covered | ### See also | | | | --- | --- | | [is\_enum](../types/is_enum "cpp/types/is enum") (C++11) | checks if a type is an enumeration type (class template) | | [is\_scoped\_enum](../types/is_scoped_enum "cpp/types/is scoped enum") (C++23) | checks if a type is a scoped enumeration type (class template) | | [underlying\_type](../types/underlying_type "cpp/types/underlying type") (C++11) | obtains the underlying integer type for a given enumeration type (class template) | | [to\_underlying](../utility/to_underlying "cpp/utility/to underlying") (C++23) | converts an enumeration to its underlying type (function template) | | [C documentation](https://en.cppreference.com/w/c/language/enum "c/language/enum") for Enumerations | cpp Unqualified name lookup Unqualified name lookup ======================= For an *unqualified* name, that is a name that does not appear to the right of a scope resolution operator `::`, name lookup examines the [scopes](scope "cpp/language/scope") as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined. (Note: lookup from some contexts skips some declarations, for example, lookup of the name used to the left of `::` ignores function, variable, and enumerator declarations, lookup of a name used as a base class specifier ignores all non-type declarations). For the purpose of unqualified name lookup, all declarations from a namespace nominated by a [using directive](namespace "cpp/language/namespace") appear as if declared in the nearest enclosing namespace which contains, directly or indirectly, both the using-directive and the nominated namespace. Unqualified name lookup of the name used to the left of the function-call operator (and, equivalently, operator in an expression) is described in [argument-dependent lookup](adl "cpp/language/adl"). ### File scope For a name used in global (top-level namespace) scope, outside of any function, class, or user-declared namespace, the global scope before the use of the name is examined: ``` int n = 1; // declaration of n int x = n + 1; // OK: lookup finds ::n int z = y - 1; // Error: lookup fails int y = 2; // declaration of y ``` ### Namespace scope For a name used in a user-declared namespace outside of any function or class, this namespace is searched before the use of the name, then the namespace enclosing this namespace before the declaration of this namespace, etc until the global namespace is reached. ``` int n = 1; // declaration namespace N { int m = 2; namespace Y { int x = n; // OK, lookup finds ::n int y = m; // OK, lookup finds ::N::m int z = k; // Error: lookup fails } int k = 3; } ``` ### Definition outside of its namespace For a name used in the definition of a namespace-member variable outside the namespace, lookup proceeds the same way as for a name used inside the namespace: ``` namespace X { extern int x; // declaration, not definition int n = 1; // found 1st }; int n = 2; // found 2nd int X::x = n; // finds X::n, sets X::x to 1 ``` ### Non-member function definition For a name used in the definition of a function, either in its body or as part of default argument, where the function is a member of user-declared or global namespace, the block in which the name is used is searched before the use of the name, then the enclosing block is searched before the start of that block, etc, until reaching the block that is the function body. Then the namespace in which the function is declared is searched until the definition (not necessarily the declaration) of the function that uses the name, then the enclosing namespaces, etc. ``` namespace A { namespace N { void f(); int i = 3; // found 3rd (if 2nd is not present) } int i = 4; // found 4th (if 3rd is not present) } int i = 5; // found 5th (if 4th is not present) void A::N::f() { int i = 2; // found 2nd (if 1st is not present) while(true) { int i = 1; // found 1st: lookup is done std::cout << i; } } // int i; // not found namespace A { namespace N { // int i; // not found } } ``` ### Class definition For a name used anywhere in [class definition](class "cpp/language/class") (including base class specifiers and nested class definitions), except inside a member function body, a default argument of a member function, exception specification of a member function, or default member initializer, where the member may belong to a nested class whose definition is in the body of the enclosing class, the following scopes are searched: a) the body of the class in which the name is used until the point of use b) the entire body of its base class(es), recursing into their bases when no declarations are found c) if this class is [nested](nested_types "cpp/language/nested types"), the body of the enclosing class until the definition of this class and the entire body of the base class(es) of the enclosing class. d) if this class is [local](class#Local_classes "cpp/language/class"), or nested within a local class, the block scope in which the class is defined until the point of definition e) if this class is a member of a namespace, or is nested in a class that is a member of a namespace, or is a local class in a function that is a member of a namespace, the scope of the namespace is searched until the definition of the class, enclosing class, or function; lookup continues to the namespaces enclosing that one until the global scope. For a [friend](friend "cpp/language/friend") declaration, the lookup to determine whether it refers to a previously declared entity proceeds as above except that it stops after the innermost enclosing namespace. ``` namespace M { // const int i = 1; // never found class B { // static const int i = 3; // found 3rd (but will not pass access check) }; } // const int i = 5; // found 5th namespace N { // const int i = 4; // found 4th class Y : public M::B { // static const int i = 2; // found 2nd class X { // static const int i = 1; // found 1st int a[i]; // use of i // static const int i = 1; // never found }; // static const int i = 2; // never found }; // const int i = 4; // never found } // const int i = 5; // never found ``` ### Injected class name For the name of a class or class template used within the definition of that class or template or derived from one, unqualified name lookup finds the class that's being defined as if the name was introduced by a member declaration (with public member access). For more detail, see [injected-class-name](injected-class-name "cpp/language/injected-class-name"). ### Member function definition For a name used inside a member function body, a default argument of a member function, exception specification of a member function, or a default member initializer, the scopes searched are the same as in [class definition](#Class_definition), except that the entire scope of the class is considered, not just the part prior to the declaration that uses the name. For nested classes the entire body of the enclosing class is searched. ``` class B { // int i; // found 3rd }; namespace M { // int i; // found 5th namespace N { // int i; // found 4th class X : public B { // int i; // found 2nd void f(); // int i; // found 2nd as well }; // int i; // found 4th } } // int i; // found 6th void M::N::X::f() { // int i; // found 1st i = 16; // int i; // never found } namespace M { namespace N { // int i; // never found } } ``` Either way, when examining the bases from which the class is derived, the following rules, sometime referred to as [dominance in virtual inheritance](https://en.wikipedia.org/wiki/Dominance_(C%2B%2B) "enwiki:Dominance (C++)"), are followed: | | | | --- | --- | | A member name found in a sub-object `B` hides the same member name in any sub-object `A` if `A` is a base class sub-object of `B`. (Note that this does not hide the name in any additional, non-virtual, copies of `A` on the inheritance lattice that aren't bases of `B`: this rule only has an effect on virtual inheritance.) Names introduced by using-declarations are treated as names in the class containing the declaration. After examining each base, the resulting set must either include declarations of a static member from subobjects of the same type, or declarations of non-static members from the same subobject | (until C++11) | | A *lookup set* is constructed, which consists of the declarations and the subobjects in which these declarations were found. Using-declarations are replaced by the members they represent and type declarations, including injected-class-names are replaced by the types they represent. If `C` is the class in whose scope the name was used, `C` is examined first. If the list of declarations in `C` is empty, lookup set is built for each of its direct bases `Bi` (recursively applying these rules if `Bi` has its own bases). Once built, the lookup sets for the direct bases are merged into the lookup set in `C` as follows * if the set of declarations in `Bi` is empty, it is discarded * if the lookup set of `C` built so far is empty, it is replaced by the lookup set of `Bi` * if every subobject in the lookup set of `Bi` is a base of at least one of the subobjects already added to the lookup set of `C`, the lookup set of `Bi` is discarded. * if every subobject already added to the lookup set of `C` is a base of at least one subobject in the lookup set of `Bi`, then the lookup set of `C` is discarded and replaced with the lookup set of `Bi` * otherwise, if the declaration sets in `Bi` and in `C` are different, the result is an ambiguous merge: the new lookup set of `C` has an invalid declaration and a union of the subobjects ealier merged into `C` and introduced from `Bi`. This invalid lookup set may not be an error if it is discarded later. * otherwise, the new lookup set of `C` has the shared declaration sets and the union of the subobjects ealier merged into `C` and introduced from `Bi` | (since C++11) | ``` struct X { void f(); }; struct B1: virtual X { void f(); }; struct B2: virtual X {}; struct D : B1, B2 { void foo() { X::f(); // OK, calls X::f (qualified lookup) f(); // OK, calls B1::f (unqualified lookup) } }; // C++98 rules: B1::f hides X::f, so even though X::f can be reached from D // through B2, it is not found by name lookup from D. // C++11 rules: lookup set for f in D finds nothing, proceeds to bases // lookup set for f in B1 finds B1::f, and is completed // merge replaces the empty set, now lookup set for f in C has B1::f in B1 // lookup set for f in B2 finds nothing, proceeds to bases // lookup for f in X finds X::f // merge replaces the empty set, now lookup set for f in B2 has X::f in X // merge into C finds that every subobject (X) in the lookup set in B2 is a base // of every subobject (B1) already merged, so the B2 set is discareded // C is left with just B1::f found in B1 // (if struct D : B2, B1 was used, then the last merge would *replace* C's // so far merged X::f in X because every subobject already added to C (that is X) // would be a base of at least one subobject in the new set (B1), the end // result would be the same: lookup set in C holds just B1::f found in B1) ``` Unqualified name lookup that finds static members of `B`, nested types of `B`, and enumerators declared in `B` is unambiguous even if there are multiple non-virtual base subobjects of type `B` in the inheritance tree of the class being examined: ``` struct V { int v; }; struct A { int a; static int s; enum { e }; }; struct B : A, virtual V {}; struct C : A, virtual V {}; struct D : B, C {}; void f(D& pd) { ++pd.v; // OK: only one v because only one virtual base subobject ++pd.s; // OK: only one static A::s, even though found in B and in C int i = pd.e; // OK: only one enumerator A::e, even though found in B and C ++pd.a; // error, ambiguous: A::a in B and A::a in C } ``` ### Friend function definition For a name used in a [friend](friend "cpp/language/friend") function definition inside the body of the class that is granting friendship, unqualified name lookup proceeds the same way as for a member function. For a name used in a [friend](friend "cpp/language/friend") function which is defined outside the body of a class, unqualified name lookup proceeds the same way as for a function in a namespace. ``` int i = 3; // found 3rd for f1, found 2nd for f2 struct X { static const int i = 2; // found 2nd for f1, never found for f2 friend void f1(int x) { // int i; // found 1st i = x; // finds and modifies X::i } friend int f2(); // static const int i = 2; // found 2nd for f1 anywhere in class scope }; void f2(int x) { // int i; // found 1st i = x; // finds and modifies ::i } ``` ### Friend function declaration For a name used in the declarator of a [friend](friend "cpp/language/friend") function declaration that friends a member function from another class, if the name is not a part of any template argument in the [declarator](declarations#Declarators "cpp/language/declarations") identifier, the unqualified lookup first examines the entire scope of the member function's class. If not found in that scope (or if the name is a part of a template argument in the declarator identifier), the lookup continues as if for a member function of the class that is granting friendship. ``` template<class T> struct S; // the class whose member functions are friended struct A { typedef int AT; void f1(AT); void f2(float); template<class T> void f3(); void f4(S<AT>); }; // the class that is granting friendship for f1, f2 and f3 struct B { typedef char AT; typedef float BT; friend void A::f1(AT); // lookup for AT finds A::AT (AT found in A) friend void A::f2(BT); // lookup for BT finds B::BT (BT not found in A) friend void A::f3<AT>(); // lookup for AT finds B::AT (no lookup in A, because // AT is in the declarator identifier A::f3<AT>) }; // the class template that is granting friendship for f4 template<class AT> struct C { friend void A::f4(S<AT>); // lookup for AT finds A::AT // (AT is not in the declarator identifier A::f4) }; ``` ### Default argument For a name used in a [default argument](default_arguments "cpp/language/default arguments") in a function declaration, or name used in the expression part of a [member-initializer](initializer_list "cpp/language/initializer list") of a constructor, the function parameter names are found first, before the enclosing block, class, or namespace scopes are examined: ``` class X { int a, b, i, j; public: const int& r; X(int i): r(a), // initializes X::r to refer to X::a b(i), // initializes X::b to the value of the parameter i i(i), // initializes X::i to the value of the parameter i j(this->i) // initializes X::j to the value of X::i {} } int a; int f(int a, int b = a); // error: lookup for a finds the parameter a, not ::a // and parameters are not allowed as default arguments ``` ### Static data member definition For a name used in the definition of a [static data member](static "cpp/language/static"), lookup proceeds the same way as for a name used in the definition of a member function. ``` struct X { static int x; static const int n = 1; // found 1st }; int n = 2; // found 2nd int X::x = n; // finds X::n, sets X::x to 1, not 2 ``` ### Enumerator declaration For a name used in the initializer part of the [enumerator declaration](enum "cpp/language/enum"), previously declared enumerators in the same enumeration are found first, before the unqualified name lookup proceeds to examine the enclosing block, class, or namespace scope. ``` const int RED = 7; enum class color { RED, GREEN = RED + 2, // RED finds color::RED, not ::RED, so GREEN = 2 BLUE = ::RED + 4 // qualified lookup finds ::RED, BLUE = 11 }; ``` ### Catch clause of a function-try block For a name used in the catch-clause of a [function-try-block](function-try-block "cpp/language/function-try-block"), lookup proceeds as if for a name used in the very beginning of the outermost block of the function body (in particular, function parameters are visible, but names declared in that outermost block are not). ``` int n = 3; // found 3rd int f(int n = 2) // found 2nd try { int n = -1; // never found } catch(...) { // int n = 1; // found 1st assert(n == 2); // loookup for n finds function parameter f throw; } ``` ### Overloaded operator For an [operator](expressions#Operators "cpp/language/expressions") used in expression (e.g., `operator+` used in `a+b`), the lookup rules are slightly different from the operator used in an explicit function-call expression such as `operator+(a,b)`: when parsing an expression, two separate lookups are performed: for the non-member operator overloads and for the member operator overloads (for the operators where both forms are permitted). Those sets are then merged with the built-in operator overloads on equal grounds as described in [overload resolution](overload_resolution "cpp/language/overload resolution"). If explicit function call syntax is used, regular unqualified name lookup is performed: ``` struct A {}; void operator+(A, A); // user-defined non-member operator+ struct B { void operator+(B); // user-defined member operator+ void f(); }; A a; void B::f() // definition of a member function of B { operator+(a, a); // error: regular name lookup from a member function // finds the declaration of operator+ in the scope of B // and stops there, never reaching the global scope a + a; // OK: member lookup finds B::operator+, non-member lookup // finds ::operator+(A,A), overload resolution selects ::operator+(A,A) } ``` ### Template definition For a [non-dependent name](dependent_name "cpp/language/dependent name") used in a template definition, unqualified name lookup takes place when the template definition is examined. The binding to the declarations made at that point is not affected by declarations visible at the point of instantiation. For a [dependent name](dependent_name "cpp/language/dependent name") used in a template definition, the lookup is postponed until the template arguments are known, at which time [ADL](adl "cpp/language/adl") examines function declarations with external linkage (until C++11) that are visible from the template definition context as well as in the template instantiation context, while non-ADL lookup only examines function declarations with external linkage (until C++11) that are visible from the template definition context (in other words, adding a new function declaration after template definition does not make it visible except via ADL). The behavior is undefined if there is a better match with external linkage in the namespaces examined by the ADL lookup, declared in some other translation unit, or if the lookup would have been ambiguous if those translation units were examined. In any case, if a base class depends on a template parameter, its scope is not examined by unqualified name lookup (neither at the point of definition nor at the point of instantiation). ``` void f(char); // first declaration of f template<class T> void g(T t) { f(1); // non-dependent name: lookup finds ::f(char) and binds it now f(T(1)); // dependent name: lookup postponed f(t); // dependent name: lookup postponed // dd++; // non-dependent name: lookup finds no declaration } enum E { e }; void f(E); // second declaration of f void f(int); // third declaration of f double dd; void h() { g(e); // instantiates g<E>, at which point // the second and the third uses of the name 'f' // are looked up and find ::f(char) (by lookup) and ::f(E) (by ADL) // then overload resolution chooses ::f(E). // This calls f(char), then f(E) twice g(32); // instantiates g<int>, at which point // the second and the third uses of the name 'f' // are looked up and find ::f(char) only // then overload resolution chooses ::f(char) // This calls f(char) three times } typedef double A; template<class T> class B { typedef int A; }; template<class T> struct X : B<T> { A a; // lookup for A finds ::A (double), not B<T>::A }; ``` Note: see [dependent name lookup rules](dependent_name#Lookup_rules "cpp/language/dependent name") for the reasoning and implications of this rule. ### Template name ### Member of a class template outside of template ### References * C++20 standard (ISO/IEC 14882:2020): + 6.5 Name lookup [basic.lookup] (p: 38-50) + 11.8 Member name lookup [class.member.lookup] (p: 283-285) + 13.8 Name resolution [temp.res] (p: 385-400) * C++17 standard (ISO/IEC 14882:2017): + 6.4 Name lookup [basic.lookup] (p: 50-63) + 13.2 Member name lookup [class.member.lookup] (p: 259-262) + 17.6 Name resolution [temp.res] (p: 375-378) * C++14 standard (ISO/IEC 14882:2014): + 3.4 Name lookup [basic.lookup] (p: 42-56) + 10.2 Member name lookup [class.member.lookup] (p: 233-236) + 14.6 Name resolution [temp.res] (p: 346-359) * C++11 standard (ISO/IEC 14882:2011): + 3.4 Name lookup [basic.lookup] + 10.2 Member name lookup [class.member.lookup] + 14.6 Name resolution [temp.res] * C++98 standard (ISO/IEC 14882:1998): + 3.4 Name lookup [basic.lookup] + 10.2 Member name lookup [class.member.lookup] + 14.6 Name resolution [temp.res] ### Defect Reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 490](https://cplusplus.github.io/CWG/issues/490.html) | C++98 | any name in a template argument in a friendmember function declaration was not lookedup in the scope of the member function's class | only excludes the namesin template arguments inthe declarator identifier | | [CWG 514](https://cplusplus.github.io/CWG/issues/514.html) | C++98 | any unqualified name used in namespacescope was first looked up in that scope | the unqualified names used to define anamespace variable member outside thatnamespace are first looked up in that namespace | ### See also * [Qualified name lookup](qualified_lookup "cpp/language/qualified lookup") * [Scope](scope "cpp/language/scope") * [Argument-dependent lookup](adl "cpp/language/adl") * [Template argument deduction](function_template "cpp/language/function template") * [Overload resolution](overload_resolution "cpp/language/overload resolution")
programming_docs
cpp Character literal Character literal ================= ### Syntax | | | | | --- | --- | --- | | `'`c-char `'` | (1) | | | `u8'`c-char `'` | (2) | (since C++17) | | `u'`c-char `'` | (3) | (since C++11) | | `U'`c-char `'` | (4) | (since C++11) | | `L'`c-char `'` | (5) | | | `'`c-char-sequence `'` | (6) | | | `L'`c-char-sequence `'` | (7) | | | | | | | --- | --- | --- | | c-char | - | either * a basic-c-char, * an escape sequence, as defined in [escape sequences](escape "cpp/language/escape") * a universal character name, as defined in [escape sequences](escape "cpp/language/escape") | | basic-c-char | - | A character from the [source character set](translation_phases#Phase_5 "cpp/language/translation phases") (until C++23)[translation character set](charset#Translation_character_set "cpp/language/charset") (since C++23), except the single-quote `'`, backslash `\`, or new-line character | | c-char-sequence | - | two or more c-chars | ### Explanation 1) Ordinary character literal, e.g. `'a'` or `'\n'` or `'\13'`. Such literal has type `char` and the value equal to the representation of c-char in the [execution character set](charset#Execution_character_set_.28Old_definition.29 "cpp/language/charset") (until C++23)the corresponding code point from [ordinary literal encoding](charset#Code_unit_and_literal_encoding "cpp/language/charset") (since C++23). 2) UTF-8 character literal, e.g. `u8'a'`. Such literal has type `char` (until C++20)`char8_t` (since C++20) and the value equal to ISO 10646 code point value of c-char, provided that the code point value is representable with a single UTF-8 code unit (that is, c-char is in the range 0x0-0x7F, inclusive). 3) UTF-16 character literal, e.g. `u'猫'`, but not `u'🍌'` (`u'\U0001f34c'`). Such literal has type `char16_t` and the value equal to ISO 10646 code point value of c-char, provided that the code point value is representable with a single UTF-16 code unit (that is, c-char is in the range 0x0-0xFFFF, inclusive). 4) UTF-32 character literal, e.g. `U'猫'` or `U'🍌'`. Such literal has type `char32_t` and the value equal to ISO 10646 code point value of c-char. 5) Wide character literal, e.g. `L'β'` or `L'猫'`. Such literal has type `wchar_t` and the value equal to the value of c-char in the execution wide character set (until C++23)the corresponding code point from wide literal encoding (since C++23). 6) Ordinary multicharacter literal, e.g. `'AB'`, is conditionally-supported, has type `int` and implementation-defined value. 7) Wide multicharacter literal, e.g. `L'AB'`, is conditionally-supported, has type `wchar_t` and implementation-defined value. #### Non-encodable characters In (1), if c-char is not a numeric character sequence and is not representable as a single byte in the execution character set, e.g. `'猫'` or `'🍌'`, the character literal is conditionally supported, has type `int` and implementation-defined value. In (2-4), if c-char is not a numeric character sequence and cannot be represented as a single code unit in the associated character encoding, the character literal is ill-formed. In (5), if c-char is not a numeric character sequence and is not representable as a single code unit in the execution wide character set (e.g. a non-BMP value on Windows where `wchar_t` is 16-bit), the character literal is conditionally supported, has type `wchar_t` and implementation-defined value. #### Numeric escape sequences Numeric (octal and hexadecimal) escape sequences can be used for specifying the value of the character. | | | | --- | --- | | If the character literal contains only one numeric escape sequence, and the value specified by the escape sequence is representable by the unsigned version of its type, the character literal has the same value as the specified value (possibly after conversion to the character type). A UTF-*N* character literal can have any value representable by its type. If the value does not correspond to a valid Unicode code point, or if the its corresponding code point is not representable as single code unit in UTF-*N*, it can still be specified by a numeric escape sequence with the value. E.g. `u8'\xff'` is well-formed and equal to `char8_t(0xFF)`. | (since C++23) | | | | | --- | --- | | If the value specified by a numeric escape sequence used in a ordinary or wide character literal is not representable by `char` or `wchar_t` respectively, the value of the character literal is implementation-defined. | (until C++23) | | If the value specified by a numeric escape sequence used in a ordinary or wide character literal with one c-char is representable by the unsigned version of the underlying type of `char` or `wchar_t` respectively, the value of the literal is the integer value of that unsigned integer type and the specified value converted to the type of the literal. Otherwise, the program is ill-formed. | (since C++23) | | | | | --- | --- | | If the value specified by a numeric escape sequence used in a UTF-*N* character literal is not representable by the corresponding `char*N*_t`, the value of the character literal is implementation-defined (until C++17)the program is ill-formed (since C++17). | (since C++11) | ### Notes Multicharacter literals were inherited by C from the B programming language. Although not specified by the C or C++ standard, most compilers (MSVC is a notable exception) implement multicharacter literals as specified in B: the values of each char in the literal initialize successive bytes of the resulting integer, in big-endian zero-padded right-adjusted order, e.g. the value of `'\1'` is `0x00000001` and the value of `'\1\2\3\4'` is `0x01020304`. In C, character constants such as `'a'` or `'\n'` have type `int`, rather than `char`. ### Example ``` #include <cstdint> #include <iomanip> #include <iostream> #include <string_view> template <typename CharT> void dump(std::string_view s, const CharT c) { const uint8_t* data {reinterpret_cast<const uint8_t*>(&c)}; std::cout << s << " \t" << std::hex << std::uppercase << std::setfill('0'); for (auto i {0U}; i != sizeof(CharT); ++i){ std::cout << std::setw(2) << static_cast<unsigned>(data[i]) << ' '; } std::cout << '\n'; } void print(std::string_view str = "") { std::cout << str << '\n'; } int main() { print("Ordinary character literals:"); char c1 = 'a'; dump("'a'", c1); char c2 = '\x2a'; dump("'*'", c2); print("\n" "Ordinary multi-character literals:"); int mc1 = 'ab'; dump("'ab'", mc1); // implementation-defined int mc2 = 'abc'; dump("'abc'", mc2); // implementation-defined print("\n" "Non-encodable character literals:"); int ne1 = '¢'; dump("'¢'", ne1); // implementation-defined int ne2 = '猫'; dump("'猫'", ne2); // implementation-defined int ne3 = '🍌'; dump("'🍌'", ne3); // implementation-defined print("\n" "UTF-8 character literals:"); char8_t C1 = u8'a'; dump("u8'a'", C1); // char8_t C2 = u8'¢'; dump("u8'¢'", C2); // error: ¢ maps to two UTF-8 code units // char8_t C3 = u8'猫'; dump("u8'猫'", C3); // error: 猫 maps to three UTF-8 code units // char8_t C4 = u8'🍌'; dump("u8'🍌'", C4); // error: 🍌 maps to four UTF-8 code units print("\n" "UTF-16 character literals:"); char16_t uc1 = u'a'; dump("u'a'", uc1); char16_t uc2 = u'¢'; dump("u'¢'", uc2); char16_t uc3 = u'猫'; dump("u'猫'", uc3); // char16_t uc4 = u'🍌'; dump("u'🍌'", uc4); // error: 🍌 maps to two UTF-16 code units print("\n" "UTF-32 character literals:"); char32_t Uc1 = U'a'; dump("U'a'", Uc1); char32_t Uc2 = U'¢'; dump("U'¢'", Uc2); char32_t Uc3 = U'猫'; dump("U'猫'", Uc3); char32_t Uc4 = U'🍌'; dump("U'🍌'", Uc4); print("\n" "Wide character literals:"); wchar_t wc1 = L'a'; dump("L'a'", wc1); wchar_t wc2 = L'¢'; dump("L'¢'", wc2); wchar_t wc3 = L'猫'; dump("L'猫'", wc3); wchar_t wc4 = L'🍌'; dump("L'🍌'", wc4); } ``` Possible output: ``` Ordinary character literals: 'a' 61 '*' 2A Ordinary multi-character literals: 'ab' 62 61 00 00 'abc' 63 62 61 00 Non-encodable character literals: '¢' A2 C2 00 00 '猫' AB 8C E7 00 '🍌' 8C 8D 9F F0 UTF-8 character literals: u8'a' 61 UTF-16 character literals: u'a' 61 00 u'¢' A2 00 u'猫' 2B 73 UTF-32 character literals: U'a' 61 00 00 00 U'¢' A2 00 00 00 U'猫' 2B 73 00 00 U'🍌' 4C F3 01 00 Wide character literals: L'a' 61 00 00 00 L'¢' A2 00 00 00 L'猫' 2B 73 00 00 L'🍌' 4C F3 01 00 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 912](https://cplusplus.github.io/CWG/issues/912.html) | C++98 | non-encodable ordinary character literal was unspecified | specified as conditionally-supported | | [CWG 1024](https://cplusplus.github.io/CWG/issues/1024.html) | C++98 | multicharacter literal were required to be supported | made conditionally-supported | | [CWG 1656](https://cplusplus.github.io/CWG/issues/1656.html) | C++98 | meaning of numeric escape sequence in a character literal is unclear | specified | ### See also | | | | --- | --- | | [user-defined literals](user_literal "cpp/language/user literal")(C++11) | literals with user-defined suffix | | [C documentation](https://en.cppreference.com/w/c/language/character_constant "c/language/character constant") for Character constant | cpp const_cast conversion `const_cast` conversion ======================== Converts between types with different cv-qualification. ### Syntax | | | | | --- | --- | --- | | `const_cast` `<` new-type `>` `(` expression `)` | | | Returns a value of type new-type. ### Explanation Only the following conversions can be done with `const_cast`. In particular, only `const_cast` may be used to cast away (remove) constness or volatility. 1) Two possibly multilevel pointers to the same type may be converted between each other, regardless of cv-qualifiers at each level. 2) lvalue of any type `T` may be converted to a lvalue or rvalue reference to the same type `T`, more or less cv-qualified. Likewise, a prvalue of class type or an xvalue of any type may be converted to a more or less cv-qualified rvalue reference. The result of a reference `const_cast` refers to the original object if expression is a glvalue and to the [materialized temporary](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion") otherwise (since C++17). 3) Same rules apply to possibly multilevel pointers to data members and possibly multilevel pointers to arrays of known and unknown bound (arrays to cv-qualified elements are considered to be cv-qualified themselves) (since C++17) 4) null pointer value may be converted to the null pointer value of new-type As with all cast expressions, the result is: | | | | --- | --- | | * an lvalue if new-type is a reference type; * an rvalue otherwise. | (until C++11) | | * an lvalue if new-type is an lvalue reference type or an rvalue reference to function type; * an xvalue if new-type is an rvalue reference to object type; * a prvalue otherwise. | (since C++11) | ### Notes Pointers to functions and pointers to member functions are not subject to `const_cast`. `const_cast` makes it possible to form a reference or pointer to non-const type that is actually referring to a [const object](cv "cpp/language/cv") or a reference or pointer to non-volatile type that is actually referring to a [volatile object](cv "cpp/language/cv"). Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile [glvalue](value_category#glvalue "cpp/language/value category") results in undefined behavior. ### Keywords [`const_cast`](../keyword/const_cast "cpp/keyword/const cast"). ### Example ``` #include <iostream> struct type { int i; type(): i(3) {} void f(int v) const { // this->i = v; // compile error: this is a pointer to const const_cast<type*>(this)->i = v; // OK as long as the type object isn't const } }; int main() { int i = 3; // i is not declared const const int& rci = i; const_cast<int&>(rci) = 4; // OK: modifies i std::cout << "i = " << i << '\n'; type t; // if this was const type t, then t.f(4) would be undefined behavior t.f(4); std::cout << "type::i = " << t.i << '\n'; const int j = 3; // j is declared const [[maybe_unused]] int* pj = const_cast<int*>(&j); // *pj = 4; // undefined behavior [[maybe_unused]] void (type::* pmf)(int) const = &type::f; // pointer to member function // const_cast<void(type::*)(int)>(pmf); // compile error: const_cast does // not work on function pointers } ``` Output: ``` i = 4 type::i = 4 ``` ### See also * [`static_cast`](static_cast "cpp/language/static cast") * [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") * [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") * [explicit cast](explicit_cast "cpp/language/explicit cast") * [implicit conversions](implicit_cast "cpp/language/implicit cast") cpp Array declaration Array declaration ================= Declares an object of array type. ### Syntax An array declaration is any simple declaration whose [declarator](declarations "cpp/language/declarations") has the form. | | | | | --- | --- | --- | | noptr-declarator `[` expr(optional) `]` attr(optional) | | | | | | | | --- | --- | --- | | noptr-declarator | - | any valid declarator, but if it begins with `*`, `&`, or `&&`, it has to be surrounded by parentheses. | | expr | - | an [integral constant expression](constant_expression "cpp/language/constant expression") (until C++14)a [converted constant expression](constant_expression "cpp/language/constant expression") of type `[std::size\_t](../types/size_t "cpp/types/size t")` (since C++14), which evaluates to a value greater than zero | | attr | - | (since C++11) optional list of [attributes](attributes "cpp/language/attributes") | A declaration of the form `T a[N];`, declares `a` as an array object that consists of `N` contiguously allocated objects of type `T`. The elements of an array are numbered `0, …, N - 1`, and may be accessed with the [subscript operator []](operator_member_access#Built-in_subscript_operator "cpp/language/operator member access"), as in `a[0]`, …, `a[N - 1]`. Arrays can be constructed from any [fundamental type](types "cpp/language/types") (except `void`), [pointers](pointer "cpp/language/pointer"), [pointers to members](pointer "cpp/language/pointer"), [classes](classes "cpp/language/classes"), [enumerations](enum "cpp/language/enum"), or from other arrays of known bound (in which case the array is said to be multi-dimensional). In other words, only object types except for array types of unknown bound can be element types of array types. Array types of incomplete element type are also incomplete types. | | | | --- | --- | | The possibly [constrained](constraints "cpp/language/constraints") (since C++20) [`auto`](auto "cpp/language/auto") specifier can be used as array element type in the declaration of a pointer or reference to array, which deduces the element type from the initializer or the function argument (since C++14), e.g. `auto (*p)[42] = &a;` is valid if `a` is an lvalue of type `int[42]`. | (since C++11) | There are no arrays of references or arrays of functions. Applying [cv-qualifiers](cv "cpp/language/cv") to an array type (through typedef or template type manipulation) applies the qualifiers to the element type, but any array type whose elements are of cv-qualified type is considered to have the same cv-qualification. ``` // a and b have the same const-qualified type "array of 5 const char" typedef const char CC; CC a[5] = {}; typedef char CA[5]; const CA b = {}; ``` When used with [new[]-expression](new "cpp/language/new"), the size of an array may be zero; such an array has no elements: ``` int* p = new int[0]; // accessing p[0] or *p is undefined delete[] p; // cleanup still required ``` #### Assignment Objects of array type cannot be modified as a whole: even though they are [lvalues](value_category#lvalue "cpp/language/value category") (e.g. an address of array can be taken), they cannot appear on the left hand side of an assignment operator: ``` int a[3] = {1, 2, 3}, b[3] = {4, 5, 6}; int (*p)[3] = &a; // okay: address of a can be taken a = b; // error: a is an array struct { int c[3]; } s1, s2 = {3, 4, 5}; s1 = s2; // okay: implicity-defined copy assignment operator // can assign data members of array type ``` #### Array-to-pointer decay There is an [implicit conversion](implicit_conversion "cpp/language/implicit conversion") from lvalues and rvalues of array type to rvalues of pointer type: it constructs a pointer to the first element of an array. This conversion is used whenever arrays appear in context where arrays are not expected, but pointers are: ``` #include <iostream> #include <numeric> #include <iterator> void g(int (&a)[3]) { std::cout << a[0] << '\n'; } void f(int* p) { std::cout << *p << '\n'; } int main() { int a[3] = {1, 2, 3}; int* p = a; std::cout << sizeof a << '\n' // prints size of array << sizeof p << '\n'; // prints size of a pointer // where arrays are acceptable, but pointers aren't, only arrays may be used g(a); // okay: function takes an array by reference // g(p); // error for(int n: a) // okay: arrays can be used in range-for loops std::cout << n << ' '; // prints elements of the array // for(int n: p) // error // std::cout << n << ' '; std::iota(std::begin(a), std::end(a), 7); // okay: begin and end take arrays // std::iota(std::begin(p), std::end(p), 7); // error // where pointers are acceptable, but arrays aren't, both may be used: f(a); // okay: function takes a pointer f(p); // okay: function takes a pointer std::cout << *a << '\n' // prints the first element << *p << '\n' // same << *(a + 1) << ' ' << a[1] << '\n' // prints the second element << *(p + 1) << ' ' << p[1] << '\n'; // same } ``` #### Multidimensional arrays When the element type of an array is another array, it is said that the array is multidimensional: ``` // array of 2 arrays of 3 int each int a[2][3] = {{1, 2, 3}, // can be viewed as a 2 × 3 matrix {4, 5, 6}}; // with row-major layout ``` Note that when array-to-pointer decay is applied, a multidimensional array is converted to a pointer to its first element (e.g., a pointer to its first row or to its first plane): array-to-pointer decay is applied only once. ``` int a[2]; // array of 2 int int* p1 = a; // a decays to a pointer to the first element of a int b[2][3]; // array of 2 arrays of 3 int // int** p2 = b; // error: b does not decay to int** int (*p2)[3] = b; // b decays to a pointer to the first 3-element row of b int c[2][3][4]; // array of 2 arrays of 3 arrays of 4 int // int*** p3 = c; // error: c does not decay to int*** int (*p3)[3][4] = c; // c decays to a pointer to the first 3 × 4-element plane of c ``` #### Arrays of unknown bound If expr is omitted in the declaration of an array, the type declared is "array of unknown bound of T", which is a kind of [incomplete type](incomplete_type "cpp/language/incomplete type"), except when used in a declaration with an [aggregate initializer](aggregate_initialization "cpp/language/aggregate initialization"): ``` extern int x[]; // the type of x is "array of unknown bound of int" int a[] = {1, 2, 3}; // the type of a is "array of 3 int" ``` Because array elements cannot be arrays of unknown bound, multidimensional arrays cannot have unknown bound in a dimension other than the first: ``` extern int a[][2]; // okay: array of unknown bound of arrays of 2 int extern int b[2][]; // error: array has incomplete element type ``` If there is a preceding declaration of the entity in the same scope in which the bound was specified, an omitted array bound is taken to be the same as in that earlier declaration, and similarly for the definition of a static data member of a class: ``` extern int x[10]; struct S { static int y[10]; }; int x[]; // OK: bound is 10 int S::y[]; // OK: bound is 10 void f() { extern int x[]; int i = sizeof(x); // error: incomplete object type } ``` References and pointers to arrays of unknown bound can be formed, but cannot be initialized or assigned from arrays and pointers to arrays of known bound. Note that in the C programming language, pointers to arrays of unknown bound are compatible with pointers to arrays of known bound and are thus convertible and assignable in both directions. ``` extern int a1[]; int (&r1)[] = a1; // okay int (*p1)[] = &a1; // okay int (*q)[2] = &a1; // error (but okay in C) int a2[] = {1, 2, 3}; int (&r2)[] = a2; // error int (*p2)[] = &a2; // error (but okay in C) ``` Pointers to arrays of unknown bound cannot participate in [pointer arithmetic](operator_arithmetic#Additive_operators "cpp/language/operator arithmetic") and cannot be used on the left of the [subscript operator](operator_member_access#Built-in_subscript_operator "cpp/language/operator member access"), but can be dereferenced. #### Array rvalues Although arrays cannot be returned from functions by value and cannot be targets of most cast expressions, array [prvalues](value_category "cpp/language/value category") may be formed by using a type alias to construct an array temporary using [brace-initialized functional cast](explicit_cast "cpp/language/explicit cast"). | | | | --- | --- | | Like class prvalues, array prvalues convert to xvalues by [temporary materialization](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion") when evaluated. | (since C++17) | Array [xvalues](value_category "cpp/language/value category") may be formed directly by accessing an array member of a class rvalue or by using `std::move` or another cast or function call that returns an rvalue reference. ``` #include <iostream> #include <type_traits> #include <utility> void f(int (&&x)[2][3]) { std::cout << sizeof x << '\n'; } struct X { int i[2][3]; } x; template<typename T> using identity = T; int main() { std::cout << sizeof X().i << '\n'; // size of the array f(X().i); // okay: binds to xvalue // f(x.i); // error: cannot bind to lvalue int a[2][3]; f(std::move(a)); // okay: binds to xvalue using arr_t = int[2][3]; f(arr_t{}); // okay: binds to prvalue f(identity<int[][3]>{{1, 2, 3}, {4, 5, 6}}); // okay: binds to prvalue } ``` Output: ``` 24 24 24 24 24 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 393](https://cplusplus.github.io/CWG/issues/393.html) | C++98 | a pointer or reference to an array of unknownbound could not be a function parameter | allowed | | [CWG 619](https://cplusplus.github.io/CWG/issues/619.html) | C++98 | when omitted, the bound of an array couldnot be inferred from a previous declaration | inference allowed | | [CWG 2099](https://cplusplus.github.io/CWG/issues/2099.html) | C++98 | the bound of an array static data member couldnot be omitted even if an initializer is provided | omission allowed | | [CWG 2397](https://cplusplus.github.io/CWG/issues/2397.html) | C++11 | `auto` could not be used as element type | allowed | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/array "c/language/array") for Array declaration |
programming_docs
cpp Coroutines (C++20) Coroutines (C++20) ================== A coroutine is a function that can suspend execution to be resumed later. Coroutines are stackless: they suspend execution by returning to the caller and the data that is required to resume execution is stored separately from the stack. This allows for sequential code that executes asynchronously (e.g. to handle non-blocking I/O without explicit callbacks), and also supports algorithms on lazy-computed infinite sequences and other uses. A function is a coroutine if its definition does any of the following: * uses the `co_await` operator to suspend execution until resumed ``` task<> tcp_echo_server() { char data[1024]; while (true) { size_t n = co_await socket.async_read_some(buffer(data)); co_await async_write(socket, buffer(data, n)); } } ``` * uses the keyword `co_yield` to suspend execution returning a value ``` generator<int> iota(int n = 0) { while(true) co_yield n++; } ``` * uses the keyword `co_return` to complete execution returning a value ``` lazy<int> f() { co_return 7; } ``` Every coroutine must have a return type that satisfies a number of requirements, noted below. ### Restrictions Coroutines cannot use [variadic arguments](variadic_arguments "cpp/language/variadic arguments"), plain [return](return "cpp/language/return") statements, or [placeholder return types](function "cpp/language/function") ([`auto`](auto "cpp/language/auto") or `Concept`). [Consteval functions](consteval "cpp/language/consteval"), [constexpr functions](constexpr "cpp/language/constexpr"), [constructors](constructor "cpp/language/constructor"), [destructors](destructor "cpp/language/destructor"), and the [main function](main_function "cpp/language/main function") cannot be coroutines. ### Execution Each coroutine is associated with. * the *promise object*, manipulated from inside the coroutine. The coroutine submits its result or exception through this object. * the *coroutine handle*, manipulated from outside the coroutine. This is a non-owning handle used to resume execution of the coroutine or to destroy the coroutine frame. * the *coroutine state*, which is an internal, heap-allocated (unless the allocation is optimized out), object that contains + the promise object + the parameters (all copied by value) + some representation of the current suspension point, so that resume knows where to continue and destroy knows what local variables were in scope + local variables and temporaries whose lifetime spans the current suspension point When a coroutine begins execution, it performs the following: * allocates the coroutine state object using `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)` (see below) * copies all function parameters to the coroutine state: by-value parameters are moved or copied, by-reference parameters remain references (and so may become dangling if the coroutine is resumed after the lifetime of referred object ends) ``` #include <coroutine> #include <iostream> struct promise; struct coroutine : std::coroutine_handle<promise> { using promise_type = struct promise; }; struct promise { coroutine get_return_object() { return {coroutine::from_promise(*this)}; } std::suspend_always initial_suspend() noexcept { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void return_void() {} void unhandled_exception() {} }; struct S { int i; coroutine f() { std::cout << i; co_return; } }; void bad1() { coroutine h = S{0}.f(); // S{0} destroyed h.resume(); // resumed coroutine executes std::cout << i, uses S::i after free h.destroy(); } coroutine bad2() { S s{0}; return s.f(); // returned coroutine can't be resumed without committing use after free } void bad3() { coroutine h = [i = 0]() -> coroutine { // a lambda that's also a coroutine std::cout << i; co_return; }(); // immediately invoked // lambda destroyed h.resume(); // uses (anonymous lambda type)::i after free h.destroy(); } void good() { coroutine h = [](int i) -> coroutine { // make i a coroutine parameter std::cout << i; co_return; }(0); // lambda destroyed h.resume(); // no problem, i has been copied to the coroutine frame as a by-value parameter h.destroy(); } ``` * calls the constructor for the promise object. If the promise type has a constructor that takes all coroutine parameters, that constructor is called, with post-copy coroutine arguments. Otherwise the default constructor is called. * calls `promise.get_return_object()` and keeps the result in a local variable. The result of that call will be returned to the caller when the coroutine first suspends. Any exceptions thrown up to and including this step propagate back to the caller, not placed in the promise. * calls `promise.initial_suspend()` and `co_await`s its result. Typical Promise types either return a `suspend_always`, for lazily-started coroutines, or `suspend_never`, for eagerly-started coroutines. * when `co_await promise.initial_suspend()` resumes, starts executing the body of the coroutine When a coroutine reaches a suspension point. * the return object obtained earlier is returned to the caller/resumer, after implicit conversion to the return type of the coroutine, if necessary. When a coroutine reaches the `co_return` statement, it performs the following: * calls `promise.return_void()` for + `co_return;` + `co_return expr` where expr has type void + falling off the end of a void-returning coroutine. The behavior is undefined if the Promise type has no `Promise::return_void()` member function in this case. * or calls `promise.return_value(expr)` for `co_return expr` where expr has non-void type * destroys all variables with automatic storage duration in reverse order they were created. * calls `promise.final_suspend()` and `co_await`s the result. If the coroutine ends with an uncaught exception, it performs the following: * catches the exception and calls `promise.unhandled_exception()` from within the catch-block * calls `promise.final_suspend()` and `co_await`s the result (e.g. to resume a continuation or publish a result). It's undefined behavior to resume a coroutine from this point. When the coroutine state is destroyed either because it terminated via co\_return or uncaught exception, or because it was destroyed via its handle, it does the following: * calls the destructor of the promise object. * calls the destructors of the function parameter copies. * calls `[operator delete](http://en.cppreference.com/w/cpp/memory/new/operator_delete)` to free the memory used by the coroutine state * transfers execution back to the caller/resumer. ### Heap allocation coroutine state is allocated on the heap via non-array `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)`. If the `Promise` type defines a class-level replacement, it will be used, otherwise global `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)` will be used. If the `Promise` type defines a placement form of `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)` that takes additional parameters, and they match an argument list where the first argument is the size requested (of type `[std::size\_t](../types/size_t "cpp/types/size t")`) and the rest are the coroutine function arguments, those arguments will be passed to `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)` (this makes it possible to use [leading-allocator-convention](../memory/uses_allocator#Uses-allocator_construction "cpp/memory/uses allocator") for coroutines). The call to `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)` can be optimized out (even if custom allocator is used) if. * The lifetime of the coroutine state is strictly nested within the lifetime of the caller, and * the size of coroutine frame is known at the call site in that case, coroutine state is embedded in the caller's stack frame (if the caller is an ordinary function) or coroutine state (if the caller is a coroutine). If allocation fails, the coroutine throws `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")`, unless the Promise type defines the member function `Promise::get_return_object_on_allocation_failure()`. If that member function is defined, allocation uses the `nothrow` form of `[operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)` and on allocation failure, the coroutine immediately returns the object obtained from `Promise::get_return_object_on_allocation_failure()` to the caller. ### Promise The Promise type is determined by the compiler from the return type of the coroutine using `[std::coroutine\_traits](../coroutine/coroutine_traits "cpp/coroutine/coroutine traits")`. Formally, let `R` and `Args...` denote the return type and parameter type list of a coroutine respectively, `ClassT` and `/*cv-qual*/` (if any) denote the class type to which the coroutine belongs and its cv-qualification respectively if it is defined as a non-static member function, its `Promise` type is determined by: * `[std::coroutine\_traits](http://en.cppreference.com/w/cpp/coroutine/coroutine_traits)<R, Args...>::promise\_type`, if the coroutine is not defined as a non-static member function, * `[std::coroutine\_traits](http://en.cppreference.com/w/cpp/coroutine/coroutine_traits)<R, ClassT /\*cv-qual\*/&, Args...>::promise\_type`, if the coroutine is defined as a non-static member function that is not rvalue-reference-qualified, * `[std::coroutine\_traits](http://en.cppreference.com/w/cpp/coroutine/coroutine_traits)<R, ClassT /\*cv-qual\*/&&, Args...>::promise\_type`, if the coroutine is defined as a non-static member function that is rvalue-reference-qualified. For example: * If the coroutine is defined as `task<float> foo([std::string](http://en.cppreference.com/w/cpp/string/basic_string) x, bool flag);`, then its `Promise` type is `[std::coroutine\_traits](http://en.cppreference.com/w/cpp/coroutine/coroutine_traits)<task<float>, [std::string](http://en.cppreference.com/w/cpp/string/basic_string), bool>::promise\_type`. * If the coroutine is defined as `task<void> my_class::method1(int x) const;`, its `Promise` type is `[std::coroutine\_traits](http://en.cppreference.com/w/cpp/coroutine/coroutine_traits)<task<void>, const my_class&, int>::promise\_type`. * If the coroutine is defined as `task<void> my_class::method1(int x) &&;`, its `Promise` type is `[std::coroutine\_traits](http://en.cppreference.com/w/cpp/coroutine/coroutine_traits)<task<void>, my_class&&, int>::promise\_type`. ### co\_await The unary operator `co_await` suspends a coroutine and returns control to the caller. Its operand is an expression whose type must either define `operator co_await`, or be convertible to such type by means of the current coroutine's `Promise::await_transform`. | | | | | --- | --- | --- | | `co_await` expr | | | First, expr is converted to an awaitable as follows: * if expr is produced by an initial suspend point, a final suspend point, or a yield expression, the awaitable is expr, as-is. * otherwise, if the current coroutine's Promise type has the member function `await_transform`, then the awaitable is `promise.await_transform(expr)` * otherwise, the awaitable is expr, as-is. Then, the awaiter object is obtained, as follows: * if overload resolution for `operator co_await` gives a single best overload, the awaiter is the result of that call (`awaitable.operator co_await()` for member overload, `operator co_await(static_cast<Awaitable&&>(awaitable))` for the non-member overload) * otherwise, if overload resolution finds no operator co\_await, the awaiter is awaitable, as-is * otherwise, if overload resolution is ambiguous, the program is ill-formed If the expression above is a prvalue, the awaiter object is a temporary [materialized](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion") from it. Otherwise, if the expression above is an glvalue, the awaiter object is the object to which it refers. Then, `awaiter.await_ready()` is called (this is a short-cut to avoid the cost of suspension if it's known that the result is ready or can be completed synchronously). If its result, contextually-converted to bool is `false` then. The coroutine is suspended (its coroutine state is populated with local variables and current suspension point). `awaiter.await_suspend(handle)` is called, where handle is the coroutine handle representing the current coroutine. Inside that function, the suspended coroutine state is observable via that handle, and it's this function's responsibility to schedule it to resume on some executor, or to be destroyed (returning false counts as scheduling) * if await\_suspend returns void, control is immediately returned to the caller/resumer of the current coroutine (this coroutine remains suspended), otherwise * if await\_suspend returns bool, + the value `true` returns control to the caller/resumer of the current coroutine + the value `false` resumes the current coroutine. * if await\_suspend returns a coroutine handle for some other coroutine, that handle is resumed (by a call to `handle.resume()`) (note this may chain to eventually cause the current coroutine to resume) * if await\_suspend throws an exception, the exception is caught, the coroutine is resumed, and the exception is immediately re-thrown Finally, `awaiter.await_resume()` is called (whether the coroutine was suspended or not), and its result is the result of the whole `co_await expr` expression. If the coroutine was suspended in the co\_await expression, and is later resumed, the resume point is immediately before the call to `awaiter.await_resume()`. Note that because the coroutine is fully suspended before entering `awaiter.await_suspend()`, that function is free to transfer the coroutine handle across threads, with no additional synchronization. For example, it can put it inside a callback, scheduled to run on a threadpool when async I/O operation completes. In that case, since the current coroutine may have been resumed and thus executed the awaiter object's destructor, all concurrently as `await_suspend()` continues its execution on the current thread, `await_suspend()` should treat `*this` as destroyed and not access it after the handle was published to other threads. ### Example ``` #include <coroutine> #include <iostream> #include <stdexcept> #include <thread> auto switch_to_new_thread(std::jthread& out) { struct awaitable { std::jthread* p_out; bool await_ready() { return false; } void await_suspend(std::coroutine_handle<> h) { std::jthread& out = *p_out; if (out.joinable()) throw std::runtime_error("Output jthread parameter not empty"); out = std::jthread([h] { h.resume(); }); // Potential undefined behavior: accessing potentially destroyed *this // std::cout << "New thread ID: " << p_out->get_id() << '\n'; std::cout << "New thread ID: " << out.get_id() << '\n'; // this is OK } void await_resume() {} }; return awaitable{&out}; } struct task{ struct promise_type { task get_return_object() { return {}; } std::suspend_never initial_suspend() { return {}; } std::suspend_never final_suspend() noexcept { return {}; } void return_void() {} void unhandled_exception() {} }; }; task resuming_on_new_thread(std::jthread& out) { std::cout << "Coroutine started on thread: " << std::this_thread::get_id() << '\n'; co_await switch_to_new_thread(out); // awaiter destroyed here std::cout << "Coroutine resumed on thread: " << std::this_thread::get_id() << '\n'; } int main() { std::jthread out; resuming_on_new_thread(out); } ``` Possible output: ``` Coroutine started on thread: 139972277602112 New thread ID: 139972267284224 Coroutine resumed on thread: 139972267284224 ``` Note: the awaiter object is part of coroutine state (as a temporary whose lifetime crosses a suspension point) and is destroyed before the co\_await expression finishes. It can be used to maintain per-operation state as required by some async I/O APIs without resorting to additional heap allocations. The standard library defines two trivial awaitables: `[std::suspend\_always](../coroutine/suspend_always "cpp/coroutine/suspend always")` and `[std::suspend\_never](../coroutine/suspend_never "cpp/coroutine/suspend never")`. ### co\_yield Yield-expression returns a value to the caller and suspends the current coroutine: it is the common building block of resumable generator functions. | | | | | --- | --- | --- | | `co_yield` expr | | | | `co_yield` braced-init-list | | | It is equivalent to. ``` co_await promise.yield_value(expr) ``` A typical generator's `yield_value` would store (copy/move or just store the address of, since the argument's lifetime crosses the suspension point inside the `co_await`) its argument into the generator object and return `[std::suspend\_always](../coroutine/suspend_always "cpp/coroutine/suspend always")`, transferring control to the caller/resumer. ``` #include <coroutine> #include <exception> #include <iostream> template<typename T> struct Generator { // The class name 'Generator' is our choice and it is not required for coroutine magic. // Compiler recognizes coroutine by the presence of 'co_yield' keyword. // You can use name 'MyGenerator' (or any other name) instead as long as you include // nested struct promise_type with 'MyGenerator get_return_object()' method. // Note: You need to adjust class constructor/destructor names too when choosing to // rename class. struct promise_type; using handle_type = std::coroutine_handle<promise_type>; struct promise_type { // required T value_; std::exception_ptr exception_; Generator get_return_object() { return Generator(handle_type::from_promise(*this)); } std::suspend_always initial_suspend() { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void unhandled_exception() { exception_ = std::current_exception(); } // saving // exception template<std::convertible_to<T> From> // C++20 concept std::suspend_always yield_value(From &&from) { value_ = std::forward<From>(from); // caching the result in promise return {}; } void return_void() {} }; handle_type h_; Generator(handle_type h) : h_(h) {} ~Generator() { h_.destroy(); } explicit operator bool() { fill(); // The only way to reliably find out whether or not we finished coroutine, // whether or not there is going to be a next value generated (co_yield) in // coroutine via C++ getter (operator () below) is to execute/resume coroutine // until the next co_yield point (or let it fall off end). // Then we store/cache result in promise to allow getter (operator() below to // grab it without executing coroutine). return !h_.done(); } T operator()() { fill(); full_ = false; // we are going to move out previously cached // result to make promise empty again return std::move(h_.promise().value_); } private: bool full_ = false; void fill() { if (!full_) { h_(); if (h_.promise().exception_) std::rethrow_exception(h_.promise().exception_); // propagate coroutine exception in called context full_ = true; } } }; Generator<uint64_t> fibonacci_sequence(unsigned n) { if (n==0) co_return; if (n>94) throw std::runtime_error("Too big Fibonacci sequence. Elements would overflow."); co_yield 0; if (n==1) co_return; co_yield 1; if (n==2) co_return; uint64_t a=0; uint64_t b=1; for (unsigned i = 2; i < n; i++) { uint64_t s=a+b; co_yield s; a=b; b=s; } } int main() { try { auto gen = fibonacci_sequence(10); // max 94 before uint64_t overflows for (int j=0; gen; j++) std::cout << "fib("<<j <<")=" << gen() << '\n'; } catch (const std::exception& ex) { std::cerr << "Exception: " << ex.what() << '\n'; } catch (...) { std::cerr << "Unknown exception.\n"; } } ``` Output: ``` fib(0)=0 fib(1)=1 fib(2)=1 fib(3)=2 fib(4)=3 fib(5)=5 fib(6)=8 fib(7)=13 fib(8)=21 fib(9)=34 ``` ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_coroutine`](../feature_test#Library_features "cpp/feature test") | ### Library support [Coroutine support library](../coroutine "cpp/coroutine") defines several types providing compile and run-time support for coroutines. ### External links * David Mazières, 2021 - [Tutorial on C++20 coroutines](https://www.scs.stanford.edu/~dm/blog/c++-coroutines.html)
programming_docs
cpp Bit-field Bit-field ========= Declares a class data member with explicit size, in bits. Adjacent bit-field members may (or may not) be packed to share and straddle the individual bytes. A bit-field declaration is a [class data member declaration](data_members "cpp/language/data members") which uses the following declarator: | | | | | --- | --- | --- | | identifier(optional) attr(optional) `:` size | (1) | | | identifier(optional) attr(optional) `:` size brace-or-equal-initializer | (2) | (since C++20) | The *type* of the bit-field is introduced by the decl-specifier-seq of the [declaration syntax](declarations "cpp/language/declarations"). | | | | | --- | --- | --- | | attr | - | (since C++11) sequence of any number of [attributes](attributes "cpp/language/attributes") | | identifier | - | the name of the bit-field that is being declared. The name is optional: unnamed bit-fields introduce the specified number of [padding bits](object#Object_representation_and_value_representation "cpp/language/object"). | | size | - | an [integral constant expression](constant_expression#Integral_constant_expression "cpp/language/constant expression") with a value greater or equal to zero. When greater than zero, this is the number of bits that this bit-field will occupy. The value zero is only allowed for nameless bitfields and has [special meaning](#zero_size). | | brace-or-equal-initializer | - | [default member initializer](data_members#Member_initialization "cpp/language/data members") to be used with this bit-field | ### Explanation The type of a bit-field can only be integral or (possibly cv-qualified) enumeration type, an unnamed bit-field cannot be declared with a cv-qualified type. A bit-field cannot be a [static data member](static "cpp/language/static"). There are no bit-field [prvalues](value_category "cpp/language/value category"): lvalue-to-rvalue conversion always produces an object of the underlying type of the bit-field. The number of bits in a bit-field sets the limit to the range of values it can hold: ``` #include <iostream> struct S { // three-bit unsigned field, allowed values are 0...7 unsigned int b : 3; }; int main() { S s = {6}; ++s.b; // store the value 7 in the bit-field std::cout << s.b << '\n'; ++s.b; // the value 8 does not fit in this bit-field std::cout << s.b << '\n'; // formally implementation-defined, typically 0 } ``` Possible output: ``` 7 0 ``` Multiple adjacent bit-fields are usually packed together (although this behavior is implementation-defined): ``` #include <iostream> struct S { // will usually occupy 2 bytes: // 3 bits: value of b1 // 2 bits: unused // 6 bits: value of b2 // 2 bits: value of b3 // 3 bits: unused unsigned char b1 : 3, : 2, b2 : 6, b3 : 2; }; int main() { std::cout << sizeof(S) << '\n'; // usually prints 2 } ``` Possible output: ``` 2 ``` The special unnamed bit-field of size zero can be forced to break up padding. It specifies that the next bit-field begins at the beginning of its allocation unit: ``` #include <iostream> struct S { // will usually occupy 2 bytes: // 3 bits: value of b1 // 5 bits: unused // 2 bits: value of b2 // 6 bits: unused unsigned char b1 : 3; unsigned char :0; // start a new byte unsigned char b2 : 2; }; int main() { std::cout << sizeof(S) << '\n'; // usually prints 2 // would usually print 1 if not for // the padding break in line 11 } ``` Possible output: ``` 2 ``` If the specified size of the bit-field is greater than the size of its type, the value is limited by the type: a `[std::uint8\_t](http://en.cppreference.com/w/cpp/types/integer) b : 1000;` would still hold values between 0 and 255. the extra bits are [padding bits](object#Object_representation_and_value_representation "cpp/language/object"). Because bit-fields do not necessarily begin at the beginning of a byte, address of a bit-field cannot be taken. Pointers and non-const references to bit-fields are not possible. When [initializing a const reference](reference_initialization "cpp/language/reference initialization") from a bit-field, a temporary is created (its type is the type of the bit-field), copy initialized with the value of the bit-field, and the reference is bound to that temporary. | | | | --- | --- | | There are no [default member initializers](data_members#Member_initialization "cpp/language/data members") for bit-fields: `int b : 1 = 0;` and `int b : 1 {0}` are ill-formed. | (until C++20) | | In case of ambiguity between the size of the bit-field and the default member initializer, the longest sequence of tokens that forms a valid size is chosen: ``` int a; const int b = 0; struct S { // simple cases int x1 : 8 = 42; // OK; "= 42" is brace-or-equal-initializer int x2 : 8 { 42 }; // OK; "{ 42 }" is brace-or-equal-initializer // ambiguities int y1 : true ? 8 : a = 42; // OK; brace-or-equal-initializer is absent int y2 : true ? 8 : b = 42; // error: cannot assign to const int int y3 : (true ? 8 : b) = 42; // OK; "= 42" is brace-or-equal-initializer int z : 1 || new int { 0 }; // OK; brace-or-equal-initializer is absent }; ``` | (since C++20) | ### Notes The following properties of bit-fields are *implementation-defined*: * The value that results from assigning or initializing a signed bit-field with a value out of range, or from incrementing a signed bit-field past its range. * Everything about the actual allocation details of bit-fields within the class object + For example, on some platforms, bit-fields don't straddle bytes, on others they do + Also, on some platforms, bit-fields are packed left-to-right, on others right-to-left In the C programming language, the width of a bit-field cannot exceed the width of the underlying type, and whether `int` bit-fields that are not explicitly `signed` or `unsigned` are signed or unsigned is implementation-defined. For example, `int b:3;` may have the range of values `0..7` or `-4..3` in C, but only the latter choice is allowed in C++. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 324](https://cplusplus.github.io/CWG/issues/324.html) | C++98 | it was unspecified whether the return valueof an assignment to a bit-field is a bit-field | added bit-field specifications foroperators which may return lvalues | | [CWG 739](https://cplusplus.github.io/CWG/issues/739.html) | C++98 | signedness of bit-fields that are neither declared`signed` nor `unsigned` were implementation-defined | consistent with underlying types | | [CWG 2229](https://cplusplus.github.io/CWG/issues/2229.html) | C++98 | unnamed bit-fields could be declared with a cv-qualified type | prohibited | | [CWG 2511](https://cplusplus.github.io/CWG/issues/2511.html) | C++98 | cv-qualifications were not allowed in bit-field types | bit-fields can have cv-qualifiedenumeration types | ### References * C++20 standard (ISO/IEC 14882:2020): + 11.4.9 Bit-fields [class.bit] * C++17 standard (ISO/IEC 14882:2017): + 12.2.4 Bit-fields [class.bit] * C++14 standard (ISO/IEC 14882:2014): + 9.6 Bit-fields [class.bit] * C++11 standard (ISO/IEC 14882:2011): + 9.6 Bit-fields [class.bit] * C++03 standard (ISO/IEC 14882:2003): + 9.6 Bit-fields [class.bit] * C++98 standard (ISO/IEC 14882:1998): + 9.6 Bit-fields [class.bit] ### See also | | | | --- | --- | | [bitset](../utility/bitset "cpp/utility/bitset") | implements constant length bit array (class template) | | [vector<bool>](../container/vector_bool "cpp/container/vector bool") | space-efficient dynamic bitset (class template specialization) | | [**Bit manipulation**](../numeric#Bit_manipulation_.28since_C.2B.2B20.29 "cpp/numeric") (C++20) | utilities to access, manipulate, and process individual bits and bit sequences | | [C documentation](https://en.cppreference.com/w/c/language/bit_field "c/language/bit field") for Bit-fields | cpp alignas specifier (since C++11) `alignas` specifier (since C++11) ================================== Specifies the [alignment requirement](object#Alignment "cpp/language/object") of a type or an object. ### Syntax | | | | | --- | --- | --- | | `alignas(` expression `)` | | | | `alignas(` type-id `)` | | | | `alignas(` pack `...` `)` | | | 1) expression must be an [integral constant expression](constant_expression#Integral_constant_expression "cpp/language/constant expression") that evaluates to zero, or to a valid value for an [alignment](object#Alignment "cpp/language/object") or extended alignment. 2) Equivalent to `alignas(alignof(type-id))` 3) Equivalent to multiple alignas specifiers applied to the same declaration, one for each member of the [parameter pack](parameter_pack "cpp/language/parameter pack"), which can be either type or non-type parameter pack. ### Explanation The `alignas` specifier may be applied to: * the declaration or definition of a [class](classes "cpp/language/classes"); * the declaration of a non-bitfield class data member; * the declaration of a variable, except that it cannot be applied to the following: + a function parameter; + the exception parameter of a catch clause. The object or the type declared by such a declaration will have its [alignment requirement](object#Alignment "cpp/language/object") equal to the strictest (largest) non-zero expression of all `alignas` specifiers used in the declaration, unless it would weaken the natural alignment of the type. If the strictest (largest) `alignas` on a declaration is weaker than the alignment it would have without any `alignas` specifiers (that is, weaker than its natural alignment or weaker than `alignas` on another declaration of the same object or type), the program is ill-formed: ``` struct alignas(8) S {}; struct alignas(1) U { S s; }; // error: alignment of U would have been 8 without alignas(1) ``` Invalid non-zero alignments, such as `alignas(3)` are ill-formed. Valid non-zero alignments that are weaker than another `alignas` on the same declaration are ignored. `alignas(0)` is always ignored. ### Notes As of the ISO C11 standard, the C language has the `_Alignas` keyword and defines `alignas` as a preprocessor macro expanding to the keyword in the header [`<stdalign.h>`](https://en.cppreference.com/w/c/types "c/types"). In C++, this is a keyword, and. | | | | --- | --- | | the headers [`<stdalign.h>`](../header#Meaningless_C_headers "cpp/header") and [`<cstdalign>`](../header/cstdalign "cpp/header/cstdalign") do not define such macro. They do, however, define the macro constant `__alignas_is_defined`. | (until C++20) | | the header [`<stdalign.h>`](../header#Meaningless_C_headers "cpp/header") does not define such macro. It does, however, define the macro constant `__alignas_is_defined`. | (since C++20) | ### Keywords [`alignas`](../keyword/alignas "cpp/keyword/alignas"). ### Example ``` // every object of type struct_float will be aligned to alignof(float) boundary // (usually 4): struct alignas(float) struct_float { // your definition here }; // every object of type sse_t will be aligned to 32-byte boundary: struct alignas(32) sse_t { float sse_data[4]; }; // the array "cacheline" will be aligned to 64-byte boundary: alignas(64) char cacheline[64]; #include <iostream> int main() { struct default_aligned { float data[4]; } a, b, c; sse_t x, y, z; std::cout << "alignof(struct_float) = " << alignof(struct_float) << '\n' << "sizeof(sse_t) = " << sizeof(sse_t) << '\n' << "alignof(sse_t) = " << alignof(sse_t) << '\n' << "alignof(cacheline) = " << alignof(alignas(64) char[64]) << '\n' << std::hex << std::showbase << "&a: " << &a << '\n' << "&b: " << &b << '\n' << "&c: " << &c << '\n' << "&x: " << &x << '\n' << "&y: " << &y << '\n' << "&z: " << &z << '\n'; } ``` Possible output: ``` alignof(struct_float) = 4 sizeof(sse_t) = 32 alignof(sse_t) = 32 alignof(cacheline) = 64 &a: 0x7fffcec89930 &b: 0x7fffcec89940 &c: 0x7fffcec89950 &x: 0x7fffcec89960 &y: 0x7fffcec89980 &z: 0x7fffcec899a0 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1437](https://cplusplus.github.io/CWG/issues/1437.html) | C++11 | alignas could be used in alias declarations | prohibited | | [CWG 2354](https://cplusplus.github.io/CWG/issues/2354.html) | C++11 | alignas could be applied to the declaration of an enumeration | prohibited | ### See also | | | | --- | --- | | [`alignof` operator](alignof "cpp/language/alignof")(C++11) | queries alignment requirements of a type | | [alignment\_of](../types/alignment_of "cpp/types/alignment of") (C++11) | obtains the type's alignment requirements (class template) | | [C documentation](https://en.cppreference.com/w/c/language/_Alignas "c/language/ Alignas") for `_Alignas` | cpp static_assert declaration (since C++11) `static_assert` declaration (since C++11) ========================================== Performs compile-time assertion checking. ### Syntax | | | | | --- | --- | --- | | `static_assert` `(` bool-constexpr `,` message `)` | | (since C++11) | | `static_assert` `(` bool-constexpr `)` | | (since C++17) | ### Explanation | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | bool-constexpr | - | | | | | --- | --- | | a [contextually converted constant expression of type `bool`](constant_expression#Converted_constant_expression "cpp/language/constant expression"). | (until C++23) | | an expression [contextually converted to `bool`](implicit_conversion#Contextual_conversions "cpp/language/implicit conversion") where the conversion is a [constant expression](constant_expression "cpp/language/constant expression"). | (since C++23) | | | message | - | optional (since C++17) string literal that will appear as compiler error if bool-constexpr is false, except that characters not in the [basic source character set](charset#Basic_source_character_set "cpp/language/charset") are not required to appear (until C++23). | A static assert declaration may appear at namespace and block scope (as a [block declaration](declarations "cpp/language/declarations")) and inside a class body (as a [member declaration](class "cpp/language/class")). If bool-constexpr returns `true`, this declaration has no effect. Otherwise a compile-time error is issued, and the text of message, if any, is included in the diagnostic message. | | | | --- | --- | | message can be omitted. | (since C++17) | | | | | --- | --- | | Built-in conversions are not allowed, except for non-[narrowing](list_initialization#Narrowing_conversions "cpp/language/list initialization") [integral conversions](implicit_conversion#Integral_conversions "cpp/language/implicit conversion") to `bool`. | (until C++23) | ### Note Since message has to be a string literal, it cannot contain dynamic information or even a [constant expression](constant_expression "cpp/language/constant expression") that is not a string literal itself. In particular, it cannot contain the [name](name "cpp/language/name") of the [template type argument](template_parameters "cpp/language/template parameters"). ### Example ``` #include <type_traits> static_assert(03301 == 1729); // since C++17 the message string is optional template <class T> void swap(T& a, T& b) noexcept { static_assert(std::is_copy_constructible_v<T>, "Swap requires copying"); static_assert(std::is_nothrow_copy_constructible_v<T> && std::is_nothrow_copy_assignable_v<T>, "Swap requires nothrow copy/assign"); auto c = b; b = a; a = c; } template <class T> struct data_structure { static_assert(std::is_default_constructible_v<T>, "Data structure requires default-constructible elements"); }; struct no_copy { no_copy ( const no_copy& ) = delete; no_copy () = default; }; struct no_default { no_default () = delete; }; int main() { int a, b; swap(a, b); no_copy nc_a, nc_b; swap(nc_a, nc_b); // 1 [[maybe_unused]] data_structure<int> ds_ok; [[maybe_unused]] data_structure<no_default> ds_error; // 2 } ``` Possible output: ``` 1: error: static assertion failed: Swap requires copying 2: error: static assertion failed: Data structure requires default-constructible elements ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 2039](https://cplusplus.github.io/CWG/issues/2039.html) | C++11 | only the expression before conversion is required to be constant | the conversion must also be valid in a constant expression | ### See also | | | | --- | --- | | [#error](../preprocessor/error "cpp/preprocessor/error") | shows the given error message and renders the program ill-formed (preprocessing directive) | | [assert](../error/assert "cpp/error/assert") | aborts the program if the user-specified condition is not `true`. May be disabled for release builds (function macro) | | [abort](../utility/program/abort "cpp/utility/program/abort") | causes abnormal program termination (without cleaning up) (function) | | [exit](../utility/program/exit "cpp/utility/program/exit") | causes normal program termination with cleaning up (function) | | [enable\_if](../types/enable_if "cpp/types/enable if") (C++11) | conditionally [removes](sfinae "cpp/language/sfinae") a function overload or template specialization from overload resolution (class template) | | [**Type traits**](../types#Type_traits_.28since_C.2B.2B11.29 "cpp/types") (C++11) | defines a compile-time template-based interface to query or modify the properties of types | | [C documentation](https://en.cppreference.com/w/c/language/_Static_assert "c/language/ Static assert") for Static assertion | cpp Variadic arguments Variadic arguments ================== Allows a function to accept any number of extra arguments. Indicated by a trailing `...` (other than one introducing a pack expansion) (since C++11) following the parameter-list of a [function declaration](function "cpp/language/function"). When the parameter-list is not empty, an optional comma may precede a `...` signifying a variadic function. This provides compatibility with C (which added a requirement for a comma when it adopted function prototypes from C++). ``` // the function declared as follows int printx(const char* fmt...); // may be called with one or more arguments: printx("hello world"); printx("a=%d b=%d", a, b); int printx(const char* fmt, ...); // same as above (extraneous comma is allowed // for C compatibility) int printy(..., const char* fmt); // error: ... cannot appear as a parameter int printz(...); // valid, but the arguments cannot be accessed portably ``` | | | | --- | --- | | Note: this is different from a function [parameter pack](parameter_pack "cpp/language/parameter pack") expansion, which is indicated by an ellipsis that is a part of a parameter declarator, rather than an ellipsis that appears after all parameter declarations. Both parameter pack expansion and the "variadic" ellipsis may appear in the declaration of a function template, as in the case of `[std::is\_function](../types/is_function "cpp/types/is function")`. | (since C++11) | ### Default conversions When a variadic function is called, after lvalue-to-rvalue, array-to-pointer, and function-to-pointer [conversions](implicit_conversion#Value_transformations "cpp/language/implicit conversion"), each argument that is a part of the variable argument list undergoes additional conversions known as *default argument promotions*: | | | | --- | --- | | * `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` is converted to `void*` | (since C++11) | * `float` arguments are converted to `double` as in [floating-point promotion](implicit_conversion#Floating-point_promotion "cpp/language/implicit conversion") * `bool`, `char`, `short`, and unscoped (since C++11) enumerations are converted to `int` or wider integer types as in [integer promotion](implicit_conversion#Integral_promotion "cpp/language/implicit conversion") Only arithmetic, enumeration, pointer, pointer to member, and class type arguments (after conversion) are allowed. However, non-POD class types (until C++11)class types with an eligible non-trivial copy constructor, an eligible non-trivial move constructor, or a non-trivial destructor, together with scoped enumerations (since C++11), are conditionally-supported in potentially-evaluated calls with implementation-defined semantics (these types are always supported in [unevaluated calls](expressions#Unevaluated_expressions "cpp/language/expressions")). Because variadic parameters have the lowest rank for the purpose of [overload resolution](overload_resolution "cpp/language/overload resolution"), they are commonly used as the catch-all fallbacks in [SFINAE](sfinae "cpp/language/sfinae"). Within the body of a function that uses variadic arguments, the values of these arguments may be accessed using the [`<cstdarg>` library facilities](../utility/variadic "cpp/utility/variadic"): | Defined in header `[<cstdarg>](../header/cstdarg "cpp/header/cstdarg")` | | --- | | [va\_start](../utility/variadic/va_start "cpp/utility/variadic/va start") | enables access to variadic function arguments (function macro) | | [va\_arg](../utility/variadic/va_arg "cpp/utility/variadic/va arg") | accesses the next variadic function argument (function macro) | | [va\_copy](../utility/variadic/va_copy "cpp/utility/variadic/va copy") (C++11) | makes a copy of the variadic function arguments (function macro) | | [va\_end](../utility/variadic/va_end "cpp/utility/variadic/va end") | ends traversal of the variadic function arguments (function macro) | | [va\_list](../utility/variadic/va_list "cpp/utility/variadic/va list") | holds the information needed by va\_start, va\_arg, va\_end, and va\_copy (typedef) | The behavior of the `[va\_start](../utility/variadic/va_start "cpp/utility/variadic/va start")` macro is undefined if the last parameter before the ellipsis has reference type, or has type that is not compatible with the type that results from default argument promotions. | | | | --- | --- | | If the a [pack expansion](parameter_pack#Pack_expansion "cpp/language/parameter pack") or an entity resulting from a [lambda capture](lambda#Lambda_capture "cpp/language/lambda") is used as the last parameter in `[va\_start](../utility/variadic/va_start "cpp/utility/variadic/va start")`, the program is ill-formed, no diagnostic required. | (since C++11) | ### Alternatives | | | | --- | --- | | * [Variadic templates](parameter_pack "cpp/language/parameter pack") can also be used to create functions that take variable number of arguments. They are often the better choice because they do not impose restrictions on the types of the arguments, do not perform integral and floating-point promotions, and are type safe. * If all variable arguments share a common type, a `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` provides a convenient mechanism (albeit with a different syntax) for accessing variable arguments. In this case however the arguments cannot be modified since `[std::initializer\_list](../utility/initializer_list "cpp/utility/initializer list")` can only provide a const pointer to its elements. | (since C++11) | ### Notes In the C programming language until C23, at least one named parameter must appear before the ellipsis parameter, so `R printz(...);` is not valid until C23. In C++, this form is allowed even though the arguments passed to such function are not accessible, and is commonly used as the fallback overload in [SFINAE](sfinae "cpp/language/sfinae"), exploiting the lowest priority of the ellipsis conversion in [overload resolution](overload_resolution "cpp/language/overload resolution"). This syntax for variadic arguments was introduced in 1983 C++ without the comma before the ellipsis. When C89 adopted function prototypes from C++, it replaced the syntax with one requiring the comma. For compatibility, C++98 accepts both C++-style `f(int n...)` and C-style `f(int n, ...)`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 506](https://cplusplus.github.io/CWG/issues/506.html) | C++98 | passing non-POD class arguments to anellipsis resulted in undefined behavior | passing such arguments isconditionally-supported withimplementation-defined semantics | | [CWG 634](https://cplusplus.github.io/CWG/issues/634.html) | C++98 | conditionally-supported class typesmade some SFINAE idioms not work | always supported if unevaluated | | [CWG 2247](https://cplusplus.github.io/CWG/issues/2247.html) | C++11 | no restriction on passing parameterpack or lambda capture to `va_start` | made ill-formed,no diagnostic required | | [CWG 2347](https://cplusplus.github.io/CWG/issues/2347.html) | C++11 | it was unclear whether scoped enumerations passed toan ellipsis are subject to default argument promotions | passing scoped enumerationsis conditionally-supported withimplementation-defined semantics | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/variadic "c/language/variadic") for Variadic arguments |
programming_docs
cpp Explicit (full) template specialization Explicit (full) template specialization ======================================= Allows customizing the template code for a given set of template arguments. ### Syntax | | | | | --- | --- | --- | | `template` `<>` declaration | | | Any of the following can be fully specialized: 1. [function template](function_template "cpp/language/function template") 2. [class template](class_template "cpp/language/class template") 3. [variable template](variable_template "cpp/language/variable template") (since C++14) 4. [member function](member_functions "cpp/language/member functions") of a class template 5. [static data member](static "cpp/language/static") of a class template 6. [member class](nested_types "cpp/language/nested types") of a class template 7. member [enumeration](enum "cpp/language/enum") of a class template 8. [member class template](member_template "cpp/language/member template") of a class or class template 9. [member function template](member_template#Member_function_templates "cpp/language/member template") of a class or class template For example, ``` #include <iostream> template<typename T> // primary template struct is_void : std::false_type {}; template<> // explicit specialization for T = void struct is_void<void> : std::true_type {}; int main() { // for any type T other than void, the class is derived from false_type std::cout << is_void<char>::value << '\n'; // but when T is void, the class is derived from true_type std::cout << is_void<void>::value << '\n'; } ``` ### In detail Explicit specialization may be declared in any scope where its primary template may be defined (which may be different from the scope where the primary template is defined; such as with out-of-class specialization of a [member template](member_template "cpp/language/member template")) . Explicit specialization has to appear after the non-specialized template declaration. ``` namespace N { template<class T> // primary template class X { /*...*/ }; template<> // specialization in same namespace class X<int> { /*...*/ }; template<class T> // primary template class Y { /*...*/ }; template<> // forward declare specialization for double class Y<double>; } template<> // OK: specialization in same namespace class N::Y<double> { /*...*/ }; ``` Specialization must be declared before the first use that would cause implicit instantiation, in every translation unit where such use occurs: ``` class String {}; template<class T> class Array { /*...*/ }; template<class T> // primary template void sort(Array<T>& v) { /*...*/ } void f(Array<String>& v) { sort(v); // implicitly instantiates sort(Array<String>&), } // using the primary template for sort() template<> // ERROR: explicit specialization of sort(Array<String>) void sort<String>(Array<String>& v); // after implicit instantiation ``` A template specialization that was declared but not defined can be used just like any other [incomplete type](incomplete_type "cpp/language/incomplete type") (e.g. pointers and references to it may be used): ``` template<class T> // primary template class X; template<> // specialization (declared, not defined) class X<int>; X<int>* p; // OK: pointer to incomplete type X<int> x; // error: object of incomplete type ``` ### Explicit specializations of function templates When specializing a function template, its template arguments can be omitted if [template argument deduction](template_argument_deduction "cpp/language/template argument deduction") can provide them from the function arguments: ``` template<class T> class Array { /*...*/ }; template<class T> // primary template void sort(Array<T>& v); template<> // specialization for T = int void sort(Array<int>&); // no need to write // template<> void sort<int>(Array<int>&); ``` A function with the same name and the same argument list as a specialization is not a specialization (see template overloading in [function template](function_template "cpp/language/function template")). An explicit specialization of a function template is inline only if it is declared with the [inline specifier](inline "cpp/language/inline") (or defined as deleted), it doesn't matter if the primary template is inline. [Default function arguments](default_arguments "cpp/language/default arguments") cannot be specified in explicit specializations of function templates, member function templates, and member functions of class templates when the class is implicitly instantiated. An explicit specialization cannot be a [friend declaration](friend "cpp/language/friend"). ### Members of specializations When defining a member of an explicitly specialized class template outside the body of the class, the syntax `template<>` is not used, except if it's a member of an explicitly specialized member class template, which is specialized as a class template, because otherwise, the syntax would require such definition to begin with `template<parameters>` required by the nested template. ``` template<typename T> struct A { struct B {}; // member class template<class U> // member class template struct C {}; }; template<> // specialization struct A<int> { void f(int); // member function of a specialization }; // template<> not used for a member of a specialization void A<int>::f(int) { /* ... */ } template<> // specialization of a member class struct A<char>::B { void f(); }; // template<> not used for a member of a specialized member class either void A<char>::B::f() { /* ... */ } template<> // specialization of a member class template template<class U> struct A<char>::C { void f(); }; // template<> is used when defining a member of an explicitly // specialized member class template specialized as a class template template<> template<class U> void A<char>::C<U>::f() { /* ... */ } ``` An explicit specialization of a static data member of a template is a definition if the declaration includes an initializer; otherwise, it is a declaration. These definitions must use braces for default initialization: ``` template<> X Q<int>::x; // declaration of a static member template<> X Q<int>::x (); // error: function declaration template<> X Q<int>::x {}; // definition of a default-initialized static member ``` A member or a member template of a class template may be explicitly specialized for a given implicit instantiation of the class template, even if the member or member template is defined in the class template definition. ``` template<typename T> struct A { void f(T); // member, declared in the primary template void h(T) {} // member, defined in the primary template template<class X1> // member template void g1(T, X1); template<class X2> // member template void g2(T, X2); }; // specialization of a member template<> void A<int>::f(int); // member specialization OK even if defined in-class template<> void A<int>::h(int) {} // out of class member template definition template<class T> template<class X1> void A<T>::g1(T, X1) {} // member template specialization template<> template<class X1> void A<int>::g1(int, X1); // member template specialization template<> template<> void A<int>::g2<char>(int, char); // for X2 = char // same, using template argument deduction (X1 = char) template<> template<> void A<int>::g1(int, char); ``` Member or a member template may be nested within many enclosing class templates. In an explicit specialization for such a member, there's a `template<>` for every enclosing class template that is explicitly specialized. ``` template<class T1> struct A { template<class T2> struct B { template<class T3> void mf(); }; }; template<> struct A<int>; template<> template<> struct A<char>::B<double>; template<> template<> template<> void A<char>::B<char>::mf<double>(); ``` In such a nested declaration, some of the levels may remain unspecialized (except that it can't specialize a class member template if its enclosing class is unspecialized). For each of those levels, the declaration needs `template<arguments>`, because such specializations are themselves templates: ``` template<class T1> class A { template<class T2> class B { template<class T3> // member template void mf1(T3); void mf2(); // non-template member }; }; // specialization template<> // for the specialized A template<class X> // for the unspecialized B class A<int>::B { template<class T> void mf1(T); }; // specialization template<> // for the specialized A template<> // for the specialized B template<class T> // for the unspecialized mf1 void A<int>::B<double>::mf1(T t) {} // ERROR: B<double> is specialized and is a member template, so its enclosing A // must be specialized also template<class Y> template<> void A<Y>::B<double>::mf2() {} ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 531](https://cplusplus.github.io/CWG/issues/531.html) | C++98 | the syntax of defining members of explicitspecializations in namespace scope was not specified | specified | | [CWG 727](https://cplusplus.github.io/CWG/issues/727.html) | C++98 | full specializations not allowed inclass scope, even though partial are | full specialization allowed in any scope | | [CWG 730](https://cplusplus.github.io/CWG/issues/730.html) | C++98 | member templates of non-templateclasses could not be fully specialized | allowed | ### See also * [templates](templates "cpp/language/templates") * [class template](class_template "cpp/language/class template") * [function template](function_template "cpp/language/function template") * [partial specialization](partial_specialization "cpp/language/partial specialization") cpp Scope Scope ===== Each [name](name "cpp/language/name") that appears in a C++ program is only visible in some possibly discontiguous portion of the source code called its *scope*. Within a scope, [unqualified name lookup](lookup "cpp/language/lookup") can be used to associate the name with its declaration. ### Block scope The potential scope of a name declared in a [block (compound statement)](statements#Compound_statements "cpp/language/statements") begins at the point of declaration and ends at the end of the block. Actual scope is the same as potential scope unless an identical name is declared in a nested block, in which case the potential scope of the name in the nested block is excluded from the actual scope of the name in the enclosing block. ``` int main() { int i = 0; // scope of outer i begins ++i; // outer i is in scope { int i = 1; // scope of inner i begins, // scope of outer i pauses i = 42; // inner i is in scope } // block ends, scope of inner i ends, // scope of outer i resumes } // block ends, scope of outer i ends //int j = i; // error: i is not in scope ``` The potential scope of a name declared in an exception handler begins at the point of declaration and ends at the end of the exception handler, and is not in scope in another exception handler or in the enclosing block. ``` try { f(); } catch (const std::runtime_error& re) { // scope of re begins int n = 1; // scope of n begins std::cout << n << re.what(); // re is in scope } // scope of re ends, scope of n ends catch (std::exception& e) { // std::cout << re.what(); // error: re is not in scope // ++n; // error: n is not in scope } ``` The potential scope of a name declared in the *init-statement* of a [for loop](for "cpp/language/for"), in the *condition* of a [for loop](for "cpp/language/for"), in the *range\_declaration* of a [range-for loop](range-for "cpp/language/range-for"), in the *init-statement* of a [if statement](if "cpp/language/if") or [switch statement](switch "cpp/language/switch") (since C++17), in the *condition* of a [if statement](if "cpp/language/if"), [switch statement](switch "cpp/language/switch"), or [while loop](while "cpp/language/while") begins at the point of declaration and ends at the end of the controlled statement. ``` Base* bp = new Derived; if (Derived* dp = dynamic_cast<Derived*>(bp)) { dp->f(); // dp is in scope } // scope of dp ends for (int n = 0; // scope of n begins n < 10; // n is in scope ++n) // n is in scope { std::cout << n << ' '; // n is in scope } // scope of n ends ``` ### Function parameter scope The potential scope of a name declared in a function parameter (including parameters of a lambda expression) or of a function-local predefined variable begins at the point of declaration. * If the enclosing function declarator is not the declarator of a function definition, its potential scope ends at the end of that function declarator. * Otherwise, its potential scope ends at the end of the last exception handler of the [function-try-block](function-try-block "cpp/language/function-try-block"), or at the end of the function body if a function try block was not used. ``` const int n = 3; int f1( int n // scope of function parameter n begins, // scope of global n pauses // , int y = n // error: default argument references a function parameter ); int (*(*f2)(int n))[n]; // OK: scope of function parameter n // ends at the end of its function declarator // in the array declarator, global n is in scope // declares a pointer to function returning a pointer to an array of 3 int //auto (*f3)(int n)->int (*)[n]; // error: function parameter n as array bound void f(int n = 2) // scope of function parameter n begins try // function try block { // function body begins ++n; // function parameter n is in scope { int n = 2; // scope of local n begins // scope of function parameter n pauses ++n; // local n is in scope } // scope of local n ends // scope of function parameter n resumes } catch (std::exception& e) { ++n; // function parameter n is in scope throw; } // last exception handler ends, scope of function parameter n ends int a = n; // global n is in scope ``` ### Namespace scope The potential scope of a name declared in a [namespace](namespace "cpp/language/namespace") begins at the point of declaration and includes the rest of the namespace and all namespace definitions with an identical namespace name that follow, plus, for any [using-directive](namespace "cpp/language/namespace") that introduced this name or its entire namespace into another scope, the rest of that scope. The top-level scope of a translation unit ("file scope" or "global scope") is also a namespace and is properly called "global namespace scope". The potential scope of a name declared in the global namespace scope begins at the point of declaration and ends at the end of the translation unit. The potential scope of a name declared in an unnamed namespace or in an inline namespace includes the potential scope that name would have if it were declared in the enclosing namespace. ``` namespace N { // scope of N begins (as a member of global namespace) int i; // scope of i begins int g(int a) { return a; } // scope of g begins int j(); // scope of j begins void q(); // scope of q begins namespace { int x; // scope of x begins } // scope of x continues (member of unnamed namespace) inline namespace inl { // scope of inl begins int y; // scope of y begins } // scope of y continues (member of inline namespace) } // scopes of i, g, j, q, inl, x, and y pause namespace { int l = 1; // scope of l begins } // scope of l continues (member of unnamed namespace) namespace N { // scopes of i, g, j, q, inl, x, and y resume int g(char a) { // overloads N::g(int) return l + a; // l from unnamed namespace is in scope } // int i; // error: duplicate definition (i is already in scope) int j(); // OK: duplicate function declaration is allowed int j() { // OK: definition of the earlier-declared N::j() return g(i); // calls N::g(int) } // int q(); // error: q is already in scope with a different return type } // scopes of i, g, j, q, inl, x, and y pause int main() { using namespace N; // scopes of i, g, j, q, inl, x, and y resume i = 1; // N::i is in scope x = 1; // N::(anonymous)::x is in scope y = 1; // N::inl::y is in scope inl::y = 2; // N::inl is also in scope } // scopes of i, g, j, q, inl, x, and y end ``` | | | | --- | --- | | The name may also be visible in translation units that have [imported](modules "cpp/language/modules") the current translation unit. | (since C++20) | ### Class scope The potential scope of a name declared in a [class](class "cpp/language/class") begins at the point of declaration and includes the rest of the class body, all the derived classes bodies, the function bodies (even if defined outside the class definition or before the declaration of the name), function default arguments, function exception specifications, in-class brace-or-equal initializers, and all these things in nested classes, recursively. ``` struct X { int f(int a = n) { // n is in scope in function default argument return a * n; // n is in scope in function body } using r = int; r g(); int i = n * 2; // n is in scope in initializer // int x[n]; // error: n is not in scope in class body static const int n = 1; // scope of n begins int x[n]; // OK: n is now in scope in class body }; // scope of n pauses struct Y: X { // scope of n resumes int y[n]; // n is in scope }; // scope of n ends //r X::g() { // error: r is not in scope outside out-of-class function body auto X::g()->r { // OK: trailing return type r is in scope return n; // n is in scope in out-of-class function body } ``` If a name is used in a class body before it is declared, and another declaration for that name is in scope, the program is [ill-formed, no diagnostic required](ub "cpp/language/ub"). ``` typedef int c; // ::c enum { i = 1 }; // ::i class X { // char v[i]; // error: at this point, i refers to ::i // but there is also X::i int f() { return sizeof(c); // OK: X::c is in scope in member function } enum { i = 2 }; // X::i char c; // X::c char w[i]; // OK: i refers to X::i now }; // scope of outer i resumes typedef char* T; struct Y { // T a; // error: at this point, T refers to ::T // but there is also Y::T typedef long T; T b; }; ``` Names of class members can be used in the following contexts: * in its own class scope or in the class scope of a derived class; * after the `.` operator applied to an expression of the type of its class or a class derived from it; * after the `->` operator applied to an expression of the type of pointer to its class or pointers to a class derived from it; * after the `::` operator applied to the name of its class or the name of a class derived from it. ### Enumeration scope The potential scope of an enumerator of an [unscoped enumeration](enum "cpp/language/enum") begins at the point of declaration and ends at the end of the enclosing scope. The potential scope of an enumerator of a [scoped enumeration](enum "cpp/language/enum") begins at the point of declaration and ends at the end of the enum specifier. ``` enum e1_t { // unscoped enumeration A, B = A * 2 // A is in scope }; // scopes of A and B continue enum class e2_t { // scoped enumeration SA, SB = SA * 2 // SA is in scope }; // scopes of SA and SB end e1_t e1 = B; // OK: B is in scope //e2_t e2 = SB; // error: SB is not in scope e2_t e2 = e2_t::SB; // OK ``` ### Template parameter scope The potential scope of a template parameter name begins at the point of declaration and ends at the end of the smallest template declaration in which it was introduced. In particular, a template parameter can be used in the declarations of subsequent template parameters and in the specifications of base classes, but can't be used in the declarations of the preceding template parameters. ``` template< typename T, // scope of T begins T* p, // T is in scope class U = T // T is in scope > class X: public std::vector<T> // T is in scope { T f(); // T is in scope }; // scopes of T and U end ``` The potential scope of the name of the parameter of a template template parameter is the smallest template parameter list in which that name appears. ``` template< template< // template template parameter typename Y, // scope of Y begins typename G = Y // Y is in scope > // scopes of Y and G end class T, // typename U = Y // error: Y is not in scope typename U > class X { }; // scopes of T and U end ``` Similar to other nested scopes, the name of a template parameter hides the same name from the enclosing scope for the duration of its own. ``` typedef int N; template< N X, // ::N is in scope typename N, // scope of N begins, scope of ::N pauses template<N Y> class T // N is in scope > struct A; // scope of N ends, scope of ::N resumes ``` ### Point of declaration In general, a name is visible after the *locus* of its first declaration, which is located as follows. The locus of a name declared in a simple declaration is immediately after that name's [declarator](declarations#Declarators "cpp/language/declarations") and before its initializer, if any. ``` unsigned char x = 32; // outer x is in scope { unsigned char x = x; // inner x is in scope before the initializer (= x) // this does not initialize inner x with the value of outer x, // this initializes inner x with its own, indeterminate, value } std::function<int(int)> f = [&](int n){ return n > 1 ? n * f(n - 1) : n; }; // the name of the function f is in scope in the lambda and can // be correctly captured by reference, giving a recursive function ``` ``` const int x = 2; // outer x is in scope { int x[x] = {}; // inner x is in scope before the initializer (= {}), // but after the declarator (x[x]) // in the declarator, outer x is still in scope // this declares an array of 2 int } ``` The locus of a class or class template declaration is immediately after the identifier that names the class (or the [template-id](templates#template-id "cpp/language/templates") that names the template specialization) in its [class-head](classes "cpp/language/classes"). The class or class template name is already in scope in the list of base classes. ``` struct S: std::enable_shared_from_this<S> // S is in scope at the colon {}; ``` The locus of [enum specifier](enum "cpp/language/enum") or opaque enum declaration is immediately after the identifier that names the enumeration. ``` enum E: int { // E is in scope at the colon A = sizeof(E) }; ``` The locus of a [type alias or alias template](type_alias "cpp/language/type alias") declaration is immediately after the type-id to which the alias refers. ``` using T = int; // outer T is in scope at the semicolon { using T = T*; // inner T is in scope at the semicolon, // outer T is still in scope before the semicolon // same as T = int* } ``` The locus for a declarator in a [using declaration](using_declaration "cpp/language/using declaration") that does not name a constructor is immediately after the declarator. ``` template<int N> class Base { protected: static const int next = N + 1; static const int value = N; }; struct Derived: Base<0>, Base<1>, Base<2> { using Base<0>::next, // next is in scope at the comma Base<next>::value; // Derived::value is 1 }; ``` The locus of an enumerator is immediately after its definition (not before the initializer as it is for variables). ``` const int x = 12; { enum { x = x + 1, // enumerator x is in scope at the comma, // outer x is in scope before the comma, // enumerator x is initialized to 13 y = x + 1 // y is initialized to 14 }; } ``` The locus for an [injected-class-name](injected-class-name "cpp/language/injected-class-name") is immediately following the opening brace of its class (or class template) definition. ``` template<typename T> struct Array // : std::enable_shared_from_this<Array> // error: the injected class name is not in scope : std::enable_shared_from_this< Array<T> > // OK: the template-name Array is in scope { // the injected class name Array is now in scope as if a public member name Array* p; // pointer to Array<T> }; ``` | | | | --- | --- | | The locus of the implicit declaration for a function-local predefined variable `__func__` is immediately before the function body of a function definition. | (since C++11) | | | | | --- | --- | | The locus of a [structured binding declaration](structured_binding "cpp/language/structured binding") is immediately after the identifier-list, but structured binding initializers are prohibited from referring to any of the names being declared. | (since C++17) | | | | | --- | --- | | The locus of the variable or the structured bindings (since C++17) declared in the range\_declaration of a [range-for loop](range-for "cpp/language/range-for") is immediately after the range\_expression. ``` std::vector<int> x; for (auto x: x) { // auto x is in scope at the closing parenthesis, // vector x is in scope before the closing parenthesis // the auto x is in scope } ``` | (since C++11) | The locus of a [template parameter](template_parameters "cpp/language/template parameters") is immediately after its complete template parameter (including the optional default argument). ``` typedef unsigned char T; template< class T = T, // template parameter T is in scope at the comma, // typedef name of unsigned char is in scope before the comma T // template parameter T is in scope N = 0 > struct A { }; ``` | | | | --- | --- | | The locus of a [concept definition](constraints "cpp/language/constraints") is immediately after the concept name, but concept definitions are prohibited from referring to the concept name being declared. | (since C++20) | The locus of a named [namespace definition](namespace "cpp/language/namespace") is immediately after the namespace name. ### References * C++20 standard (ISO/IEC 14882:2020): + 6.4 Scope [basic.scope] * C++17 standard (ISO/IEC 14882:2017): + 6.3 Scope [basic.scope] * C++14 standard (ISO/IEC 14882:2014): + 3.3 Scope [basic.scope] * C++11 standard (ISO/IEC 14882:2011): + 3.3 Scope [basic.scope] * C++98 standard (ISO/IEC 14882:1998): + 3.3 Declarative regions and scopes [basic.scope] ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/scope "c/language/scope") for Scope |
programming_docs
cpp Classes Classes ======= A class is a user-defined type. A class type is defined by class-specifier, which appears in decl-specifier-seq of the [declaration](declarations "cpp/language/declarations") syntax. See [class declaration](class "cpp/language/class") for the syntax of the class specifier. A class can have the following kinds of members: 1) data members: a) [non-static data members](data_members "cpp/language/data members"), including [bit-fields](bit_field "cpp/language/bit field"). b) [static data members](static#Static_data_members "cpp/language/static") 2) member functions: a) [non-static member functions](member_functions "cpp/language/member functions") b) [static member functions](static#Static_member_functions "cpp/language/static") 3) nested types: a) [nested classes](nested_classes "cpp/language/nested classes") and [enumerations](enum "cpp/language/enum") defined within the class definition b) aliases of existing types, defined with [`typedef`](typedef "cpp/language/typedef") or [type alias](type_alias "cpp/language/type alias") (since C++11)declarations c) the name of the class within its own definition acts as a public member type alias of itself for the purpose of [lookup](unqualified_lookup#Injected_class_name "cpp/language/unqualified lookup") (except when used to name a [constructor](constructor "cpp/language/constructor")): this is known as *[injected-class-name](injected-class-name "cpp/language/injected-class-name")* 4) [enumerators](enum "cpp/language/enum") from all unscoped enumerations defined within the class, or introduced by [using-declarations](using_declaration "cpp/language/using declaration") or [using-enum-declarations](enum#Using-enum-declaration "cpp/language/enum") (since C++20) 5) [member templates](member_template "cpp/language/member template") (variable templates, (since C++14)class templates or function templates) may appear in the body of any non-local class/struct/union. All members are defined at once in the class definition, they cannot be added to an already-defined class (unlike the members of namespaces). A member of a class `T` cannot use `T` as its name if the member is. * a static data member, * a member function, * a member type, * a member template, * an enumerator of an unscoped (since C++11) enumeration, or * a member of a member anonymous union. However, a non-static data member may use the name `T` as long as there are no user-declared constructors. A class with at least one declared or inherited [virtual](virtual "cpp/language/virtual") member function is *polymorphic*. Objects of this type are [polymorphic objects](object#Polymorphic_objects "cpp/language/object") and have runtime type information stored as part of the object representation, which may be queried with [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") and [`typeid`](typeid "cpp/language/typeid"). Virtual member functions participate in dynamic binding. A class with at least one declared or inherited pure virtual member function is an [abstract class](abstract_class "cpp/language/abstract class"). Objects of this type cannot be created. | | | | --- | --- | | A class with a [constexpr](constexpr "cpp/language/constexpr") constructor is a [LiteralType](../named_req/literaltype "cpp/named req/LiteralType"): objects of this type can be manipulated by [constexpr](constexpr "cpp/language/constexpr") functions at compile time. | (since C++11) | ### Properties of classes | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | Trivially copyable class A *trivially copyable class* is a class that. | | | | --- | --- | | * has at least one non-deleted copy constructor, move constructor, copy assignment operator, or move assignment operator * each copy constructor is either [trivial](copy_constructor#Trivial_copy_constructor "cpp/language/copy constructor") or deleted * each move constructor is either [trivial](move_constructor#Trivial_move_constructor "cpp/language/move constructor") or deleted * each copy assignment operator is either [trivial](copy_assignment#Trivial_copy_assignment_operator "cpp/language/copy assignment") or deleted * each move assignment operator is either [trivial](move_assignment#Trivial_move_assignment_operator "cpp/language/move assignment") or deleted, and * has a non-deleted [trivial destructor](destructor#Trivial_destructor "cpp/language/destructor"). | (until C++20) | | * has at least one eligible [copy constructor](copy_constructor#Eligible_copy_constructor "cpp/language/copy constructor"), [move constructor](move_constructor#Eligible_move_constructor "cpp/language/move constructor"), [copy assignment operator](copy_assignment#Eligible_copy_assignment_operator "cpp/language/copy assignment"), or [move assignment operator](move_assignment#Eligible_move_assignment_operator "cpp/language/move assignment"), * each eligible copy constructor is [trivial](copy_constructor#Trivial_copy_constructor "cpp/language/copy constructor") * each eligible move constructor is [trivial](move_constructor#Trivial_move_constructor "cpp/language/move constructor") * each eligible copy assignment operator is [trivial](copy_assignment#Trivial_copy_assignment_operator "cpp/language/copy assignment") * each eligible move assignment operator is [trivial](move_assignment#Trivial_move_assignment_operator "cpp/language/move assignment"), and * has a non-deleted [trivial destructor](destructor#Trivial_destructor "cpp/language/destructor"). | (since C++20) | Trivial class A *trivial class* is a class that.* is trivially copyable, and | | | | --- | --- | | * has one or more default constructors such that each is either [trivial](default_constructor#Trivial_default_constructor "cpp/language/default constructor") or deleted and at least one of which is not deleted. | (until C++20) | | * has one or more [eligible default constructors](default_constructor#Eligible_default_constructor "cpp/language/default constructor") such that each is [trivial](default_constructor#Trivial_default_constructor "cpp/language/default constructor"). | (since C++20) | Standard-layout class A *standard-layout class* is a class that.* has no [non-static data members](data_members "cpp/language/data members") of type non-standard-layout class (or array of such types) or reference, * has no [virtual functions](virtual "cpp/language/virtual") and no [virtual base classes](derived_class#Virtual_base_classes "cpp/language/derived class"), * has the same [access control](access "cpp/language/access") for all non-static data members, * has no non-standard-layout base classes, * has all non-static data members and [bit-fields](bit_field "cpp/language/bit field") in the class and its base classes first declared in the same class, and * given the class as S, has no element of the set M(S) of types as a base class, where M(X) for a type X is defined as: + If X is a non-union class type with no (possibly inherited) non-static data members, the set M(X) is empty. + If X is a non-union class type whose first non-static data member has type X0 (where said member may be an anonymous union), the set M(X) consists of X0 and the elements of M(X0). + If X is a union type, the set M(X) is the union of all M(Ui) and the set containing all Ui, where each Ui is the type of the ith non-static data member of X. + If X is an array type with element type Xe, the set M(X) consists of Xe and the elements of M(Xe). + If X is a non-class, non-array type, the set M(X) is empty. A *standard-layout struct* is a standard-layout class defined with the class keyword [`struct`](../keyword/struct "cpp/keyword/struct") or the class keyword [`class`](../keyword/class "cpp/keyword/class"). A *standard-layout union* is a standard-layout class defined with the class keyword [`union`](../keyword/union "cpp/keyword/union"). | (since C++11) | | | | | --- | --- | | Implicit-lifetime class An *implicit-lifetime class* is a class that.* is an [aggregate](aggregate_initialization "cpp/language/aggregate initialization"), or * has at least one trivial eligible constructor and a trivial, non-deleted destructor. | (since C++20) | | | | | | | | | --- | --- | --- | --- | --- | --- | | POD class A *POD class* is a class that. | | | | --- | --- | | * is an [aggregate](aggregate_initialization "cpp/language/aggregate initialization"), * has no user-declared copy assignment operator, * has no user-declared destructor, and * has no non-static data members of type non-POD class (or array of such types) or reference. | (until C++11) | | * is a trivial class, * is a standard-layout class, and * has no non-static data members of type non-POD class (or array of such types). | (since C++11) | A *POD struct* is a non-union POD class. A *POD union* is a union that is a POD class. | (until C++20) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 148](https://cplusplus.github.io/CWG/issues/148.html) | C++98 | POD classes could not contain pointers to member,which are themselves POD (scalar) types | restriction removed | | [CWG 383](https://cplusplus.github.io/CWG/issues/383.html) | C++98 | copy assignment operators or destructors could beuser-declared in POD classes if they are not defined | not allowed | | [CWG 1363](https://cplusplus.github.io/CWG/issues/1363.html) | C++11 | a class that has both trivial default constructors and non-trivial default constructors at the same time could be trivial | it is non-trivial | | [CWG 1496](https://cplusplus.github.io/CWG/issues/1496.html) | C++11 | a class that only has constructors thatare all defined as deleted could be trivial | it is non-trivial | | [CWG 1672](https://cplusplus.github.io/CWG/issues/1672.html) | C++11 | a class could be a standard-layout classif it has multiple empty base classes | it is not a standard-layout class | | [CWG 1734](https://cplusplus.github.io/CWG/issues/1734.html) | C++11 | a trivially copyable class could not have non-trivialdeleted copy/move constructors/assignment operators | can be trivial if deleted | | [CWG 1813](https://cplusplus.github.io/CWG/issues/1813.html) | C++11 | a class was never a standard-layout class if it has abase class that inherits a non-static data member | it can be a standard-layout class | | [CWG 1881](https://cplusplus.github.io/CWG/issues/1881.html) | C++11 | for a standard-layout class and its base classes,unnamed bit-fields might be declared in adifferent class declaring the data members | all non-static data membersand bit-fields need to be firstdeclared in the same class | | [CWG 1909](https://cplusplus.github.io/CWG/issues/1909.html) | C++98 | a member template could have the same name as its class | prohibited | | [CWG 2120](https://cplusplus.github.io/CWG/issues/2120.html) | C++11 | the definition of M(X) in determining a standard-layout class did not consider the case ofa class whose first member is an array | addressed this case inthe definition of M(X) | cpp Boolean literals Boolean literals ================ ### Syntax | | | | | --- | --- | --- | | `true` | (1) | | | `false` | (2) | | ### Explanation The Boolean literals are the keywords `true` and `false`. They are [prvalues](value_category "cpp/language/value category") of type [bool](types#Boolean_type "cpp/language/types"). ### Notes See [Integral conversions](implicit_cast#Integral_conversions "cpp/language/implicit cast") for implicit conversions from `bool` to other types and [boolean conversions](implicit_cast#Boolean_conversions "cpp/language/implicit cast") for the implicit conversions from other types to `bool`. ### Example ``` #include <iostream> int main() { std::cout << std::boolalpha << true << '\n' << false << '\n' << std::noboolalpha << true << '\n' << false << '\n'; } ``` Output: ``` true false 1 0 ``` ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/bool_constant "c/language/bool constant") for Predefined Boolean constants | cpp Fundamental types Fundamental types ================= (See also [type](type "cpp/language/type") for type system overview and [the list of type-related utilities](../types "cpp/types") that are provided by the C++ library). ### Void type `void` - type with an empty set of values. It is an [incomplete type](incomplete_type "cpp/language/incomplete type") that cannot be completed (consequently, objects of type `void` are disallowed). There are no [arrays](array "cpp/language/array") of `void`, nor [references](reference "cpp/language/reference") to `void`. However, [pointers to `void`](pointer#Pointers_to_void "cpp/language/pointer") and [functions](function "cpp/language/function") returning type `void` (*procedures* in other languages) are permitted. ### `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` | Defined in header `[<cstddef>](../header/cstddef "cpp/header/cstddef")` | | | | --- | --- | --- | | ``` typedef decltype(nullptr) nullptr_t; ``` | | (since C++11) | `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` is the type of the null pointer literal, [`nullptr`](nullptr "cpp/language/nullptr"). It is a distinct type that is not itself a pointer type or a pointer to member type. Its values are *null pointer constant* (see `[NULL](../types/null "cpp/types/NULL")`), and may be [implicitly converted](implicit_cast "cpp/language/implicit cast") to any pointer and pointer to member type. `sizeof([std::nullptr\_t](http://en.cppreference.com/w/cpp/types/nullptr_t))` is equal to `sizeof(void *)`. ### Data models The choices made by each implementation about the sizes of the fundamental types are collectively known as *data model*. Four data models found wide acceptance: 32 bit systems: * **LP32** or **2/4/4** (int is 16-bit, long and pointer are 32-bit) + Win16 API * **ILP32** or **4/4/4** (int, long, and pointer are 32-bit); + Win32 API + Unix and Unix-like systems (Linux, macOS) 64 bit systems: * **LLP64** or **4/4/8** (int and long are 32-bit, pointer is 64-bit) + Win64 API * **LP64** or **4/8/8** (int is 32-bit, long and pointer are 64-bit) + Unix and Unix-like systems (Linux, macOS) Other models are very rare. For example, **ILP64** (**8/8/8**: int, long, and pointer are 64-bit) only appeared in some early 64-bit Unix systems (e.g. [UNICOS on Cray](https://en.wikipedia.org/wiki/UNICOS "enwiki:UNICOS")). ### Signed and unsigned integer types `int` - basic integer type. The keyword `int` may be omitted if any of the modifiers listed below are used. If no length modifiers are present, it's guaranteed to have a width of at least 16 bits. However, on 32/64 bit systems it is almost exclusively guaranteed to have width of at least 32 bits (see below). #### Modifiers Modifies the basic integer type. Can be mixed in any order. Only one of each group can be present in type name. **Signedness**. `signed` - target type will have signed representation (this is the default if omitted) `unsigned` - target type will have unsigned representation **Size**. `short` - target type will be optimized for space and will have width of at least 16 bits. `long` - target type will have width of at least 32 bits. | | | | --- | --- | | `long long` - target type will have width of at least 64 bits. | (since C++11) | Note: as with all type specifiers, any order is permitted: `unsigned long long int` and `long int unsigned long` name the same type. #### Properties The following table summarizes all available integer types and their properties in various common data models: | Type specifier | Equivalent type | Width in bits by data model | | --- | --- | --- | | C++ standard | LP32 | ILP32 | LLP64 | LP64 | | `short` | `short int` | at least **16** | **16** | **16** | **16** | **16** | | `short int` | | `signed short` | | `signed short int` | | `unsigned short` | `unsigned short int` | | `unsigned short int` | | `int` | `int` | at least **16** | **16** | **32** | **32** | **32** | | `signed` | | `signed int` | | `unsigned` | `unsigned int` | | `unsigned int` | | `long` | `long int` | at least **32** | **32** | **32** | **32** | **64** | | `long int` | | `signed long` | | `signed long int` | | `unsigned long` | `unsigned long int` | | `unsigned long int` | | `long long` | `long long int` (C++11) | at least **64** | **64** | **64** | **64** | **64** | | `long long int` | | `signed long long` | | `signed long long int` | | `unsigned long long` | `unsigned long long int` (C++11) | | `unsigned long long int` | Note: integer arithmetic is defined differently for the signed and unsigned integer types. See [arithmetic operators](operator_arithmetic "cpp/language/operator arithmetic"), in particular [integer overflows](operator_arithmetic#Overflows "cpp/language/operator arithmetic"). `[std::size\_t](../types/size_t "cpp/types/size t")` is the unsigned integer type of the result of the [`sizeof`](sizeof "cpp/language/sizeof") operator as well as the [`sizeof...`](sizeof... "cpp/language/sizeof...") operator and the [`alignof`](alignof "cpp/language/alignof") operator (since C++11). | | | | --- | --- | | See also [Fixed width integer types](../types/integer "cpp/types/integer"). | (since C++11) | ### Boolean type `bool` - type, capable of holding one of the two values: [`true`](bool_literal "cpp/language/bool literal") or [`false`](bool_literal "cpp/language/bool literal"). The value of `sizeof(bool)` is implementation defined and might differ from 1. ### Character types `signed char` - type for signed character representation. `unsigned char` - type for unsigned character representation. Also used to inspect [object representations](object "cpp/language/object") (raw memory). `char` - type for character representation which can be most efficiently processed on the target system (has the same representation and alignment as either `signed char` or `unsigned char`, but is always a distinct type). [Multibyte characters strings](../string/multibyte "cpp/string/multibyte") use this type to represent code units. For every value of type `unsigned char` in range [0, 255], converting the value to `char` and then back to `unsigned char` produces the original value. (since C++11) The signedness of `char` depends on the compiler and the target platform: the defaults for ARM and PowerPC are typically unsigned, the defaults for x86 and x64 are typically signed. `wchar_t` - type for wide character representation (see [wide strings](../string/wide "cpp/string/wide")). It has the same size, signedness, and alignment as one of the integer types, but is a distinct type. In practice, it is 32 bits and holds UTF-32 on Linux and many other non-Windows systems, but 16 bits and holds UTF-16 code units on Windows. The standard used to require `wchar_t` to be large enough to represent any supported character code point. However, such requirement cannot be fulfilled on Windows, and thus it is considered as a defect and removed by [P2460R2](https://wg21.link/P2460R2). | | | | --- | --- | | `char16_t` - type for UTF-16 character representation, required to be large enough to represent any UTF-16 code unit (16 bits). It has the same size, signedness, and alignment as `[std::uint\_least16\_t](../types/integer "cpp/types/integer")`, but is a distinct type. `char32_t` - type for UTF-32 character representation, required to be large enough to represent any UTF-32 code unit (32 bits). It has the same size, signedness, and alignment as `[std::uint\_least32\_t](../types/integer "cpp/types/integer")`, but is a distinct type. | (since C++11) | | | | | --- | --- | | `char8_t` - type for UTF-8 character representation, required to be large enough to represent any UTF-8 code unit (8 bits). It has the same size, signedness, and alignment as `unsigned char` (and therefore, the same size and alignment as `char` and `signed char`), but is a distinct type. | (since C++20) | Besides the minimal bit counts, the C++ Standard guarantees that `1 == sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)`. Note: this allows the extreme case in which [bytes](https://en.wikipedia.org/wiki/Byte "enwiki:Byte") are sized 64 bits, all types (including `char`) are 64 bits wide, and `sizeof` returns 1 for every type. ### Floating-point types The following three types and their cv-qualified versions are collectively called floating-point types. `float` - single precision floating-point type. Matches [IEEE-754 binary32 format](https://en.wikipedia.org/wiki/Single-precision_floating-point_format "enwiki:Single-precision floating-point format") if supported. `double` - double precision floating-point type. Matches [IEEE-754 binary64 format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format "enwiki:Double-precision floating-point format") if supported. `long double` - extended precision floating-point type. Matches [IEEE-754 binary128 format](https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format "enwiki:Quadruple-precision floating-point format") if supported, otherwise matches [IEEE-754 binary64-extended format](https://en.wikipedia.org/wiki/Extended_precision "enwiki:Extended precision") if supported, otherwise matches some non-IEEE-754 extended floating-point format as long as its precision is better than binary64 and range is at least as good as binary64, otherwise matches IEEE-754 binary64 format. * binary128 format is used by some HP-UX, SPARC, MIPS, ARM64, and z/OS implementations. * The most well known IEEE-754 binary64-extended format is 80-bit x87 extended precision format. It is used by many x86 and x86-64 implementations (a notable exception is MSVC, which implements `long double` in the same format as `double`, i.e. binary64). #### Properties Floating-point types may support [special values](../types/numeric_limits "cpp/types/numeric limits"): * *infinity* (positive and negative), see `[INFINITY](../numeric/math/infinity "cpp/numeric/math/INFINITY")` * the *negative zero*, `-0.0`. It compares equal to the positive zero, but is meaningful in some arithmetic operations, e.g. `1.0/0.0 == [INFINITY](http://en.cppreference.com/w/cpp/numeric/math/INFINITY)`, but `1.0/-0.0 == -[INFINITY](http://en.cppreference.com/w/cpp/numeric/math/INFINITY)`), and for some mathematical functions, e.g. [`sqrt(std::complex)`](../numeric/complex/sqrt "cpp/numeric/complex/sqrt") * *not-a-number* (NaN), which does not compare equal with anything (including itself). Multiple bit patterns represent NaNs, see `[std::nan](../numeric/math/nan "cpp/numeric/math/nan")`, `[NAN](../numeric/math/nan "cpp/numeric/math/NAN")`. Note that C++ takes no special notice of signalling NaNs other than detecting their support by `[std::numeric\_limits::has\_signaling\_NaN](../types/numeric_limits/has_signaling_nan "cpp/types/numeric limits/has signaling NaN")`, and treats all NaNs as quiet. Real floating-point numbers may be used with [arithmetic operators](operator_arithmetic "cpp/language/operator arithmetic") + - / \* and various mathematical functions from [`<cmath>`](../header/cmath "cpp/header/cmath"). Both built-in operators and library functions may raise floating-point exceptions and set `[errno](../error/errno "cpp/error/errno")` as described in [`math errhandling`](../numeric/math/math_errhandling "cpp/numeric/math/math errhandling"). Floating-point expressions may have greater range and precision than indicated by their types, see `[FLT\_EVAL\_METHOD](../types/climits/flt_eval_method "cpp/types/climits/FLT EVAL METHOD")`. Floating-point expressions may also be *contracted*, that is, calculated as if all intermediate values have infinite range and precision, see [`#pragma STDC FP_CONTRACT`](../preprocessor/impl#.23pragma_STDC "cpp/preprocessor/impl"). Standard C++ does not restrict the accuracy of floating-point operations. Some operations on floating-point numbers are affected by and modify the state of [the floating-point environment](../numeric/fenv "cpp/numeric/fenv") (most notably, the rounding direction). [Implicit conversions](implicit_conversion "cpp/language/implicit conversion") are defined between real floating types and integer types. See [Limits of floating-point types](../types/climits#Limits_of_floating_point_types "cpp/types/climits") and `[std::numeric\_limits](../types/numeric_limits "cpp/types/numeric limits")` for additional details, limits, and properties of the floating-point types. ### Range of values The following table provides a reference for the limits of common numeric representations. Prior to C++20, the C++ Standard allowed any signed integer representation, and the minimum guaranteed range of N-bit signed integers was from \(\scriptsize -(2^{N-1}-1)\)-(2N-1 -1) to \(\scriptsize +2^{N-1}-1\)+2N-1 -1 (e.g. **-127** to **127** for a signed 8-bit type), which corresponds to the limits of [ones' complement](https://en.wikipedia.org/wiki/Ones%27_complement "enwiki:Ones' complement") or [sign-and-magnitude](https://en.wikipedia.org/wiki/Signed_number_representations#Sign-and-magnitude_method "enwiki:Signed number representations"). However, all C++ compilers use [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement "enwiki:Two's complement") representation, and as of C++20, it is the only representation allowed by the standard, with the guaranteed range from \(\scriptsize -2^{N-1}\)-2N-1 to \(\scriptsize +2^{N-1}-1\)+2N-1 -1 (e.g. **-128** to **127** for a signed 8-bit type). 8-bit ones' complement and sign-and-magnitude representations for `char` have been disallowed since C++11 (via [CWG 1759](https://cplusplus.github.io/CWG/issues/1759.html)), because a UTF-8 code unit of value 0x80 used in a [UTF-8 string literal](string_literal "cpp/language/string literal") must be storable in a `char` element object. | Type | Size in bits | Format | Value range | | --- | --- | --- | --- | | Approximate | Exact | | character | 8 | signed | | **-128** to **127** | | unsigned | | **0** to **255** | | 16 | UTF-16 | | **0** to **65535** | | 32 | UTF-32 | | **0** to **1114111** (**0x10ffff**) | | integer | 16 | signed | **± 3.27 · 104** | **-32768** to **32767** | | unsigned | **0** to **6.55 · 104** | **0** to **65535** | | 32 | signed | **± 2.14 · 109** | **-2,147,483,648** to **2,147,483,647** | | unsigned | **0** to **4.29 · 109** | **0** to **4,294,967,295** | | 64 | signed | **± 9.22 · 1018** | **-9,223,372,036,854,775,808** to **9,223,372,036,854,775,807** | | unsigned | **0** to **1.84 · 1019** | **0** to **18,446,744,073,709,551,615** | | binary floating point | 32 | [IEEE-754](https://en.wikipedia.org/wiki/Single-precision_floating-point_format "enwiki:Single-precision floating-point format") | * min subnormal:**± 1.401,298,4 · 10-45** * min normal:**± 1.175,494,3 · 10-38** * max:**± 3.402,823,4 · 1038** | * min subnormal:**±0x1p-149** * min normal:**±0x1p-126** * max:**±0x1.fffffep+127** | | 64 | [IEEE-754](https://en.wikipedia.org/wiki/Double-precision_floating-point_format "enwiki:Double-precision floating-point format") | * min subnormal:**± 4.940,656,458,412 · 10-324** * min normal:**± 2.225,073,858,507,201,4 · 10-308** * max:**± 1.797,693,134,862,315,7 · 10308** | * min subnormal:**±0x1p-1074** * min normal:**±0x1p-1022** * max:**±0x1.fffffffffffffp+1023** | | 80[[note 1]](#cite_note-1) | [x86](https://en.wikipedia.org/wiki/Extended_precision "enwiki:Extended precision") | * min subnormal:**± 3.645,199,531,882,474,602,528 · 10-4951** * min normal:**± 3.362,103,143,112,093,506,263 · 10-4932** * max:**± 1.189,731,495,357,231,765,021 · 104932** | * min subnormal:**±0x1p-16446** * min normal:**±0x1p-16382** * max:**±0x1.fffffffffffffffep+16383** | | 128 | [IEEE-754](https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format "enwiki:Quadruple-precision floating-point format") | * min subnormal:**± 6.475,175,119,438,025,110,924,438,958,227,646,552,5 · 10-4966** * min normal:**± 3.362,103,143,112,093,506,262,677,817,321,752,602,6 · 10-4932** * max:**± 1.189,731,495,357,231,765,085,759,326,628,007,016,2 · 104932** | * min subnormal:**±0x1p-16494** * min normal:**±0x1p-16382** * max:**±0x1.ffffffffffffffffffffffffffffp+16383** | 1. The object representation usually occupies 96/128 bits on 32/64-bit platforms respectively. Note: actual (as opposed to guaranteed minimal) limits on the values representable by these types are available in [C numeric limits interface](../types/climits "cpp/types/climits") and `[std::numeric\_limits](../types/numeric_limits "cpp/types/numeric limits")`. ### Keywords [`void`](../keyword/void "cpp/keyword/void"), [`bool`](../keyword/bool "cpp/keyword/bool"), [`true`](../keyword/true "cpp/keyword/true"), [`false`](../keyword/false "cpp/keyword/false"), [`char`](../keyword/char "cpp/keyword/char"), [`wchar_t`](../keyword/wchar_t "cpp/keyword/wchar t"), [`char8_t`](../keyword/char8_t "cpp/keyword/char8 t"), (since C++20) [`char16_t`](../keyword/char16_t "cpp/keyword/char16 t"), [`char32_t`](../keyword/char32_t "cpp/keyword/char32 t"), (since C++11) [`int`](../keyword/int "cpp/keyword/int"), [`short`](../keyword/short "cpp/keyword/short"), [`long`](../keyword/long "cpp/keyword/long"), [`signed`](../keyword/signed "cpp/keyword/signed"), [`unsigned`](../keyword/unsigned "cpp/keyword/unsigned"), [`float`](../keyword/float "cpp/keyword/float"), [`double`](../keyword/double "cpp/keyword/double"). ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 238](https://cplusplus.github.io/CWG/issues/238.html) | C++98 | the constraints placed on a floating-point implementation was unspecified | specified as no constraint | | [CWG 1759](https://cplusplus.github.io/CWG/issues/1759.html) | C++11 | `char` is not guaranteed to be able to represent UTF-8 code unit 0x80 | guaranteed | ### See also * [the C++ type system overview](type "cpp/language/type") * [const-volatility (cv) specifiers and qualifiers](cv "cpp/language/cv") * [storage duration specifiers](storage_duration "cpp/language/storage duration") | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/arithmetic_types "c/language/arithmetic types") for arithmetic types |
programming_docs
cpp noexcept operator (since C++11) noexcept operator (since C++11) =============================== The `noexcept` operator performs a compile-time check that returns `true` if an expression is declared to not throw any exceptions. It can be used within a function template's [`noexcept` specifier](noexcept_spec "cpp/language/noexcept spec") to declare that the function will throw exceptions for some types but not others. ### Syntax | | | | | --- | --- | --- | | `noexcept(` expression `)` | | | Returns a [prvalue](value_category "cpp/language/value category") of type `bool`. ### Explanation The `noexcept` operator does not evaluate expression. The result is `true` if the set of [*potential exceptions*](except_spec "cpp/language/except spec") of the expression is empty (until C++17)expression is [*non-throwing*](noexcept_spec "cpp/language/noexcept spec") (since C++17), and `false` otherwise. ### Keywords [`noexcept`](../keyword/noexcept "cpp/keyword/noexcept"). ### Example ``` #include <iostream> #include <utility> #include <vector> void may_throw(); void no_throw() noexcept; auto lmay_throw = []{}; auto lno_throw = []() noexcept {}; class T { public: ~T(){} // dtor prevents move ctor // copy ctor is noexcept }; class U { public: ~U(){} // dtor prevents move ctor // copy ctor is noexcept(false) std::vector<int> v; }; class V { public: std::vector<int> v; }; int main() { T t; U u; V v; std::cout << std::boolalpha << "Is may_throw() noexcept? " << noexcept(may_throw()) << '\n' << "Is no_throw() noexcept? " << noexcept(no_throw()) << '\n' << "Is lmay_throw() noexcept? " << noexcept(lmay_throw()) << '\n' << "Is lno_throw() noexcept? " << noexcept(lno_throw()) << '\n' << "Is ~T() noexcept? " << noexcept(std::declval<T>().~T()) << '\n' // note: the following tests also require that ~T() is noexcept because // the expression within noexcept constructs and destroys a temporary << "Is T(rvalue T) noexcept? " << noexcept(T(std::declval<T>())) << '\n' << "Is T(lvalue T) noexcept? " << noexcept(T(t)) << '\n' << "Is U(rvalue U) noexcept? " << noexcept(U(std::declval<U>())) << '\n' << "Is U(lvalue U) noexcept? " << noexcept(U(u)) << '\n' << "Is V(rvalue V) noexcept? " << noexcept(V(std::declval<V>())) << '\n' << "Is V(lvalue V) noexcept? " << noexcept(V(v)) << '\n'; } ``` Output: ``` Is may_throw() noexcept? false Is no_throw() noexcept? true Is lmay_throw() noexcept? false Is lno_throw() noexcept? true Is ~T() noexcept? true Is T(rvalue T) noexcept? true Is T(lvalue T) noexcept? true Is U(rvalue U) noexcept? false Is U(lvalue U) noexcept? false Is V(rvalue V) noexcept? true Is V(lvalue V) noexcept? false ``` ### See also | | | | --- | --- | | [`noexcept` specifier](noexcept_spec "cpp/language/noexcept spec")(C++11) | specifies whether a function could throw exceptions | | [Dynamic exception specification](except_spec "cpp/language/except spec")(until C++17) | specifies what exceptions are thrown by a function (deprecated in C++11) | cpp Acronyms Acronyms ======== | Acronym | Full name | See also | | --- | --- | --- | | AAA | Almost Always [Auto](../keyword/auto "cpp/keyword/auto") | [GOTW #94](https://herbsutter.com/2013/06/13/gotw-94-special-edition-aaa-style-almost-always-auto) | | ABC | [Abstract Base Class](abstract_class "cpp/language/abstract class") | | | ABI | [Application Binary Interface](https://en.wikipedia.org/wiki/Application_binary_interface "enwiki:Application binary interface") | [Itanium C++ ABI](https://itanium-cxx-abi.github.io/cxx-abi/abi.html) | | ADL | [Argument-Dependent Lookup](adl "cpp/language/adl") | | | ADT | [Abstract Data Type](https://en.wikipedia.org/wiki/Abstract_data_type "enwiki:Abstract data type") | | | API | [Application Programming Interface](https://en.wikipedia.org/wiki/Application_programming_interface "enwiki:Application programming interface") | | | CAS | [Compare And Swap](https://en.wikipedia.org/wiki/Compare-and-swap "enwiki:Compare-and-swap"); [Copy And Swap](https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom) | [`compare_exchange`](../atomic/atomic/compare_exchange "cpp/atomic/atomic/compare exchange") | | COW | [Copy On Write](https://en.wikipedia.org/wiki/Copy-on-write "enwiki:Copy-on-write") | | | CPO | [Customization Point Object](../ranges "cpp/ranges") | [[customization.point.object]](http://eel.is/c++draft/customization.point.object#1) | | CRTP | [Curiously Recurring Template Pattern](crtp "cpp/language/crtp") | `[std::enable\_shared\_from\_this](../memory/enable_shared_from_this "cpp/memory/enable shared from this")`, `[std::ranges::view\_interface](../ranges/view_interface "cpp/ranges/view interface")` | | CTAD | [Class Template Argument Deduction](class_template_argument_deduction "cpp/language/class template argument deduction") | | | EBO | [Empty Base Optimization](ebo "cpp/language/ebo") | `[std::allocator](../memory/allocator "cpp/memory/allocator")`, `[std::default\_delete](../memory/default_delete "cpp/memory/default delete")` | | EBCO | [Empty Base Class Optimization](ebo "cpp/language/ebo") | | | ICE | [Internal Compiler Error](https://en.wikipedia.org/wiki/Compilation_error#Internal_Compiler_Errors "enwiki:Compilation error"); Integer Constant Expression | | | IFNDR | [Ill-Formed, No Diagnostic Required](ndr "cpp/language/ndr") | | | IIILE | Immediately Invoked Initializing [Lambda Expression](lambda "cpp/language/lambda") | | | IPO | [InterProcedural Optimization](https://en.wikipedia.org/wiki/Interprocedural_optimization "enwiki:Interprocedural optimization") | | | LTO | [Link-Time Optimization](https://en.wikipedia.org/wiki/Interprocedural_optimization#WPO_and_LTO "enwiki:Interprocedural optimization") | | | NDR | [No Diagnostic Required](ndr "cpp/language/ndr") | | | NRVO | [Named Return Value Optimization](copy_elision "cpp/language/copy elision") | | | NSDMI | [Non-Static Data Member Initialization](data_members "cpp/language/data members") | | | NTBS | [Null-Terminated Byte Strings](../string/byte "cpp/string/byte") | | | NTTP | [Non-Type Template Parameter](template_parameters "cpp/language/template parameters") | | | ODR | [One Definition Rule](definition "cpp/language/definition") | | | OOP | [Object-Oriented Programming](https://en.wikipedia.org/wiki/Object-oriented_programming "enwiki:Object-oriented programming") | | | PIMPL | [Pointer to IMPLementation](pimpl "cpp/language/pimpl") | | | POCCA | [Propagate on Container Copy Assignment](../memory/allocator_traits "cpp/memory/allocator traits") | | | POCMA | [Propagate on Container Move Assignment](../memory/allocator_traits "cpp/memory/allocator traits") | | | POCS | [Propagate on Container Swap](../memory/allocator_traits "cpp/memory/allocator traits") | | | RAII | [Resource Acquisition Is Initialization](raii "cpp/language/raii") | | | RACO | [Range Adaptor Closure Object](../ranges#Range_adaptor_closure_objects "cpp/ranges") | | | RAO | [Range Adaptor Object](../ranges#Range_adaptor_objects "cpp/ranges") | | | RTTI | [RunTime Type Identification](types "cpp/language/types") | `[std::type\_info](../types/type_info "cpp/types/type info")` | | RVO | [Return Value Optimization](copy_elision "cpp/language/copy elision") | | | SBO | Small Buffer Optimization | | | SBRM | Scope-Bound Resource Management, see [RAII](raii "cpp/language/raii") | | | SCARY | **S**eemingly erroneous (appearing **C**onstrained by conflicting generic parameters), but **A**ctually work with the **R**ight implementation (unconstrained b**Y** the conflict due to minimized dependencies). | [stroustrup.com/SCARY](https://www.stroustrup.com/SCARY.pdf) | | SFINAE | [Substitution Failure Is Not An Error](sfinae "cpp/language/sfinae") | `[std::enable\_if](../types/enable_if "cpp/types/enable if")`, `[std::void\_t](../types/void_t "cpp/types/void t")` | | SIOF | Static Initialization Order Fiasco | | | SOCCC | [Select On Container Copy Construction](../memory/allocator_traits/select_on_container_copy_construction "cpp/memory/allocator traits/select on container copy construction") | | | SOO | Small Object Optimization | `std::move_only_function`, `[std::function](../utility/functional/function "cpp/utility/functional/function")`, `[std::any](../utility/any "cpp/utility/any")` | | SSO | Small String Optimization | `[std::basic\_string](../string/basic_string "cpp/string/basic string")` | | TMP | [Template Meta Programming](template_metaprogramming "cpp/language/template metaprogramming") | [`<type_traits>`](../header/type_traits "cpp/header/type traits") | | TU | [Translation Unit](translation_phases#Phase_7 "cpp/language/translation phases") | [Modules](modules "cpp/language/modules"), [TU-local](tu_local "cpp/language/tu local") | | UB | [Undefined Behavior](ub "cpp/language/ub") | | | UDC | [User-defined conversion](cast_operator "cpp/language/cast operator") operator | | | UDL | [User-Defined Literals](user_literal "cpp/language/user literal") | | | WPO | [Whole-Program Optimization](https://en.wikipedia.org/wiki/Interprocedural_optimization#WPO_and_LTO "enwiki:Interprocedural optimization") | | ### External links * [“A C++ acronym glossary” by Arthur O’Dwyer, 2019/08](https://quuxplusone.github.io/blog/2019/08/02/the-tough-guide-to-cpp-acronyms/) cpp Move assignment operator Move assignment operator ======================== A move assignment operator of class `T` is a non-template [non-static member function](member_functions "cpp/language/member functions") with the name `operator=` that takes exactly one parameter of type `T&&`, `const T&&`, `volatile T&&`, or `const volatile T&&`. ### Syntax | | | | | --- | --- | --- | | class-name `&` class-name `:: operator=` ( class-name `&&` ) | (1) | (since C++11) | | class-name `&` class-name `:: operator=` ( class-name `&&` ) = `default;` | (2) | (since C++11) | | class-name `&` class-name `:: operator=` ( class-name `&&` ) = `delete;` | (3) | (since C++11) | ### Explanation 1) Typical declaration of a move assignment operator. 2) Forcing a move assignment operator to be generated by the compiler. 3) Avoiding implicit move assignment. The move assignment operator is called whenever it is selected by [overload resolution](overload_resolution "cpp/language/overload resolution"), e.g. when an object appears on the left-hand side of an assignment expression, where the right-hand side is an rvalue of the same or implicitly convertible type. Move assignment operators typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc.), rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. For example, move-assigning from a `[std::string](../string/basic_string "cpp/string/basic string")` or from a `[std::vector](../container/vector "cpp/container/vector")` may result in the argument being left empty. This is not, however, a guarantee. A move assignment is less, not more restrictively defined than ordinary assignment; where ordinary assignment must leave two copies of data at completion, move assignment is required to leave only one. ### Implicitly-declared move assignment operator If no user-defined move assignment operators are provided for a class type (`struct`, `class`, or `union`), and all of the following is true: * there are no user-declared [copy constructors](copy_constructor "cpp/language/copy constructor"); * there are no user-declared [move constructors](move_constructor "cpp/language/move constructor"); * there are no user-declared [copy assignment operators](copy_assignment "cpp/language/copy assignment"); * there is no user-declared [destructor](destructor "cpp/language/destructor"), then the compiler will declare a move assignment operator as an `inline public` member of its class with the signature `T& T::operator=(T&&)`. A class can have multiple move assignment operators, e.g. both `T& T::operator=(const T&&)` and `T& T::operator=(T&&)`. If some user-defined move assignment operators are present, the user may still force the generation of the implicitly declared move assignment operator with the keyword `default`. The implicitly-declared (or defaulted on its first declaration) move assignment operator has an exception specification as described in [dynamic exception specification](except_spec "cpp/language/except spec") (until C++17)[noexcept specification](noexcept_spec "cpp/language/noexcept spec") (since C++17). Because some assignment operator (move or copy) is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration. ### Deleted implicitly-declared move assignment operator The implicitly-declared or defaulted move assignment operator for class `T` is defined as *deleted* if any of the following is true: * `T` has a non-static data member that is `const`; * `T` has a non-static data member of a reference type; * `T` has a non-static data member or a direct base class that cannot be move-assigned (has deleted, inaccessible, or ambiguous move assignment operator). A deleted implicitly-declared move assignment operator is ignored by [overload resolution](overload_resolution "cpp/language/overload resolution"). ### Trivial move assignment operator The move assignment operator for class `T` is trivial if all of the following is true: * It is not user-provided (meaning, it is implicitly-defined or defaulted); * `T` has no virtual member functions; * `T` has no virtual base classes; * the move assignment operator selected for every direct base of `T` is trivial; * the move assignment operator selected for every non-static class type (or array of class type) member of `T` is trivial. A trivial move assignment operator performs the same action as the trivial copy assignment operator, that is, makes a copy of the object representation as if by `[std::memmove](../string/byte/memmove "cpp/string/byte/memmove")`. All data types compatible with the C language (POD types) are trivially move-assignable. ### Eligible move assignment operator | | | | --- | --- | | A move assignment operator is eligible if it is not deleted. | (until C++20) | | A move assignment operator is eligible if.* it is not deleted, and * its [associated constraints](constraints "cpp/language/constraints"), if any, are satisfied, and * no move assignment operator with the same first parameter type and the same cv/ref-qualifiers (if any) is [more constrained](constraints#Partial_ordering_of_constraints "cpp/language/constraints") than it. | (since C++20) | Triviality of eligible move assignment operators determines whether the class is a [trivially copyable type](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"). ### Implicitly-defined move assignment operator If the implicitly-declared move assignment operator is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if [odr-used](definition#ODR-use "cpp/language/definition") or [needed for constant evaluation](constant_expression#Functions_and_variables_needed_for_constant_evaluation "cpp/language/constant expression") (since C++14). For `union` types, the implicitly-defined move assignment operator copies the object representation (as by `[std::memmove](../string/byte/memmove "cpp/string/byte/memmove")`). For non-union class types (`class` and `struct`), the move assignment operator performs full member-wise move assignment of the object's direct bases and immediate non-static members, in their declaration order, using built-in assignment for the scalars, memberwise move-assignment for arrays, and move assignment operator for class types (called non-virtually). | | | | --- | --- | | The implicitly-defined move assignment operator for a class `T` is [`constexpr`](constexpr "cpp/language/constexpr") if.* `T` is a [literal type](../named_req/literaltype "cpp/named req/LiteralType"), and * the assignment operator selected to move each direct base class subobject is a constexpr function, and * for each non-static data member of `T` that is of class type (or array thereof), the assignment operator selected to move that member is a constexpr function. | (since C++14) | As with copy assignment, it is unspecified whether virtual base class subobjects that are accessible through more than one path in the inheritance lattice, are assigned more than once by the implicitly-defined move assignment operator: ``` struct V { V& operator=(V&& other) { // this may be called once or twice // if called twice, 'other' is the just-moved-from V subobject return *this; } }; struct A : virtual V {}; // operator= calls V::operator= struct B : virtual V {}; // operator= calls V::operator= struct C : B, A {}; // operator= calls B::operator=, then A::operator= // but they may only call V::operator= once int main() { C c1, c2; c2 = std::move(c1); } ``` ### Notes If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an [*rvalue*](value_category "cpp/language/value category") (either a [*prvalue*](value_category "cpp/language/value category") such as a nameless temporary or an [*xvalue*](value_category "cpp/language/value category") such as the result of `std::move`), and selects the copy assignment if the argument is an [*lvalue*](value_category "cpp/language/value category") (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable. It is unspecified whether virtual base class subobjects that are accessible through more than one path in the inheritance lattice, are assigned more than once by the implicitly-defined move assignment operator (same applies to [copy assignment](copy_assignment "cpp/language/copy assignment")). See [assignment operator overloading](operators#Assignment_operator "cpp/language/operators") for additional detail on the expected behavior of a user-defined move-assignment operator. ### Example ``` #include <string> #include <iostream> #include <utility> struct A { std::string s; A() : s("test") {} A(const A& o) : s(o.s) { std::cout << "move failed!\n"; } A(A&& o) : s(std::move(o.s)) {} A& operator=(const A& other) { s = other.s; std::cout << "copy assigned\n"; return *this; } A& operator=(A&& other) { s = std::move(other.s); std::cout << "move assigned\n"; return *this; } }; A f(A a) { return a; } struct B : A { std::string s2; int n; // implicit move assignment operator B& B::operator=(B&&) // calls A's move assignment operator // calls s2's move assignment operator // and makes a bitwise copy of n }; struct C : B { ~C() {} // destructor prevents implicit move assignment }; struct D : B { D() {} ~D() {} // destructor would prevent implicit move assignment D& operator=(D&&) = default; // force a move assignment anyway }; int main() { A a1, a2; std::cout << "Trying to move-assign A from rvalue temporary\n"; a1 = f(A()); // move-assignment from rvalue temporary std::cout << "Trying to move-assign A from xvalue\n"; a2 = std::move(a1); // move-assignment from xvalue std::cout << "Trying to move-assign B\n"; B b1, b2; std::cout << "Before move, b1.s = \"" << b1.s << "\"\n"; b2 = std::move(b1); // calls implicit move assignment std::cout << "After move, b1.s = \"" << b1.s << "\"\n"; std::cout << "Trying to move-assign C\n"; C c1, c2; c2 = std::move(c1); // calls the copy assignment operator std::cout << "Trying to move-assign D\n"; D d1, d2; d2 = std::move(d1); } ``` Output: ``` Trying to move-assign A from rvalue temporary move assigned Trying to move-assign A from xvalue move assigned Trying to move-assign B Before move, b1.s = "test" move assigned After move, b1.s = "" Trying to move-assign C copy assigned Trying to move-assign D move assigned ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1402](https://cplusplus.github.io/CWG/issues/1402.html) | C++11 | a defaulted move assignment operator that wouldcall a non-trivial copy assignment operator was deleted;a defaulted move assignment operator thatis deleted still participated in overload resolution | allows call to suchcopy assignmentoperator; made ignoredin overload resolution | | [CWG 1806](https://cplusplus.github.io/CWG/issues/1806.html) | C++11 | specification for a defaulted move assignment operatorinvolving a virtual base class was missing | added | | [CWG 2094](https://cplusplus.github.io/CWG/issues/2094.html) | C++11 | a volatile subobject made of a defaultedmove assignment operator non-trivial ([CWG issue 496](https://cplusplus.github.io/CWG/issues/496.html)) | triviality not affected | | [CWG 2180](https://cplusplus.github.io/CWG/issues/2180.html) | C++11 | a defaulted move assignment operator for class `T` was not defined as deletedif `T` is abstract and has non-move-assignable direct virtual base classes | the operator is definedas deleted in this case | ### See also * [constructor](constructor "cpp/language/constructor") * [converting constructor](converting_constructor "cpp/language/converting constructor") * [copy assignment](copy_assignment "cpp/language/copy assignment") * [copy constructor](copy_constructor "cpp/language/copy constructor") * [default constructor](default_constructor "cpp/language/default constructor") * [destructor](destructor "cpp/language/destructor") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [copy initialization](copy_initialization "cpp/language/copy initialization") + [default initialization](default_initialization "cpp/language/default initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [list initialization](list_initialization "cpp/language/list initialization") + [reference initialization](reference_initialization "cpp/language/reference initialization") + [value initialization](value_initialization "cpp/language/value initialization") + [zero initialization](zero_initialization "cpp/language/zero initialization") * [move constructor](move_constructor "cpp/language/move constructor")
programming_docs
cpp Increment/decrement operators Increment/decrement operators ============================= Increment/decrement operators increment or decrement the value of the object. | Operator name | Syntax | [Over​load​able](operators "cpp/language/operators") | Prototype examples (for `class T`) | | --- | --- | --- | --- | | Inside class definition | Outside class definition | | pre-increment | `++a` | Yes | `T& T::operator++();` | `T& operator++(T& a);` | | pre-decrement | `--a` | Yes | `T& T::operator--();` | `T& operator--(T& a);` | | post-increment | `a++` | Yes | `T T::operator++(int);` | `T operator++(T& a, int);` | | post-decrement | `a--` | Yes | `T T::operator--(int);` | `T operator--(T& a, int);` | | **Notes*** Prefix versions of the built-in operators return *references* and postfix versions return *values*, and typical [user-defined overloads](operators "cpp/language/operators") follow the pattern so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including `void`). * The `int` parameter is a dummy parameter used to differentiate between prefix and postfix versions of the operators. When the user-defined postfix operator is called, the value passed in that parameter is always zero, although it may be changed by calling the operator using function call notation (e.g., `a.operator++(2)` or `operator++(a, 2)`). | ### Explanation *Pre-increment* and *pre-decrement* operators increments or decrements the value of the object and returns a reference to the result. *Post-increment* and *post-decrement* creates a copy of the object, increments or decrements the value of the object and returns the copy from before the increment or decrement. | | | | --- | --- | | Using an lvalue of volatile-qualified non-class type as operand of built-in version of these operators is deprecated. | (since C++20) | #### Built-in prefix operators The prefix increment and decrement expressions have the form. | | | | | --- | --- | --- | | `++` expr | | | | `--` expr | | | 1) prefix increment (pre-increment) 2) prefix decrement (pre-decrement) The operand expr of a built-in prefix increment or decrement operator must be a modifiable (non-const) [lvalue](value_category "cpp/language/value category") of non-boolean (since C++17) arithmetic type or pointer to completely-defined [object type](type "cpp/language/type"). The expression `++x` is exactly equivalent to `x += 1` for non-boolean operands (until C++17), and the expression `--x` is exactly equivalent to `x -= 1`, that is, the prefix increment or decrement is an lvalue expression that identifies the modified operand. All arithmetic conversion rules and pointer arithmetic rules defined for [arithmetic operators](operator_arithmetic "cpp/language/operator arithmetic") apply and determine the implicit conversion (if any) applied to the operand as well as the return type of the expression. If the operand of the pre-increment operator is of type `bool`, it is set to `true` (deprecated). (until C++17). In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for every optionally volatile-qualified arithmetic type `A` other than `bool`, and for every optionally volatile-qualified pointer `P` to optionally cv-qualified object type, the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` A& operator++(A&) ``` | | | | ``` bool& operator++(bool&) ``` | | (deprecated)(until C++17) | | ``` P& operator++(P&) ``` | | | | ``` A& operator--(A&) ``` | | | | ``` P& operator--(P&) ``` | | | #### Built-in postfix operators The postfix increment and decrement expressions have the form. | | | | | --- | --- | --- | | expr `++` | | | | expr `--` | | | 1) postfix increment (post-increment) 2) postfix decrement (post-decrement) The operand expr of a built-in postfix increment or decrement operator must be a modifiable (non-const) [lvalue](value_category "cpp/language/value category") of non-boolean (since C++17) arithmetic type or pointer to completely-defined [object type](type "cpp/language/type"). The result is [prvalue](value_category "cpp/language/value category") copy of the original value of the operand. As a side-effect, the expression `x++` modifies the value of its operand as if by evaluating `x += 1` for non-boolean operands (until C++17), and the expression `x--` modifies the value of its operand as if by evaluating `x -= 1`. All arithmetic conversion rules and pointer arithmetic rules defined for [arithmetic operators](operator_arithmetic "cpp/language/operator arithmetic") apply and determine the implicit conversion (if any) applied to the operand as well as the return type of the expression. If the operand of the post-increment operator is of type `bool`, it is set to `true` (deprecated). (until C++17). In [overload resolution against user-defined operators](overload_resolution#Call_to_an_overloaded_operator "cpp/language/overload resolution"), for every optionally volatile-qualified arithmetic type `A` other than `bool`, and for every optionally volatile-qualified pointer `P` to optionally cv-qualified object type, the following function signatures participate in overload resolution: | | | | | --- | --- | --- | | ``` A operator++(A&, int) ``` | | | | ``` bool operator++(bool&, int) ``` | | (deprecated)(until C++17) | | ``` P operator++(P&, int) ``` | | | | ``` A operator--(A&, int) ``` | | | | ``` P operator--(P&, int) ``` | | | #### Example ``` #include <iostream> int main() { int n1 = 1; int n2 = ++n1; int n3 = ++ ++n1; int n4 = n1++; // int n5 = n1++ ++; // error // int n6 = n1 + ++n1; // undefined behavior std::cout << "n1 = " << n1 << '\n' << "n2 = " << n2 << '\n' << "n3 = " << n3 << '\n' << "n4 = " << n4 << '\n'; } ``` Output: ``` n1 = 5 n2 = 2 n3 = 4 n4 = 4 ``` ### Notes Because of the side-effects involved, built-in increment and decrement operators must be used with care to avoid undefined behavior due to violations of [sequencing rules](eval_order "cpp/language/eval order"). Because a temporary copy of the object is constructed during post-increment and post-decrement, *pre-increment* or *pre-decrement* operators are usually more efficient in contexts where the returned value is not used. ### Standard library Increment and decrement operators are overloaded for many standard library types. In particular, every [LegacyIterator](../named_req/iterator "cpp/named req/Iterator") overloads operator++ and every [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") overloads operator--, even if those operators are no-ops for the particular iterator. | | | --- | | overloads for arithmetic types | | [operator++operator++(int)operator--operator--(int)](../atomic/atomic/operator_arith "cpp/atomic/atomic/operator arith") | increments or decrements the atomic value by one (public member function of `std::atomic<T>`) | | [operator++operator++(int)operator--operator--(int)](../chrono/duration/operator_arith2 "cpp/chrono/duration/operator arith2") | increments or decrements the tick count (public member function of `std::chrono::duration<Rep,Period>`) | | overloads for iterator types | | [operator++operator++(int)](../memory/raw_storage_iterator/operator_arith "cpp/memory/raw storage iterator/operator arith") | advances the iterator (public member function of `std::raw_storage_iterator<OutputIt,T>`) | | [operator++operator++(int)operator+=operator+operator--operator--(int)operator-=operator-](../iterator/reverse_iterator/operator_arith "cpp/iterator/reverse iterator/operator arith") | advances or decrements the iterator (public member function of `std::reverse_iterator<Iter>`) | | [operator++operator++(int)operator+=operator+operator--operator--(int)operator-=operator-](../iterator/move_iterator/operator_arith "cpp/iterator/move iterator/operator arith") (C++11) | advances or decrements the iterator (public member function of `std::move_iterator<Iter>`) | | [operator++operator++(int)](../iterator/front_insert_iterator/operator_plus__plus_ "cpp/iterator/front insert iterator/operator++") | no-op (public member function of `std::front_insert_iterator<Container>`) | | [operator++operator++(int)](../iterator/back_insert_iterator/operator_plus__plus_ "cpp/iterator/back insert iterator/operator++") | no-op (public member function of `std::back_insert_iterator<Container>`) | | [operator++operator++(int)](../iterator/insert_iterator/operator_plus__plus_ "cpp/iterator/insert iterator/operator++") | no-op (public member function of `std::insert_iterator<Container>`) | | [operator++operator++(int)](../iterator/istream_iterator/operator_arith "cpp/iterator/istream iterator/operator arith") | advances the iterator (public member function of `std::istream_iterator<T,CharT,Traits,Distance>`) | | [operator++operator++(int)](../iterator/ostream_iterator/operator_arith "cpp/iterator/ostream iterator/operator arith") | no-op (public member function of `std::ostream_iterator<T,CharT,Traits>`) | | [operator++operator++(int)](../iterator/istreambuf_iterator/operator_arith "cpp/iterator/istreambuf iterator/operator arith") | advances the iterator (public member function of `std::istreambuf_iterator<CharT,Traits>`) | | [operator++operator++(int)](../iterator/ostreambuf_iterator/operator_arith "cpp/iterator/ostreambuf iterator/operator arith") | no-op (public member function of `std::ostreambuf_iterator<CharT,Traits>`) | | [operator++operator++(int)](../regex/regex_iterator/operator_arith "cpp/regex/regex iterator/operator arith") | advances the iterator to the next match (public member function of `std::regex_iterator<BidirIt,CharT,Traits>`) | | [operator++operator++(int)](../regex/regex_token_iterator/operator_arith "cpp/regex/regex token iterator/operator arith") | advances the iterator to the next submatch (public member function of `std::regex_token_iterator<BidirIt,CharT,Traits>`) | ### See also [Operator precedence](operator_precedence "cpp/language/operator precedence"). [Operator overloading](operators "cpp/language/operators"). | Common operators | | --- | | [assignment](operator_assignment "cpp/language/operator assignment") | **incrementdecrement** | [arithmetic](operator_arithmetic "cpp/language/operator arithmetic") | [logical](operator_logical "cpp/language/operator logical") | [comparison](operator_comparison "cpp/language/operator comparison") | [memberaccess](operator_member_access "cpp/language/operator member access") | [other](operator_other "cpp/language/operator other") | | `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b a <=> b`. | `a[b] *a &a a->b a.b a->*b a.*b`. | `a(...) a, b a ? b : c`. | | Special operators | | [`static_cast`](static_cast "cpp/language/static cast") converts one type to another related type [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") converts within inheritance hierarchies [`const_cast`](const_cast "cpp/language/const cast") adds or removes [cv](cv "cpp/language/cv") qualifiers [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") converts type to unrelated type [C-style cast](explicit_cast "cpp/language/explicit cast") converts one type to another by a mix of `static_cast`, `const_cast`, and `reinterpret_cast` [`new`](new "cpp/language/new") creates objects with dynamic storage duration [`delete`](delete "cpp/language/delete") destructs objects previously created by the new expression and releases obtained memory area [`sizeof`](sizeof "cpp/language/sizeof") queries the size of a type [`sizeof...`](sizeof... "cpp/language/sizeof...") queries the size of a [parameter pack](parameter_pack "cpp/language/parameter pack") (since C++11) [`typeid`](typeid "cpp/language/typeid") queries the type information of a type [`noexcept`](noexcept "cpp/language/noexcept") checks if an expression can throw an exception (since C++11) [`alignof`](alignof "cpp/language/alignof") queries alignment requirements of a type (since C++11). | | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/operator_incdec "c/language/operator incdec") for Increment/decrement operators | cpp Curiously Recurring Template Pattern Curiously Recurring Template Pattern ==================================== The [Curiously Recurring Template Pattern](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern "enwiki:Curiously recurring template pattern") is an idiom in which a class X derives from a class template Y, taking a template parameter Z, where Y is instantiated with Z=X. For example, ``` template<class Z> class Y {}; class X : public Y<X> {}; ``` CRTP may be used to implement "compile-time polymorphism", when a base class exposes an interface, and derived classes implement such interface. ``` #include <iostream> template <class Derived> struct Base { void name() { (static_cast<Derived*>(this))->impl(); } }; struct D1 : public Base<D1> { void impl() { std::cout << "D1::impl()\n"; } }; struct D2 : public Base<D2> { void impl() { std::cout << "D2::impl()\n"; } }; int main() { Base<D1> b1; b1.name(); Base<D2> b2; b2.name(); D1 d1; d1.name(); D2 d2; d2.name(); } ``` Output: ``` D1::impl() D2::impl() D1::impl() D2::impl() ``` ### See also | | | | --- | --- | | [enable\_shared\_from\_this](../memory/enable_shared_from_this "cpp/memory/enable shared from this") (C++11) | allows an object to create a `shared_ptr` referring to itself (class template) | | [ranges::view\_interface](../ranges/view_interface "cpp/ranges/view interface") (C++20) | helper class template for defining a [`view`](../ranges/view "cpp/ranges/view"), using the **curiously recurring template pattern** (class template) | cpp inline specifier `inline` specifier =================== The `inline` specifier, when used in a function's [decl-specifier-seq](declarations#Specifiers "cpp/language/declarations"), declares the function to be an *inline function*. A function defined entirely inside a [class/struct/union definition](classes "cpp/language/classes"), whether it's a member function or a non-member `friend` function, is implicitly an inline function unless it is attached to a [named module](modules#Module_declarations "cpp/language/modules") (since C++20). | | | | --- | --- | | A function declared `constexpr` is implicitly an inline function. A deleted function is implicitly an inline function: its (deleted) definition can appear in more than one translation unit. | (since C++11) | | | | | --- | --- | | The `inline` specifier, when used in a [decl-specifier-seq](declarations#Specifiers "cpp/language/declarations") of a variable with static storage duration (static class member or namespace-scope variable), declares the variable to be an *inline variable*. A static member variable (but not a namespace-scope variable) declared `constexpr` is implicitly an inline variable. | (since C++17) | ### Explanation An *inline function* or *inline variable* (since C++17) has the following properties: 1. The definition of an inline function or variable (since C++17) must be reachable in the translation unit where it is accessed (not necessarily before the point of access). 2. An inline function or variable (since C++17) with [external linkage](storage_duration#external_linkage "cpp/language/storage duration") (e.g. not declared `static`) has the following additional properties: 1. There may be [more than one definition](definition#One_Definition_Rule "cpp/language/definition") of an inline function or variable (since C++17) in the program as long as each definition appears in a different translation unit and (for non-static inline functions and variables (since C++17)) all definitions are identical. For example, an inline function or an inline variable (since C++17) may be defined in a header file that is included in multiple source files. 2. It must be declared `inline` in every translation unit. 3. It has the same address in every translation unit. In an inline function, * Function-local static objects in all function definitions are shared across all translation units (they all refer to the same object defined in one translation unit) * Types defined in all function definitions are also the same in all translation units. | | | | --- | --- | | Inline const variables at namespace scope have [external linkage](storage_duration#external_linkage "cpp/language/storage duration") by default (unlike the non-inline non-volatile const-qualified variables). | (since C++17) | The original intent of the `inline` keyword was to serve as an indicator to the optimizer that [inline substitution of a function](https://en.wikipedia.org/wiki/inline_expansion "enwiki:inline expansion") is preferred over function call, that is, instead of executing the function call CPU instruction to transfer control to the function body, a copy of the function body is executed without generating the call. This avoids overhead created by the function call (passing the arguments and retrieving the result) but it may result in a larger executable as the code for the function has to be repeated multiple times. Since this meaning of the keyword `inline` is non-binding, compilers are free to use inline substitution for any function that's not marked `inline`, and are free to generate function calls to any function marked `inline`. Those optimization choices do not change the rules regarding multiple definitions and shared statics listed above. | | | | --- | --- | | Because the meaning of the keyword `inline` for functions came to mean "multiple definitions are permitted" rather than "inlining is preferred", that meaning was extended to variables. | (since C++17) | #### Notes If an inline function or variable (since C++17) with external linkage is defined differently in different translation units, the behavior is undefined. The `inline` specifier cannot be used with a function or variable (since C++17) declaration at block scope (inside another function). The `inline` specifier cannot re-declare a function or variable (since C++17) that was already defined in the translation unit as non-inline. The implicitly-generated member functions and any member function declared as defaulted on its first declaration are inline just like any other function defined inside a class definition. If an inline function is declared in different translation units, the accumulated sets of [default arguments](default_arguments "cpp/language/default arguments") must be the same at the end of each translation unit. In C, inline functions do not have to be declared `inline` in every translation unit (at most one may be non-`inline` or `extern inline`), the function definitions do not have to be identical (but the behavior of the program is unspecified if it depends on which one is called), and the function-local statics are distinct between different definitions of the same function. | | | | --- | --- | | See [static data members](static "cpp/language/static") for additional rules about inline static members. Inline variables eliminate the main obstacle to packaging C++ code as header-only libraries. | (since C++17) | ### Example | | | | --- | --- | | Header file "example.h": ``` #ifndef EXAMPLE_H #define EXAMPLE_H #include <atomic> // function included in multiple source files must be inline inline int sum(int a, int b) { return a + b; } // variable with external linkage included in multiple source files must be inline inline std::atomic<int> counter(0); #endif ``` Source file #1: ``` #include "example.h" int a() { ++counter; return sum(1, 2); } ``` Source file #2: ``` #include "example.h" int b() { ++counter; return sum(3, 4); } ``` | | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 281](https://cplusplus.github.io/CWG/issues/281.html) | C++98 | a friend function declaration could use the inline specifiereven if the friended function is not an inline function | prohibit such uses | | [CWG 317](https://cplusplus.github.io/CWG/issues/317.html) | C++98 | a function could be declared inline even if it has a non-inlinedefinition in the same translation unit before the declaration | the program is ill-formed in this case | | [CWG 765](https://cplusplus.github.io/CWG/issues/765.html) | C++98 | a type defined in an inline function mightbe different in different translation units | such types are the samein all translation units | | [CWG 1823](https://cplusplus.github.io/CWG/issues/1823.html) | C++98 | string literals in all definitions of an inlinefunction were shared across all translation units | the requirement is removed due toconsistency and implementations | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/inline "c/language/inline") for `inline` |
programming_docs
cpp sizeof operator sizeof operator =============== Queries size of the object or type. Used when actual size of the object must be known. ### Syntax | | | | | --- | --- | --- | | `sizeof(` type `)` | (1) | | | `sizeof` expression | (2) | | Both versions are constant expressions of type `[std::size\_t](../types/size_t "cpp/types/size t")`. ### Explanation 1) Yields the size in bytes of the [object representation](object "cpp/language/object") of type. 2) Yields the size in bytes of the object representation of the type of expression, if that expression is evaluated. ### Notes Depending on the computer architecture, a [byte](https://en.wikipedia.org/wiki/Byte "enwiki:Byte") may consist of 8 *or more* bits, the exact number being recorded in `[CHAR\_BIT](../types/climits "cpp/types/climits")`. The following `sizeof` expressions always evaluate to `1`: * `sizeof(char)` * `sizeof(signed char)` * `sizeof(unsigned char)` | | | | --- | --- | | * `sizeof([std::byte](http://en.cppreference.com/w/cpp/types/byte))` | (since C++17) | | | | | --- | --- | | * `sizeof(char8_t)` | (since C++20) | `sizeof` cannot be used with function types, incomplete types, or bit-field lvalues (until C++11)glvalues (since C++11). When applied to a reference type, the result is the size of the referenced type. When applied to a class type, the result is the number of bytes occupied by a complete object of that class, including any additional padding required to place such object in an array. The number of bytes occupied by a [potentially-overlapping subobject](object#Subobjects "cpp/language/object") may be less than the size of that object. The result of `sizeof` is always nonzero, even if applied to an empty class type. When applied to an expression, `sizeof` does [not evaluate the expression](expressions#Unevaluated_expressions "cpp/language/expressions"), and even if the expression designates a polymorphic object, the result is the size of the static type of the expression. Lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversions are not performed. [Temporary materialization](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion"), however, is (formally) performed for prvalue arguments: the program is ill-formed if the argument is not destructible. (since C++17). ### Keywords [`sizeof`](../keyword/sizeof "cpp/keyword/sizeof"). ### Example The example output corresponds to a system with 64-bit pointers and 32-bit int. ``` #include <iostream> struct Empty {}; struct Base { int a; }; struct Derived : Base { int b; }; struct Bit { unsigned bit: 1; }; struct CharChar { char c; char c2; }; struct CharCharInt { char c; char c2; int i; }; struct IntCharChar { int i; char c; char c2; }; struct CharIntChar { char c; int i; char c2; }; struct CharShortChar { char c; short s; char c2; }; int main() { Empty e; Derived d; Base& b = d; [[maybe_unused]] Bit bit; int a[10]; std::cout << "1) sizeof empty class: " << sizeof e << '\n' << "2) sizeof pointer: " << sizeof &e << '\n' // << "3) sizeof function: " << sizeof(void()) << '\n' // error // << "4) sizeof incomplete type: " << sizeof(int[]) << '\n' // error // << "5) sizeof bit field: " << sizeof bit.bit << '\n' // error << "6) sizeof(Bit) class: " << sizeof(Bit) << '\n' << "7) sizeof(int[10]) array of 10 int: " << sizeof(int[10]) << '\n' << "8) sizeof a array of 10 int: " << sizeof a << '\n' << "9) length of array of 10 int: " << ((sizeof a) / (sizeof *a)) << '\n' << "A) length of array of 10 int (2): " << ((sizeof a) / (sizeof a[0])) << '\n' << "B) sizeof the Derived class: " << sizeof d << '\n' << "C) sizeof the Derived through Base: " << sizeof b << '\n' << "D) sizeof(unsigned) " << sizeof(unsigned) << '\n' << "E) sizeof(int) " << sizeof(int) << '\n' << "F) sizeof(short) " << sizeof(short) << '\n' << "G) sizeof(char) " << sizeof(char) << '\n' << "H) sizeof(CharChar) " << sizeof(CharChar) << '\n' << "I) sizeof(CharCharInt) " << sizeof(CharCharInt) << '\n' << "J) sizeof(IntCharChar) " << sizeof(IntCharChar) << '\n' << "K) sizeof(CharIntChar) " << sizeof(CharIntChar) << '\n' << "L) sizeof(CharShortChar) " << sizeof(CharShortChar) << '\n'; } ``` Possible output: ``` 1) sizeof empty class: 1 2) sizeof pointer: 8 6) sizeof(Bit) class: 4 7) sizeof(int[10]) array of 10 int: 40 8) sizeof a array of 10 int: 40 9) length of array of 10 int: 10 A) length of array of 10 int (2): 10 B) sizeof the Derived class: 8 C) sizeof the Derived through Base: 4 D) sizeof(unsigned) 4 E) sizeof(int) 4 F) sizeof(short) 2 G) sizeof(char) 1 H) sizeof(CharChar) 2 I) sizeof(CharCharInt) 8 J) sizeof(IntCharChar) 8 K) sizeof(CharIntChar) 12 L) sizeof(CharShortChar) 6 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1553](https://cplusplus.github.io/CWG/issues/1553.html) | C++11 | `sizeof` could be used with bit-field xvalues | prohibited | ### See also | | | | --- | --- | | [`alignof` operator](alignof "cpp/language/alignof")(C++11) | queries alignment requirements of a type | | [`sizeof...` operator](sizeof... "cpp/language/sizeof...")(C++11) | queries the number of elements in a [parameter pack](parameter_pack "cpp/language/parameter pack") | | [C documentation](https://en.cppreference.com/w/c/language/sizeof "c/language/sizeof") for `sizeof` | cpp operator overloading operator overloading ==================== Customizes the C++ operators for operands of user-defined types. ### Syntax Overloaded operators are [functions](functions "cpp/language/functions") with special function names: | | | | | --- | --- | --- | | `operator` op | (1) | | | `operator` type | (2) | | | `operator` `new` `operator` `new []` | (3) | | | `operator` `delete` `operator` `delete []` | (4) | | | `operator` `""` suffix-identifier | (5) | (since C++11) | | `operator` `co_await` | (6) | (since C++20) | | | | | | --- | --- | --- | | op | - | any of the following operators:`+` `-` `*` `/` `%` `^` `&` `|` `~` `!` `=` `<` `>` `+=` `-=` `*=` `/=` `%=` `^=` `&=` `|=` `<<` `>>` `>>=` `<<=` `==` `!=` `<=` `>=` `<=>` (since C++20) `&&` `||` `++` `--` `,` `->*` `->` `( )` `[ ]` | 1) overloaded operator; 2) [user-defined conversion function](cast_operator "cpp/language/cast operator"); 3) [allocation function](../memory/new/operator_new "cpp/memory/new/operator new"); 4) [deallocation function](../memory/new/operator_delete "cpp/memory/new/operator delete"); 5) [user-defined literal](user_literal "cpp/language/user literal"); 6) overloaded `co_await` operator for use in [co\_await expressions](coroutines#co_await "cpp/language/coroutines"). ### Overloaded operators When an operator appears in an [expression](expressions "cpp/language/expressions"), and at least one of its operands has a [class type](class "cpp/language/class") or an [enumeration type](enum "cpp/language/enum"), then [overload resolution](overload_resolution "cpp/language/overload resolution") is used to determine the user-defined function to be called among all the functions whose signatures match the following: | Expression | As member function | As non-member function | Example | | --- | --- | --- | --- | | @a | (a).operator@ ( ) | operator@ (a) | `![std::cin](http://en.cppreference.com/w/cpp/io/cin)` calls `[std::cin](http://en.cppreference.com/w/cpp/io/cin).operator!()` | | a@b | (a).operator@ (b) | operator@ (a, b) | `[std::cout](http://en.cppreference.com/w/cpp/io/cout) << 42` calls `[std::cout](http://en.cppreference.com/w/cpp/io/cout).operator<<(42)` | | a=b | (a).operator= (b) | cannot be non-member | Given `[std::string](http://en.cppreference.com/w/cpp/string/basic_string) s;`, `s = "abc";` calls `s.operator=("abc")` | | a(b...) | (a).operator()(b...) | cannot be non-member | Given `[std::random\_device](http://en.cppreference.com/w/cpp/numeric/random/random_device) r;`, `auto n = r();` calls `r.operator()()` | | a[b] | (a).operator[](b) | cannot be non-member | Given `[std::map](http://en.cppreference.com/w/cpp/container/map)<int, int> m;`, `m[1] = 2;` calls `m.operator[](1)` | | a-> | (a).operator-> ( ) | cannot be non-member | Given `[std::unique\_ptr](http://en.cppreference.com/w/cpp/memory/unique_ptr)<S> p;`, `p->bar()` calls `p.operator->()` | | a@ | (a).operator@ (0) | operator@ (a, 0) | Given `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<int>::iterator i;`, `i++` calls `i.operator++(0)` | | in this table, `@` is a placeholder representing all matching operators: all prefix operators in @a, all postfix operators other than -> in a@, all infix operators other than = in a@b. | | | | | --- | --- | | In addition, for comparison operators `==`, `!=`, `<`, `>`, `<=`, `>=`, `<=>`, overload resolution also considers the *rewritten candidates* generated from `operator==` or `operator<=>`. | (since C++20) | Note: for overloading [`co_await`](coroutines#co_await "cpp/language/coroutines"), (since C++20)[user-defined conversion functions](cast_operator "cpp/language/cast operator"), [user-defined literals](user_literal "cpp/language/user literal"), [allocation](../memory/new/operator_new "cpp/memory/new/operator new") and [deallocation](../memory/new/operator_delete "cpp/memory/new/operator delete") see their respective articles. Overloaded operators (but not the built-in operators) can be called using function notation: ``` std::string str = "Hello, "; str.operator+=("world"); // same as str += "world"; operator<<(operator<<(std::cout, str) , '\n'); // same as std::cout << str << '\n'; // (since C++17) except for sequencing ``` ### Restrictions * The operators `::` (scope resolution), `.` (member access), `.*` (member access through pointer to member), and `?:` (ternary conditional) cannot be overloaded. * New operators such as `**`, `<>`, or `&|` cannot be created. * It is not possible to change the precedence, grouping, or number of operands of operators. * The overload of operator `->` must either return a raw pointer, or return an object (by reference or by value) for which operator `->` is in turn overloaded. * The overloads of operators `&&` and `||` lose short-circuit evaluation. | | | | --- | --- | | * `&&`, `||`, and `,` (comma) lose their special [sequencing properties](eval_order "cpp/language/eval order") when overloaded and behave like regular function calls even when they are used without function-call notation. | (until C++17) | ### Canonical implementations Besides the restrictions above, the language puts no other constraints on what the overloaded operators do, or on the return type (it does not participate in overload resolution), but in general, overloaded operators are expected to behave as similar as possible to the built-in operators: `operator+` is expected to add, rather than multiply its arguments, `operator=` is expected to assign, etc. The related operators are expected to behave similarly (`operator+` and `operator+=` do the same addition-like operation). The return types are limited by the expressions in which the operator is expected to be used: for example, assignment operators return by reference to make it possible to write `a = b = c = d`, because the built-in operators allow that. Commonly overloaded operators have the following typical, canonical forms:[[1]](#cite_note-1) #### Assignment operator The assignment operator (`operator=`) has special properties: see [copy assignment](copy_assignment "cpp/language/copy assignment") and [move assignment](move_assignment "cpp/language/move assignment") for details. The canonical copy-assignment operator is expected to [perform no action on self-assignment](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c62-make-copy-assignment-safe-for-self-assignment), and to return the lhs by reference: ``` // copy assignment T& operator=(const T& other) { // Guard self assignment if (this == &other) return *this; // assume *this manages a reusable resource, such as a heap-allocated buffer mArray if (size != other.size) // resource in *this cannot be reused { delete[] mArray; // release resource in *this mArray = nullptr; size = 0; // preserve invariants in case next line throws mArray = new int[other.size]; // allocate resource in *this size = other.size; } std::copy(other.mArray, other.mArray + other.size, mArray); return *this; } ``` | | | | --- | --- | | The canonical move assignment is expected to [leave the moved-from object in valid state](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c64-a-move-operation-should-move-and-leave-its-source-in-a-valid-state) (that is, a state with class invariants intact), and either [do nothing](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c65-make-move-assignment-safe-for-self-assignment) or at least leave the object in a valid state on self-assignment, and return the lhs by reference to non-const, and be noexcept: ``` // move assignment T& operator=(T&& other) noexcept { // Guard self assignment if (this == &other) return *this; // delete[]/size=0 would also be ok delete[] mArray; // release resource in *this mArray = std::exchange(other.mArray, nullptr); // leave other in valid state size = std::exchange(other.size, 0); return *this; } ``` | (since C++11) | In those situations where copy assignment cannot benefit from resource reuse (it does not manage a heap-allocated array and does not have a (possibly transitive) member that does, such as a member `[std::vector](../container/vector "cpp/container/vector")` or `[std::string](../string/basic_string "cpp/string/basic string")`), there is a popular convenient shorthand: the copy-and-swap assignment operator, which takes its parameter by value (thus working as both copy- and move-assignment depending on the value category of the argument), swaps with the parameter, and lets the destructor clean it up. ``` // copy assignment (copy-and-swap idiom) T& T::operator=(T other) noexcept // call copy or move constructor to construct other { std::swap(size, other.size); // exchange resources between *this and other std::swap(mArray, other.mArray); return *this; } // destructor of other is called to release the resources formerly managed by *this ``` This form automatically provides [strong exception guarantee](exceptions#Exception_safety "cpp/language/exceptions"), but prohibits resource reuse. #### Stream extraction and insertion The overloads of `operator>>` and `operator<<` that take a `[std::istream](http://en.cppreference.com/w/cpp/io/basic_istream)&` or `[std::ostream](http://en.cppreference.com/w/cpp/io/basic_ostream)&` as the left hand argument are known as insertion and extraction operators. Since they take the user-defined type as the right argument (`b` in a@b), they must be implemented as non-members. ``` std::ostream& operator<<(std::ostream& os, const T& obj) { // write obj to stream return os; } std::istream& operator>>(std::istream& is, T& obj) { // read obj from stream if( /* T could not be constructed */ ) is.setstate(std::ios::failbit); return is; } ``` These operators are sometimes implemented as [friend functions](friend "cpp/language/friend"). #### Function call operator When a user-defined class overloads the function call operator, `operator()`, it becomes a [FunctionObject](../named_req/functionobject "cpp/named req/FunctionObject") type. An object of such a type can be used in a function call expression: ``` // An object of this type represents a linear function of one variable a * x + b. struct Linear { double a, b; double operator()(double x) const { return a * x + b; } }; int main() { Linear f{2, 1}; // Represents function 2x + 1. Linear g{-1, 0}; // Represents function -x. // f and g are objects that can be used like a function. double f_0 = f(0); double f_1 = f(1); double g_0 = g(0); } ``` Many standard algorithms, from `[std::sort](http://en.cppreference.com/w/cpp/algorithm/sort)` to `[std::accumulate](http://en.cppreference.com/w/cpp/algorithm/accumulate)` accept [FunctionObjects](../named_req/functionobject "cpp/named req/FunctionObject") to customize behavior. There are no particularly notable canonical forms of `operator()`, but to illustrate the usage: ``` #include <algorithm> #include <vector> #include <iostream> struct Sum { int sum = 0; void operator()(int n) { sum += n; } }; int main() { std::vector<int> v = {1, 2, 3, 4, 5}; Sum s = std::for_each(v.begin(), v.end(), Sum()); std::cout << "The sum is " << s.sum << '\n'; } ``` Output: ``` The sum is 15 ``` #### Increment and decrement When the postfix increment or decrement operator appears in an expression, the corresponding user-defined function (`operator++` or `operator--`) is called with an integer argument `0`. Typically, it is implemented as `T operator++(int)` or `T operator--(int)`, where the argument is ignored. The postfix increment and decrement operators are usually implemented in terms of the prefix versions: ``` struct X { // prefix increment X& operator++() { // actual increment takes place here return *this; // return new value by reference } // postfix increment X operator++(int) { X old = *this; // copy old value operator++(); // prefix increment return old; // return old value } // prefix decrement X& operator--() { // actual decrement takes place here return *this; // return new value by reference } // postfix decrement X operator--(int) { X old = *this; // copy old value operator--(); // prefix decrement return old; // return old value } }; ``` Although the canonical implementations of the prefix increment and decrement operators return by reference, as with any operator overload, the return type is user-defined; for example the overloads of these operators for `[std::atomic](../atomic/atomic "cpp/atomic/atomic")` return by value. #### Binary arithmetic operators Binary operators are typically implemented as non-members to maintain symmetry (for example, when adding a complex number and an integer, if `operator+` is a member function of the complex type, then only `complex + integer` would compile, and not `integer + complex`). Since for every binary arithmetic operator there exists a corresponding compound assignment operator, canonical forms of binary operators are implemented in terms of their compound assignments: ``` class X { public: X& operator+=(const X& rhs) // compound assignment (does not need to be a member, { // but often is, to modify the private members) /* addition of rhs to *this takes place here */ return *this; // return the result by reference } // friends defined inside class body are inline and are hidden from non-ADL lookup friend X operator+(X lhs, // passing lhs by value helps optimize chained a+b+c const X& rhs) // otherwise, both parameters may be const references { lhs += rhs; // reuse compound assignment return lhs; // return the result by value (uses move constructor) } }; ``` #### Comparison operators Standard algorithms such as `[std::sort](http://en.cppreference.com/w/cpp/algorithm/sort)` and containers such as `[std::set](http://en.cppreference.com/w/cpp/container/set)` expect `operator<` to be defined, by default, for the user-provided types, and expect it to implement strict weak ordering (thus satisfying the [Compare](../named_req/compare "cpp/named req/Compare") requirements). An idiomatic way to implement strict weak ordering for a structure is to use lexicographical comparison provided by `[std::tie](../utility/tuple/tie "cpp/utility/tuple/tie")`: ``` struct Record { std::string name; unsigned int floor; double weight; friend bool operator<(const Record& l, const Record& r) { return std::tie(l.name, l.floor, l.weight) < std::tie(r.name, r.floor, r.weight); // keep the same order } }; ``` Typically, once `operator<` is provided, the other relational operators are implemented in terms of `operator<`. ``` inline bool operator< (const X& lhs, const X& rhs) { /* do actual comparison */ } inline bool operator> (const X& lhs, const X& rhs) { return rhs < lhs; } inline bool operator<=(const X& lhs, const X& rhs) { return !(lhs > rhs); } inline bool operator>=(const X& lhs, const X& rhs) { return !(lhs < rhs); } ``` Likewise, the inequality operator is typically implemented in terms of `operator==`: ``` inline bool operator==(const X& lhs, const X& rhs) { /* do actual comparison */ } inline bool operator!=(const X& lhs, const X& rhs) { return !(lhs == rhs); } ``` When three-way comparison (such as `[std::memcmp](../string/byte/memcmp "cpp/string/byte/memcmp")` or `[std::string::compare](../string/basic_string/compare "cpp/string/basic string/compare")`) is provided, all six two-way comparison operators may be expressed through that: ``` inline bool operator==(const X& lhs, const X& rhs) { return cmp(lhs,rhs) == 0; } inline bool operator!=(const X& lhs, const X& rhs) { return cmp(lhs,rhs) != 0; } inline bool operator< (const X& lhs, const X& rhs) { return cmp(lhs,rhs) < 0; } inline bool operator> (const X& lhs, const X& rhs) { return cmp(lhs,rhs) > 0; } inline bool operator<=(const X& lhs, const X& rhs) { return cmp(lhs,rhs) <= 0; } inline bool operator>=(const X& lhs, const X& rhs) { return cmp(lhs,rhs) >= 0; } ``` | | | | --- | --- | | The inequality operator is automatically generated by the compiler if `operator==` is defined. Likewise, the four relational operators are automatically generated by the compiler if the three-way comparison operator `operator<=>` is defined. `operator==` and `operator!=`, in turn, are generated by the compiler if `operator<=>` is defined as defaulted: ``` struct Record { std::string name; unsigned int floor; double weight; auto operator<=>(const Record&) const = default; }; // records can now be compared with ==, !=, <, <=, >, and >= ``` See [default comparisons](default_comparisons "cpp/language/default comparisons") for details. | (since C++20) | #### Array subscript operator User-defined classes that provide array-like access that allows both reading and writing typically define two overloads for `operator[]`: const and non-const variants: ``` struct T { value_t& operator[](std::size_t idx) { return mVector[idx]; } const value_t& operator[](std::size_t idx) const { return mVector[idx]; } }; ``` | | | | --- | --- | | Alternatively, they can be expressed as a single member function template using [deduced `this`](member_functions#Explicit_object_parameter "cpp/language/member functions"): ``` struct T { template<typename Self> auto& operator[](this Self&& self, std::size_t idx) { return self.mVector[idx]; } }; ``` | (since C++23) | If the value type is known to be a scalar type, the const variant should return by value. Where direct access to the elements of the container is not wanted or not possible or distinguishing between lvalue `c[i] = v;` and rvalue `v = c[i];` usage, `operator[]` may return a proxy. See for example `[std::bitset::operator[]](../utility/bitset/operator_at "cpp/utility/bitset/operator at")`. Because a subscript operator can only take one subscript until C++23, to provide multidimensional array access semantics, e.g. to implement a 3D array access `a[i][j][k] = x;`, `operator[]` has to return a reference to a 2D plane, which has to have its own `operator[]` which returns a reference to a 1D row, which has to have `operator[]` which returns a reference to the element. To avoid this complexity, some libraries opt for overloading `operator()` instead, so that 3D access expressions have the Fortran-like syntax `a(i, j, k) = x;`. | | | | --- | --- | | Since C++23, `operator[]` can take more than one subscripts. For example, an `operator[]` of a 3D array class declared as `T& operator[]([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t) x, [std::size\_t](http://en.cppreference.com/w/cpp/types/size_t) y, [std::size\_t](http://en.cppreference.com/w/cpp/types/size_t) z);` can directly access the elements. ``` // https://godbolt.org/z/993s5dK7z #include <array> #include <cassert> #include <iostream> #include <numeric> #include <tuple> template<typename T, std::size_t X, std::size_t Y, std::size_t Z> class array3d { std::array<T, X * Y * Z> a; public: array3d() = default; array3d(array3d const&) = default; constexpr T& operator[](std::size_t x, std::size_t y, std::size_t z) // C++23 { assert(x < X and y < Y and z < Z); return a[z * Y * X + y * X + x]; } constexpr auto& underlying_array() { return a; } constexpr std::tuple<std::size_t, std::size_t, std::size_t> xyz() const { return {X, Y, Z}; } }; int main() { array3d<char, 4, 3, 2> v; v[3, 2, 1] = '#'; std::cout << "v[3, 2, 1] = '" << v[3, 2, 1] << "'\n"; // fill in the underlying 1D array auto& arr = v.underlying_array(); std::iota(arr.begin(), arr.end(), 'A'); // print out as 3D array using the order: X -> Z -> Y const auto [X, Y, Z] = v.xyz(); for (auto y {0U}; y < Y; ++y) { for (auto z {0U}; z < Z; ++z) { for (auto x {0U}; x < X; ++x) std::cout << v[x, y, z] << ' '; std::cout << "│ "; } std::cout << '\n'; } } ``` Output: ``` v[3, 2, 1] = '#' A B C D │ M N O P │ E F G H │ Q R S T │ I J K L │ U V W X │ ``` | (since C++23) | #### Bitwise arithmetic operators User-defined classes and enumerations that implement the requirements of [BitmaskType](../named_req/bitmasktype "cpp/named req/BitmaskType") are required to overload the bitwise arithmetic operators `operator&`, `operator|`, `operator^`, `operator~`, `operator&=`, `operator|=`, and `operator^=`, and may optionally overload the shift operators `operator<<` `operator>>`, `operator>>=`, and `operator<<=`. The canonical implementations usually follow the pattern for binary arithmetic operators described above. #### Boolean negation operator | | | | --- | --- | | The operator `operator!` is commonly overloaded by the user-defined classes that are intended to be used in boolean contexts. Such classes also provide a user-defined conversion function to boolean type (see `[std::basic\_ios](../io/basic_ios "cpp/io/basic ios")` for the standard library example), and the expected behavior of `operator!` is to return the value opposite of `operator bool`. | (until C++11) | | Since the built-in operator `!` performs [contextual conversion to `bool`](implicit_conversion#Contextual_conversions "cpp/language/implicit conversion"), user-defined classes that are intended to be used in boolean contexts could provide only `operator bool` and need not overload `operator!`. | (since C++11) | #### Rarely overloaded operators The following operators are rarely overloaded: * The address-of operator, `operator&`. If the unary & is applied to an lvalue of incomplete type and the complete type declares an overloaded `operator&`, it is unspecified whether the operator has the built-in meaning or the operator function is called. Because this operator may be overloaded, generic libraries use `[std::addressof](../memory/addressof "cpp/memory/addressof")` to obtain addresses of objects of user-defined types. The best known example of a canonical overloaded operator& is the Microsoft class [`CComPtrBase`](https://docs.microsoft.com/en-us/cpp/atl/reference/ccomptrbase-class?view=msvc-160#operator_amp). An example of this operator's use in EDSL can be found in [boost.spirit](http://www.boost.org/doc/libs/release/libs/spirit/doc/html/spirit/qi/reference/operator/and_predicate.html). * The boolean logic operators, `operator&&` and `operator||`. Unlike the built-in versions, the overloads cannot implement short-circuit evaluation. Also unlike the built-in versions, they do not sequence their left operand before the right one. (until C++17) In the standard library, these operators are only overloaded for `[std::valarray](../numeric/valarray "cpp/numeric/valarray")`. * The comma operator, `operator,`. Unlike the built-in version, the overloads do not sequence their left operand before the right one. (until C++17) Because this operator may be overloaded, generic libraries use expressions such as `a,void(),b` instead of `a,b` to sequence execution of expressions of user-defined types. The boost library uses `operator,` in [boost.assign](http://www.boost.org/doc/libs/release/libs/assign/doc/index.html#intro), [boost.spirit](https://github.com/boostorg/spirit/blob/develop/include/boost/spirit/home/qi/string/symbols.hpp#L317), and other libraries. The database access library [SOCI](http://soci.sourceforge.net/doc.html) also overloads `operator,`. * The member access through pointer to member `operator->*`. There are no specific downsides to overloading this operator, but it is rarely used in practice. It was suggested that it could be part of [smart pointer interface](http://www.aristeia.com/Papers/DDJ_Oct_1999.pdf), and in fact is used in that capacity by actors in [boost.phoenix](http://www.boost.org/doc/libs/release/libs/phoenix/doc/html/phoenix/modules/operator.html#phoenix.modules.operator.member_pointer_operator). It is more common in EDSLs such as [cpp.react](https://github.com/schlangster/cpp.react/blob/legacy1/include/react/Signal.h#L557). ### Example ``` #include <iostream> class Fraction { // or C++17's std::gcd constexpr int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } int n, d; public: constexpr Fraction(int n, int d = 1) : n(n/gcd(n, d)), d(d/gcd(n, d)) {} constexpr int num() const { return n; } constexpr int den() const { return d; } constexpr Fraction& operator*=(const Fraction& rhs) { int new_n = n * rhs.n / gcd(n * rhs.n, d * rhs.d); d = d * rhs.d / gcd(n * rhs.n, d * rhs.d); n = new_n; return *this; } }; std::ostream& operator<<(std::ostream& out, const Fraction& f) { return out << f.num() << '/' << f.den() ; } constexpr bool operator==(const Fraction& lhs, const Fraction& rhs) { return lhs.num() == rhs.num() && lhs.den() == rhs.den(); } constexpr bool operator!=(const Fraction& lhs, const Fraction& rhs) { return !(lhs == rhs); } constexpr Fraction operator*(Fraction lhs, const Fraction& rhs) { return lhs *= rhs; } int main() { constexpr Fraction f1{3, 8}, f2{1, 2}, f3{10, 2}; std::cout << f1 << " * " << f2 << " = " << f1 * f2 << '\n' << f2 << " * " << f3 << " = " << f2 * f3 << '\n' << 2 << " * " << f1 << " = " << 2 * f1 << '\n'; static_assert(f3 == f2 * 10); } ``` Output: ``` 3/8 * 1/2 = 3/16 1/2 * 5/1 = 5/2 2 * 3/8 = 3/4 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1481](https://cplusplus.github.io/CWG/issues/1481.html) | C++98 | the non-member prefix increment operator couldonly have a parameter of class or enumeration type | no type requirement | ### See also * [Operator precedence](operator_precedence "cpp/language/operator precedence") * [Alternative operator syntax](operator_alternative "cpp/language/operator alternative") * [Argument-dependent lookup](adl "cpp/language/adl") | Common operators | | --- | | [assignment](operator_assignment "cpp/language/operator assignment") | [incrementdecrement](operator_incdec "cpp/language/operator incdec") | [arithmetic](operator_arithmetic "cpp/language/operator arithmetic") | [logical](operator_logical "cpp/language/operator logical") | [comparison](operator_comparison "cpp/language/operator comparison") | [memberaccess](operator_member_access "cpp/language/operator member access") | [other](operator_other "cpp/language/operator other") | | `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b a <=> b`. | `a[b] *a &a a->b a.b a->*b a.*b`. | `a(...) a, b a ? b : c`. | | Special operators | | [`static_cast`](static_cast "cpp/language/static cast") converts one type to another related type [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") converts within inheritance hierarchies [`const_cast`](const_cast "cpp/language/const cast") adds or removes [cv](cv "cpp/language/cv") qualifiers [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") converts type to unrelated type [C-style cast](explicit_cast "cpp/language/explicit cast") converts one type to another by a mix of `static_cast`, `const_cast`, and `reinterpret_cast` [`new`](new "cpp/language/new") creates objects with dynamic storage duration [`delete`](delete "cpp/language/delete") destructs objects previously created by the new expression and releases obtained memory area [`sizeof`](sizeof "cpp/language/sizeof") queries the size of a type [`sizeof...`](sizeof... "cpp/language/sizeof...") queries the size of a [parameter pack](parameter_pack "cpp/language/parameter pack") (since C++11) [`typeid`](typeid "cpp/language/typeid") queries the type information of a type [`noexcept`](noexcept "cpp/language/noexcept") checks if an expression can throw an exception (since C++11) [`alignof`](alignof "cpp/language/alignof") queries alignment requirements of a type (since C++11). | ### External links 1. [Operator Overloading](https://stackoverflow.com/questions/4421706/4421719#4421719) on StackOverflow C++ FAQ
programming_docs
cpp goto statement goto statement ============== Transfers control unconditionally. Used when it is otherwise impossible to transfer control to the desired location using other statements. ### Syntax | | | | | --- | --- | --- | | attr(optional) `goto` label `;` | | | ### Explanation The goto statement transfers control to the location specified by [label](statements#Labels "cpp/language/statements"). The goto statement must be in the same function as the label it is referring, it may appear before or after the label. If transfer of control exits the scope of any automatic variables (e.g. by jumping backwards to a point before the declarations of such variables or by jumping forward out of a compound statement where the variables are scoped), the destructors are called for all variables whose scope was exited, in the order opposite to the order of their construction. The `goto` statement cannot transfer control into a [try-block](try_catch "cpp/language/try catch") or into a catch-clause, but can transfer control out of a try-block or a catch-clause (the rules above regarding automatic variables in scope are followed). If transfer of control enters the scope of any automatic variables (e.g. by jumping forward over a declaration statement), the program is ill-formed (cannot be compiled), unless all variables whose scope is entered have. 1) scalar types declared without initializers 2) class types with trivial default constructors and trivial destructors declared without initializers 3) cv-qualified versions of one of the above 4) arrays of one of the above (Note: the same rules apply to all forms of transfer of control). ### Keywords [`goto`](../keyword/goto "cpp/keyword/goto"). ### Notes In the C programming language, the `goto` statement has fewer restrictions and can enter the scope of any variable other than [variable-length array](https://en.cppreference.com/w/c/language/array#Variable-length_arrays "c/language/array") or variably-modified pointer. ### Example ``` #include <iostream> struct Object { // non-trivial destructor ~Object() { std::cout << "d"; } }; struct Trivial { double d1; double d2; }; // trivial ctor and dtor int main() { int a = 10; // loop using goto label: Object obj; std::cout << a << " "; a = a - 2; if (a != 0) { goto label; // jumps out of scope of obj, calls obj destructor } std::cout << '\n'; // goto can be used to leave a multi-level loop easily for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { std::cout << "(" << x << ";" << y << ") " << '\n'; if (x + y >= 3) { goto endloop; } } } endloop: std::cout << '\n'; goto label2; // jumps into the scope of n and t int n; // no initializer Trivial t; // trivial ctor/dtor, no initializer // int x = 1; // error: has initializer // Object obj2; // error: non-trivial dtor label2: { Object obj3; goto label3; // jumps forward, out of scope of obj3 } label3: std::cout << '\n'; } ``` Output: ``` 10 d8 d6 d4 d2 (0;0) (0;1) (0;2) (1;0) (1;1) (1;2) d d ``` ### Further Reading The popular Edsger W. Dijkstra essay, [“Goto Considered Harmful”](http://david.tribble.com/text/goto.html), presents a survey of the many subtle problems the careless use of this keyword can introduce. ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/goto "c/language/goto") for `goto` | cpp static members `static` members ================= Inside a class definition, the keyword [`static`](../keywords/static "cpp/keywords/static") declares members that are not bound to class instances. Outside a class definition, it has a different meaning: see [storage duration](storage_duration "cpp/language/storage duration"). ### Syntax A declaration for a static member is a [member declaration](class#Member_specification "cpp/language/class") whose declaration specifiers contain the keyword `static`. The keyword `static` usually appears before other specifiers (which is why the syntax is often informally described as `static` data-member or `static` member-function), but may appear anywhere in the specifier sequence. The name of any static data member and static member function must be different from the name of the containing class. ### Explanation Static members of a class are not associated with the objects of the class: they are independent variables with [static or thread (since C++11) storage duration](storage_duration "cpp/language/storage duration") or regular functions. The `static` keyword is only used with the declaration of a static member, inside the class definition, but not with the definition of that static member: ``` class X { static int n; }; // declaration (uses 'static') int X::n = 1; // definition (does not use 'static') ``` The declaration inside the class body is not a definition and may declare the member to be of [incomplete type](incomplete_type "cpp/language/incomplete type") (other than `void`), including the type in which the member is declared: ``` struct Foo; struct S { static int a[]; // declaration, incomplete type static Foo x; // declaration, incomplete type static S s; // declaration, incomplete type (inside its own definition) }; int S::a[10]; // definition, complete type struct Foo {}; Foo S::x; // definition, complete type S S::s; // definition, complete type ``` | | | | --- | --- | | However, if the declaration uses [`constexpr`](constexpr "cpp/language/constexpr") or [`inline`](inline "cpp/language/inline") (since C++17) specifier, the member must be declared to have complete type. | (since C++11) | To refer to a static member `m` of class `T`, two forms may be used: qualified name `T::m` or member access expression `E.m` or `E->m`, where `E` is an expression that evaluates to `T` or `T*` respectively. When in the same class scope, the qualification is unnecessary: ``` struct X { static void f(); // declaration static int n; // declaration }; X g() { return X(); } // some function returning X void f() { X::f(); // X::f is a qualified name of static member function g().f(); // g().f is member access expression referring to a static member function } int X::n = 7; // definition void X::f() // definition { n = 1; // X::n is accessible as just n in this scope } ``` Static members obey the [class member access rules (private, protected, public)](access "cpp/language/access"). #### Static member functions Static member functions are not associated with any object. When called, they have no `this` pointer. Static member functions cannot be `virtual`, `const`, `volatile`, or [ref-qualified](member_functions#ref-qualified_member_functions "cpp/language/member functions"). The address of a static member function may be stored in a regular [pointer to function](pointer#Pointers_to_functions "cpp/language/pointer"), but not in a [pointer to member function](pointer#Pointers_to_member_functions "cpp/language/pointer"). #### Static data members Static data members are not associated with any object. They exist even if no objects of the class have been defined. There is only one instance of the static data member in the entire program with static [storage duration](storage_duration "cpp/language/storage duration"), unless the keyword [`thread_local`](../keyword/thread_local "cpp/keyword/thread local") is used, in which case there is one such object per thread with thread storage duration (since C++11). Static data members cannot be `mutable`. Static data members of a class in namespace scope have [external linkage](storage_duration "cpp/language/storage duration") if the class itself has external linkage (is not a member of [unnamed namespace](namespace#Unnamed_namespaces "cpp/language/namespace")). Local classes (classes defined inside functions) and unnamed classes, including member classes of unnamed classes, cannot have static data members. | | | | --- | --- | | A static data member may be declared [`inline`](inline "cpp/language/inline"). An inline static data member can be defined in the class definition and may specify an initializer. It does not need an out-of-class definition: ``` struct X { inline static int n = 1; }; ``` | (since C++17) | #### Constant static members If a static data member of integral or enumeration type is declared `const` (and not `volatile`), it can be initialized with an [initializer](initialization "cpp/language/initialization") in which every expression is a [constant expression](constexpr "cpp/language/constexpr"), right inside the class definition: ``` struct X { const static int n = 1; const static int m{2}; // since C++11 const static int k; }; const int X::k = 3; ``` | | | | --- | --- | | If a static data member of [LiteralType](../named_req/literaltype "cpp/named req/LiteralType") is declared `constexpr`, it must be initialized with an initializer in which every expression is a constant expression, right inside the class definition: ``` struct X { constexpr static int arr[] = { 1, 2, 3 }; // OK constexpr static std::complex<double> n = {1,2}; // OK constexpr static int k; // Error: constexpr static requires an initializer }; ``` | (since C++11) | If a const non-inline (since C++17) static data member or a constexpr static data member (since C++11)(until C++17) is [odr-used](definition#ODR-use "cpp/language/definition"), a definition at namespace scope is still required, but it cannot have an initializer. A definition may be provided even though redundant (since C++17). ``` struct X { static const int n = 1; static constexpr int m = 4; }; const int *p = &X::n, *q = &X::m; // X::n and X::m are odr-used const int X::n; // … so a definition is necessary constexpr int X::m; // … (except for X::m in C++17) ``` | | | | --- | --- | | If a static data member is declared `constexpr`, it is implicitly `inline` and does not need to be redeclared at namespace scope. This redeclaration without an initializer (formerly required as shown above) is still permitted, but is deprecated. | (since C++17) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 194](https://cplusplus.github.io/CWG/issues/194.html) | C++98 | (static) member function names can be the same as the class name | naming restriction added (including[non-static member functions](member_functions#Defect_report "cpp/language/member functions")) | ### References * C++20 standard (ISO/IEC 14882:2020): + 11.4.8 Static members [class.static] * C++17 standard (ISO/IEC 14882:2017): + 12.2.3 Static members [class.static] * C++14 standard (ISO/IEC 14882:2014): + 9.4 Static members [class.static] * C++11 standard (ISO/IEC 14882:2011): + 9.4 Static members [class.static] * C++98 standard (ISO/IEC 14882:1998): + 9.4 Static members [class.static] ### See also * [`static` storage specifier](storage_duration "cpp/language/storage duration") cpp Non-static data members Non-static data members ======================= Non-static data members are declared in a [member specification](class "cpp/language/class") of a class. ``` class S { int n; // non-static data member int& r; // non-static data member of reference type int a[2] = {1, 2}; // non-static data member with default member initializer (C++11) std::string s, *ps; // two non-static data members struct NestedS { std::string s; } d5; // non-static data member of nested type char bit : 2; // two-bit bitfield }; ``` Any [simple declarations](declarations "cpp/language/declarations") are allowed, except. * [`extern`](../keyword/extern "cpp/keyword/extern") and [`register`](../keyword/register "cpp/keyword/register") storage class specifiers are not allowed; | | | | --- | --- | | * [`thread_local`](../keyword/thread_local "cpp/keyword/thread local") storage class specifier is not allowed (but it is allowed for [static](static "cpp/language/static") data members); | (since C++11) | * [incomplete types](incomplete_type "cpp/language/incomplete type"), [abstract class types](abstract_class "cpp/language/abstract class"), and arrays thereof are not allowed: in particular, a class `C` cannot have a non-static data member of type `C`, although it can have a non-static data member of type `C&` (reference to C) or `C*` (pointer to C); * a non-static data member cannot have the same name as the name of the class if at least one user-declared constructor is present; | | | | --- | --- | | * the [`auto` specifier](auto "cpp/language/auto") cannot be used in a non-static data member declaration (although it is allowed for static data members that are [initialized in the class definition](static#Constant_static_members "cpp/language/static")). | (since C++11) | In addition, [bit field declarations](bit_field "cpp/language/bit field") are allowed. ### Layout When an object of some class `C` is created, each non-static data member of non-reference type is allocated in some part of the object representation of `C`. Whether reference members occupy any storage is implementation-defined, but their [storage duration](storage_duration "cpp/language/storage duration") is the same as that of the object in which they are members. | | | | --- | --- | | For non-[union](union "cpp/language/union") class types, [non-zero-sized](object#Subobjects "cpp/language/object") (since C++20) members not separated by an [access specifier](access "cpp/language/access") (until C++11)with the same [member access](access "cpp/language/access") (since C++11) are always allocated so that the members declared later have higher addresses within a class object. Members separated by an access specifier (until C++11)with different access control (since C++11) are allocated in unspecified order (the compiler may group them together). | (until C++23) | | For non-[union](union "cpp/language/union") class types, [non-zero-sized](object#Subobjects "cpp/language/object") members are always allocated so that the members declared later have higher addresses within a class object. Note that access control of member still affects the standard-layout property (see below). | (since C++23) | Alignment requirements may necessitate padding between members, or after the last member of a class. ### Standard-layout | | | | --- | --- | | A class is considered to be standard-layout and to have properties described below if and only if it is a [POD class](classes#POD_class "cpp/language/classes"). | (until C++11) | | A class where all non-static data members have the same access control and certain other conditions are satisfied is known as *standard-layout class* (see [standard-layout class](classes#Standard-layout_class "cpp/language/classes") for the list of requirements). | (since C++11) | Two standard-layout non-union class types may have a *common initial sequence* of non-static data members and bit-fields, for a sequence of one or more initial members (in order of declaration), if the members have layout-compatible types either both declared with `[[[no\_unique\_address](attributes/no_unique_address "cpp/language/attributes/no unique address")]]` attribute or declared without the attribute (since C++20), and either neither member is a bit-field or both are bit-fields with the same widths. ``` struct A { int a; char b; }; struct B { const int b1; volatile char b2; }; // A and B's common initial sequence is A.a, A.b and B.b1, B.b2 struct C { int c; unsigned : 0; char b; }; // A and C's common initial sequence is A.a and C.c struct D { int d; char b : 4; }; // A and D's common initial sequence is A.a and D.d struct E { unsigned int e; char b; }; // A and E's common initial sequence is empty ``` Two standard-layout non-union class types are called *layout-compatible* if they are the same type ignoring cv-qualifiers, if any, are layout-compatible [enumerations](enum "cpp/language/enum") (i.e. enumerations with the same underlying type), or if their *common initial sequence* consists of every non-static data member and bit field (in the example above, `A` and `B` are layout-compatible). Two standard-layout unions are called *layout-compatible* if they have the same number of non-static data members and corresponding non-static data members (in any order) have layout-compatible types. Standard-layout types have the following special properties: * In a standard-layout union with an active member of non-union class type `T1`, it is permitted to read a non-static data member `m` of another union member of non-union class type `T2` provided `m` is part of the common initial sequence of `T1` and `T2` (except that reading a volatile member through non-volatile glvalue is undefined). * A pointer to an object of standard-layout class type can be [reinterpret\_cast](reinterpret_cast "cpp/language/reinterpret cast") to pointer to its first non-static non-bitfield data member (if it has non-static data members) or otherwise any of its base class subobjects (if it has any), and vice versa. In other words, padding is not allowed before the first data member of a standard-layout type. Note that [strict aliasing](reinterpret_cast#Type_aliasing "cpp/language/reinterpret cast") rules still apply to the result of such cast. * The macro `[offsetof](../types/offsetof "cpp/types/offsetof")` may be used to determine the offset of any member from the beginning of a standard-layout class. ### Member initialization Non-static data members may be initialized in one of two ways: 1) In the [member initializer list](constructor "cpp/language/constructor") of the constructor. ``` struct S { int n; std::string s; S() : n(7) {} // direct-initializes n, default-initializes s }; ``` | | | | | | --- | --- | --- | --- | | 2) Through a *default member initializer*, which is a brace or equals [initializer](initialization "cpp/language/initialization") included in the member declaration and is used if the member is omitted from the member initializer list of a constructor. ``` struct S { int n = 7; std::string s{'a', 'b', 'c'}; S() {} // default member initializer will copy-initialize n, list-initialize s }; ``` If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored for that constructor. ``` #include <iostream> int x = 0; struct S { int n = ++x; S() {} // uses default member initializer S(int arg) : n(arg) {} // uses member initializer }; int main() { std::cout << x << '\n'; // prints 0 S s1; // default initializer ran std::cout << x << '\n'; // prints 1 S s2(7); // default initializer did not run std::cout << x << '\n'; // prints 1 } ``` | | | | --- | --- | | Default member initializers are not allowed for [bit field](bit_field "cpp/language/bit field") members. | (until C++20) | Members of array type cannot deduce their size from member initializers: ``` struct X { int a[] = {1, 2, 3}; // error int b[3] = {1, 2, 3}; // OK }; ``` Default member initializers are not allowed to cause the implicit definition of a defaulted [default constructor](default_constructor "cpp/language/default constructor") for the enclosing class or the exception specification of that constructor : ``` struct node { node* p = new node; // error: use of implicit or defaulted node::node() }; ``` Reference members cannot be bound to temporaries in a default member initializer (note; same rule exists for [member initializer lists](constructor#Explanation "cpp/language/constructor")). ``` struct A { A() = default; // OK A(int v) : v(v) {} // OK const int& v = 42; // OK }; A a1; // error: ill-formed binding of temporary to reference A a2(1); // OK (default member initializer ignored because v appears in a constructor) // however a2.v is a dangling reference ``` | (since C++11) | | | | | --- | --- | | It is an error if a default member initializer has a subexpression that would execute aggregate initialization which would use the same initializer: ``` struct A; extern A a; struct A { const A& a1{A{a, a}}; // OK const A& a2{A{}}; // error }; A a{a, a}; // OK ``` | (since C++14) | ### Usage The name of a non-static data member or a non-static member function can only appear in the following three situations: 1) As a part of class member access expression, in which the class either has this member or is derived from a class that has this member, including the implicit `this->` member access expressions that appear when a non-static member name is used in any of the contexts where [`this`](this "cpp/language/this") is allowed (inside member function bodies, in member initializer lists, in the in-class default member initializers). ``` struct S { int m; int n; int x = m; // OK: implicit this-> allowed in default initializers (C++11) S(int i) : m(i), n(m) // OK: implicit this-> allowed in member initializer lists { this->f(); // explicit member access expression f(); // implicit this-> allowed in member function bodies } void f(); }; ``` 2) To form a [pointer to non-static member](pointer "cpp/language/pointer"). ``` struct S { int m; void f(); }; int S::*p = &S::m; // OK: use of m to make a pointer to member void (S::*fp)() = &S::f; // OK: use of f to make a pointer to member ``` 3) (for data members only, not member functions) When used in [unevaluated operands](expressions#Unevaluated_expressions "cpp/language/expressions"). ``` struct S { int m; static const std::size_t sz = sizeof m; // OK: m in unevaluated operand }; std::size_t j = sizeof(S::m + 42); // OK: even though there is no "this" object for m ``` Notes: such uses are allowed via the resolution of [CWG issue 613](https://cplusplus.github.io/CWG/issues/613.html) in [N2253](https://wg21.link/N2253), which is treated as a change in C++11 by some compilers (e.g. clang). ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 80](https://cplusplus.github.io/CWG/issues/80.html) | C++98 | all data members cannot have the same nameas the name of the class (breaks C compatibility) | allow non-static data membersshare the class name if there isno user-declared constructor | | [CWG 190](https://cplusplus.github.io/CWG/issues/190.html) | C++98 | when determining layout compatibility,all members were considered | only consider non-static data members | | [CWG 613](https://cplusplus.github.io/CWG/issues/613.html) | C++98 | unevaluated uses of non-static data members not allowed | such uses are allowed | | [CWG 645](https://cplusplus.github.io/CWG/issues/645.html) | C++98 | it was unspecified whether bit-field andnon-bit-field members are layout compatible | not layout compatible | | [CWG 1397](https://cplusplus.github.io/CWG/issues/1397.html) | C++11 | class was regarded as completein the default member initializers | default member init cannot triggerdefinition of default constructor | | [CWG 1425](https://cplusplus.github.io/CWG/issues/1425.html) | C++98 | it was unclear whether a standard-layout objectshares the same address with the first non-staticdata member or the first base class subobject | non-static data member if present,otherwise base class subobject if present | | [CWG 1696](https://cplusplus.github.io/CWG/issues/1696.html) | C++98 | reference members could be initialized to temporaries(whose lifetime would end at the end of constructor) | such init is ill-formed | | [CWG 1719](https://cplusplus.github.io/CWG/issues/1719.html) | C++98 | differently cv-qualified types weren't layout-compatible | cv-quals ignored, spec improved | | [CWG 2254](https://cplusplus.github.io/CWG/issues/2254.html) | C++11 | pointer to standard-layout class with no datamembers can be reinterpret\_cast to its first base class | can be reinterpret\_castto any of its base classes | ### See also | | | --- | | [classes](classes "cpp/language/classes") | | [static members](static "cpp/language/static") | | [non-static member functions](member_functions "cpp/language/member functions") | | [is\_standard\_layout](../types/is_standard_layout "cpp/types/is standard layout") (C++11) | checks if a type is a [standard-layout](data_members#Standard_layout "cpp/language/data members") type (class template) | | [offsetof](../types/offsetof "cpp/types/offsetof") | byte offset from the beginning of a standard-layout type to specified member (function macro) |
programming_docs
cpp Zero-initialization Zero-initialization =================== Sets the initial value of an object to zero. ### Syntax Note that this is not the syntax for zero-initialization, which does not have a dedicated syntax in the language. These are examples of other types of initializations, which might perform zero-initialization. | | | | | --- | --- | --- | | `static` T object `;` | (1) | | | T `()` `;` T t `=` `{}` `;` T `{}` `;` (since C++11). | (2) | | | CharT array `[` n `]` `=` `"` short-sequence `";` | (3) | | ### Explanation Zero-initialization is performed in the following situations: 1) For every named variable with static or thread-local (since C++11) [storage duration](storage_duration "cpp/language/storage duration") that is not subject to [constant initialization](constant_initialization "cpp/language/constant initialization"), before any other initialization. 2) As part of [value-initialization](value_initialization "cpp/language/value initialization") sequence for non-class types and for members of value-initialized class types that have no constructors, including value initialization of elements of [aggregates](aggregate_initialization "cpp/language/aggregate initialization") for which no initializers are provided. 3) When an array of any [character type](types#Character_types "cpp/language/types") is [initialized with a string literal](aggregate_initialization#Character_arrays "cpp/language/aggregate initialization") that is too short, the remainder of the array is zero-initialized. The effects of zero-initialization are: * If `T` is a [scalar type](../named_req/scalartype "cpp/named req/ScalarType"), the object is initialized to the value obtained by [explicitly converting](explicit_cast "cpp/language/explicit cast") the integer literal `​0​` (zero) to `T`. * If `T` is a non-union class type: + all [padding bits](object#Object_representation_and_value_representation "cpp/language/object") are initialized to zero bits, + each non-static [data member](data_members "cpp/language/data members") is zero-initialized, + each non-virtual base class [subobject](object#Subobjects "cpp/language/object") is zero-initialized, and + if the object is not a base class subobject, each [virtual base class](derived_class#Virtual_base_classes "cpp/language/derived class") subobject is zero-initialized. * If `T` is a union type: + all padding bits are initialized to zero bits, and + the object’s first non-static named data member is zero-initialized. * If `T` is array type, each element is zero-initialized. * If `T` is reference type, nothing is done. ### Notes As described in [non-local initialization](initialization#Non-local_variables "cpp/language/initialization"), static and thread-local (since C++11) variables that aren't constant-initialized are zero-initialized before any other initialization takes place. If the definition of a non-class non-local variable has no initializer, then default initialization does nothing, leaving the result of the earlier zero-initialization unmodified. A zero-initialized pointer is the null pointer value of its type, even if the value of the null pointer is not integral zero. ### Example ``` #include <string> #include <iostream> struct A { int a, b, c; }; double f[3]; // zero-initialized to three 0.0's int* p; // zero-initialized to null pointer value // (even if the value is not integral 0) std::string s; // zero-initialized to indeterminate value, then // default-initialized to "" by the std::string default constructor int main(int argc, char*[]) { delete p; // safe to delete a null pointer static int n = argc; // zero-initialized to 0 then copy-initialized to argc std::cout << "n = " << n << '\n'; A a = A(); // the effect is same as: A a{}; or A a = {}; std::cout << "a = {" << a.a << ' ' << a.b << ' ' << a.c << "}\n"; } ``` Possible output: ``` n = 1 a = {0 0 0} ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 277](https://cplusplus.github.io/CWG/issues/277.html) | C++98 | pointers might be initialized with a non-constantexpression of value 0, which is not a null pointer constant | must initialize with an integralconstant expression of value 0 | | [CWG 694](https://cplusplus.github.io/CWG/issues/694.html) | C++98 | zero-initialization for class types ignored padding | padding is initialized to zero bits | | [CWG 903](https://cplusplus.github.io/CWG/issues/903.html) | C++98 | zero-initialization for scalar types set the initial value to the valueconverted from an integral constant expression with value 0 | the object is initialized to the valueconverted from the integer literal `​0​` | | [CWG 2026](https://cplusplus.github.io/CWG/issues/2026.html) | C++98 | zero-initialization was specified to alwaysoccur first, even before constant initialization | no zero-initialization ifconstant initialization applies | | [CWG 2196](https://cplusplus.github.io/CWG/issues/2196.html) | C++98 | zero-initialization for class types ignored base class subobjects | they are also zero-initialized | | [CWG 2253](https://cplusplus.github.io/CWG/issues/2253.html) | C++98 | it was unclear whether zero-initializationapplies to unnamed bit-fields | it applies (all padding bitsare initialized to zero bits) | ### See also * [constructor](constructor "cpp/language/constructor") * [copy assignment](copy_assignment "cpp/language/copy assignment") * [default constructor](default_constructor "cpp/language/default constructor") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [copy initialization](copy_initialization "cpp/language/copy initialization") + [default initialization](default_initialization "cpp/language/default initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [list initialization](list_initialization "cpp/language/list initialization") + [value initialization](value_initialization "cpp/language/value initialization") * [move assignment](move_assignment "cpp/language/move assignment") * [`new`](new "cpp/language/new") cpp PImpl PImpl ===== "Pointer to implementation" or "pImpl" is a C++ programming technique[[1]](#cite_note-1) that removes implementation details of a class from its object representation by placing them in a separate class, accessed through an opaque pointer: ``` // -------------------- // interface (widget.h) class widget { // public members private: struct impl; // forward declaration of the implementation class // One implementation example: see below for other design options and trade-offs std::experimental::propagate_const< // const-forwarding pointer wrapper std::unique_ptr< // unique-ownership opaque pointer impl>> pImpl; // to the forward-declared implementation class }; // --------------------------- // implementation (widget.cpp) struct widget::impl { // implementation details }; ``` This technique is used to construct C++ library interfaces with stable ABI and to reduce compile-time dependencies. ### Explanation Because private data members of a class participate in its object representation, affecting size and layout, and because private member functions of a class participate in [overload resolution](overload_resolution "cpp/language/overload resolution") (which takes place before member access checking), any change to those implementation details requires recompilation of all users of the class. pImpl removes this compilation dependency; changes to the implementation do not cause recompilation. Consequently, if a library uses pImpl in its ABI, newer versions of the library may change the implementation while remaining ABI-compatible with older versions. ### Trade-offs The alternatives to the pImpl idiom are. * inline implementation: private members and public members are members of the same class * pure abstract class (OOP factory): users obtain a unique pointer to a lightweight or abstract base class, the implementation details are in the derived class that overrides its virtual member functions #### Compilation firewall In simple cases, both pImpl and factory method remove compile-time dependency between the implementation and the users of the class interface. Factory method creates a hidden dependency on the vtable, and so reordering, adding, or removing virtual member functions breaks the ABI. The pImpl approach has no hidden dependencies, however if the implementation class is a class template specialization, the compilation firewall benefit is lost: the users of the interface must observe the entire template definition in order to instantiate the correct specialization. A common design approach in this case is to refactor the implementation in a way that avoids parametrization, this is another use case for the C++ Core Guidelines: * [T.61 Do not over-parametrize members](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rt-scary) and * [T.84 Use a non-template core implementation to provide an ABI-stable interface](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t84-use-a-non-template-core-implementation-to-provide-an-abi-stable-interface) For example, the following class template does not use the type `T` in its private member or in the body of `push_back`: ``` template<class T> class ptr_vector { std::vector<void*> vp; public: void push_back(T* p) { vp.push_back(p); } }; ``` Therefore, private members can be transferred to implementation as-is, and `push_back` can forward to an implementation that does not use `T` in the interface either: ``` // --------------------- // header (ptr_vector.hpp) #include <memory> class ptr_vector_base { struct impl; // does not depend on T std::unique_ptr<impl> pImpl; protected: void push_back_fwd(void*); void print() const; // ... see implementation section for special member functions public: ptr_vector_base(); ~ptr_vector_base(); }; template<class T> class ptr_vector : private ptr_vector_base { public: void push_back(T* p) { push_back_fwd(p); } void print() const { ptr_vector_base::print(); } }; // ----------------------- // source (ptr_vector.cpp) // #include "ptr_vector.hpp" #include <vector> #include <iostream> struct ptr_vector_base::impl { std::vector<void*> vp; void push_back(void* p) { vp.push_back(p); } void print() const { for (void const * const p: vp) std::cout << p << '\n'; } }; void ptr_vector_base::push_back_fwd(void* p) { pImpl->push_back(p); } ptr_vector_base::ptr_vector_base() : pImpl{std::make_unique<impl>()} {} ptr_vector_base::~ptr_vector_base() {} void ptr_vector_base::print() const { pImpl->print(); } // --------------- // user (main.cpp) // #include "ptr_vector.hpp" int main() { int x{}, y{}, z{}; ptr_vector<int> v; v.push_back(&x); v.push_back(&y); v.push_back(&z); v.print(); } ``` Possible output: ``` 0x7ffd6200a42c 0x7ffd6200a430 0x7ffd6200a434 ``` #### Runtime overhead * Access overhead: In pImpl, each call to a private member function indirects through a pointer. Each access to a public member made by a private member indirects through another pointer. Both indirections cross translation unit boundaries and so can only be optimized out by link-time optimization. Note that OO factory requires indirection across translation units to access both public data and implementation detail, and offers even fewer opportunities for the link time optimizer due to virtual dispatch. * Space overhead: pImpl adds one pointer to the public component and, if any private member needs access to a public member, another pointer is either added to the implementation component or passed as a parameter for each call to the private member that requires it. If stateful custom allocators are supported, the allocator instance also has to be stored. * Lifetime management overhead: pImpl (as well as OO factory) place the implementation object on the heap, which imposes significant runtime overhead at construction and destruction. This may be partially offset by custom allocators, since allocation size for pImpl (but not OO factory) is known at compile time. On the other hand, pImpl classes are move-friendly; refactoring a large class as movable pImpl may improve performance of algorithms that manipulate containers holding such objects, although movable pImpl has an additional source of runtime overhead: any public member function that is permitted on a moved-from object and needs access to private implementation incurs a null pointer check. #### Maintenance overhead Use of pImpl requires a dedicated translation unit (a header-only library cannot use pImpl), introduces an additional class, a set of forwarding functions, and, if allocators are used, exposes the implementation detail of allocator use in the public interface. Since virtual members are part of the interface component of pImpl, mocking a pImpl implies mocking the interface component alone. A testable pImpl is typically designed to allow full test coverage through the available interface. ### Implementation As the object of the interface type controls the lifetime of the object of the implementation type, the pointer to implementation is usually `[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")`. Because `[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")` requires that the pointed-to type is a complete type in any context where the deleter is instantiated, the special member functions must be user-declared and defined out-of-line, in the implementation file, where the implementation class is complete. Because when const member function calls a function through a non-const member pointer, the non-const overload of the implementation function is called, the pointer has to be wrapped in `[std::experimental::propagate\_const](https://en.cppreference.com/w/cpp/experimental/propagate_const "cpp/experimental/propagate const")` or equivalent. All private data members and all private non-virtual member functions are placed in the implementation class. All public, protected, and virtual members remain in the interface class (see [GOTW #100](http://herbsutter.com/gotw/_100/) for the discussion of the alternatives). If any of the private members needs to access a public or protected member, a reference or pointer to the interface may be passed to the private function as a parameter. Alternatively, the back-reference may be maintained as part of the implementation class. If non-default allocators are intended to be supported for the allocation of the implementation object, any of the usual allocator awareness patterns may be utilized, including allocator template parameter defaulting to `[std::allocator](../memory/allocator "cpp/memory/allocator")` and constructor argument of type [`std::pmr::memory_resource*`](../memory/memory_resource "cpp/memory/memory resource"). ### Notes ### Example Demonstrates a pImpl with const propagation, with back-reference passed as a parameter, without allocator awareness, and move-enabled without runtime checks: ``` // ---------------------- // interface (widget.hpp) #include <iostream> #include <memory> #include <experimental/propagate_const> class widget { class impl; std::experimental::propagate_const<std::unique_ptr<impl>> pImpl; public: void draw() const; // public API that will be forwarded to the implementation void draw(); bool shown() const { return true; } // public API that implementation has to call widget(); // even the default ctor needs to be defined in the implementation file // Note: calling draw() on default constructed object is UB explicit widget(int); ~widget(); // defined in the implementation file, where impl is a complete type widget(widget&&); // defined in the implementation file // Note: calling draw() on moved-from object is UB widget(const widget&) = delete; widget& operator=(widget&&); // defined in the implementation file widget& operator=(const widget&) = delete; }; // --------------------------- // implementation (widget.cpp) // #include "widget.hpp" class widget::impl { int n; // private data public: void draw(const widget& w) const { if(w.shown()) // this call to public member function requires the back-reference std::cout << "drawing a const widget " << n << '\n'; } void draw(const widget& w) { if(w.shown()) std::cout << "drawing a non-const widget " << n << '\n'; } impl(int n) : n(n) {} }; void widget::draw() const { pImpl->draw(*this); } void widget::draw() { pImpl->draw(*this); } widget::widget() = default; widget::widget(int n) : pImpl{std::make_unique<impl>(n)} {} widget::widget(widget&&) = default; widget::~widget() = default; widget& widget::operator=(widget&&) = default; // --------------- // user (main.cpp) // #include "widget.hpp" int main() { widget w(7); const widget w2(8); w.draw(); w2.draw(); } ``` Output: ``` drawing a non-const widget 7 drawing a const widget 8 ``` ### External links * ↑ [GotW #28](http://www.gotw.ca/gotw/028.htm) : The Fast Pimpl Idiom 1. [GotW #100](http://herbsutter.com/gotw/_100/): Compilation Firewalls cpp fold expression(since C++17) fold expression(since C++17) ============================ Reduces ([folds](https://en.wikipedia.org/wiki/Fold_(higher-order_function) "enwiki:Fold (higher-order function)")) a [parameter pack](parameter_pack "cpp/language/parameter pack") over a binary operator. ### Syntax | | | | | --- | --- | --- | | `(` pack op `...` `)` | (1) | | | `(` `...` op pack `)` | (2) | | | `(` pack op `...` op init `)` | (3) | | | `(` init op `...` op pack `)` | (4) | | 1) unary right fold 2) unary left fold 3) binary right fold 4) binary left fold | | | | | --- | --- | --- | | op | - | any of the following 32 *binary* operators: `+` `-` `*` `/` `%` `^` `&` `|` `=` `<` `>` `<<` `>>` `+=` `-=` `*=` `/=` `%=` `^=` `&=` `|=` `<<=` `>>=` `==` `!=` `<=` `>=` `&&` `||` `,` `.*` `->*`. In a binary fold, both ops must be the same. | | pack | - | an expression that contains an unexpanded [parameter pack](parameter_pack "cpp/language/parameter pack") and does not contain an operator with [precedence](operator_precedence "cpp/language/operator precedence") lower than cast at the top level (formally, a cast-expression) | | init | - | an expression that does not contain an unexpanded [parameter pack](parameter_pack "cpp/language/parameter pack") and does not contain an operator with [precedence](operator_precedence "cpp/language/operator precedence") lower than cast at the top level (formally, a cast-expression) | Note that the opening and closing parentheses are a required part of the fold expression. ### Explanation The instantiation of a *fold expression* expands the expression `e` as follows: 1) Unary right fold `(E op ...)` becomes `(E1 op (... op (EN-1 op EN)))` 2) Unary left fold `(... op E)` becomes `(((E1 op E2) op ...) op EN)` 3) Binary right fold `(E op ... op I)` becomes `(E1 op (... op (EN−1 op (EN op I))))` 4) Binary left fold `(I op ... op E)` becomes `((((I op E1) op E2) op ...) op EN)` (where `N` is the number of elements in the pack expansion). For example, ``` template<typename... Args> bool all(Args... args) { return (... && args); } bool b = all(true, true, true, false); // within all(), the unary left fold expands as // return ((true && true) && true) && false; // b is false ``` When a unary fold is used with a pack expansion of length zero, only the following operators are allowed: 1) Logical AND (`&&`). The value for the empty pack is `true` 2) Logical OR (`||`). The value for the empty pack is `false` 3) The comma operator (`,`). The value for the empty pack is `void()` ### Note If the expression used as init or as pack has an operator with precedence below cast at the top level, it must be parenthesized: ``` template<typename ...Args> int sum(Args&&... args) { // return (args + ... + 1 * 2); // Error: operator with precedence below cast return (args + ... + (1 * 2)); // OK } ``` ### Example ``` #include <iostream> #include <vector> #include <climits> #include <cstdint> #include <type_traits> #include <utility> template<typename ...Args> void printer(Args&&... args) { (std::cout << ... << args) << '\n'; } template<typename T, typename... Args> void push_back_vec(std::vector<T>& v, Args&&... args) { static_assert((std::is_constructible_v<T, Args&&> && ...)); (v.push_back(std::forward<Args>(args)), ...); } // compile-time endianness swap based on http://stackoverflow.com/a/36937049 template<class T, std::size_t... N> constexpr T bswap_impl(T i, std::index_sequence<N...>) { return (((i >> N*CHAR_BIT & std::uint8_t(-1)) << (sizeof(T)-1-N)*CHAR_BIT) | ...); } template<class T, class U = std::make_unsigned_t<T>> constexpr U bswap(T i) { return bswap_impl<U>(i, std::make_index_sequence<sizeof(T)>{}); } int main() { printer(1, 2, 3, "abc"); std::vector<int> v; push_back_vec(v, 6, 2, 45, 12); push_back_vec(v, 1, 2, 9); for (int i : v) std::cout << i << ' '; static_assert(bswap<std::uint16_t>(0x1234u)==0x3412u); static_assert(bswap<std::uint64_t>(0x0123456789abcdefULL)==0xefcdab8967452301ULL); } ``` Output: ``` 123abc 6 2 45 12 1 2 9 ``` ### References * C++17 standard (ISO/IEC 14882:2017): + 8.1.6 Fold expressions [expr.prim.fold] * C++20 standard (ISO/IEC 14882:2020): + 7.5.6 Fold expressions [expr.prim.fold] * C++23 standard (ISO/IEC 14882:2023): + 7.5.6 Fold expressions [expr.prim.fold]
programming_docs
cpp Argument-dependent lookup Argument-dependent lookup ========================= Argument-dependent lookup, also known as ADL, or Koenig lookup [[1]](#cite_note-1), is the set of rules for looking up the unqualified function names in [function-call expressions](operator_other "cpp/language/operator other"), including implicit function calls to [overloaded operators](operators "cpp/language/operators"). These function names are looked up in the namespaces of their arguments in addition to the scopes and namespaces considered by the usual [unqualified name lookup](lookup "cpp/language/lookup"). Argument-dependent lookup makes it possible to use operators defined in a different namespace. Example: ``` #include <iostream> int main() { std::cout << "Test\n"; // There is no operator<< in global namespace, but ADL // examines std namespace because the left argument is in // std and finds std::operator<<(std::ostream&, const char*) operator<<(std::cout, "Test\n"); // same, using function call notation // however, std::cout << endl; // Error: 'endl' is not declared in this namespace. // This is not a function call to endl(), so ADL does not apply endl(std::cout); // OK: this is a function call: ADL examines std namespace // because the argument of endl is in std, and finds std::endl (endl)(std::cout); // Error: 'endl' is not declared in this namespace. // The sub-expression (endl) is not a function call expression } ``` ### Details First, the argument-dependent lookup is not considered if the lookup set produced by usual [unqualified lookup](lookup "cpp/language/lookup") contains any of the following: 1) a declaration of a class member 2) a declaration of a function at block scope (that's not a [using-declaration](namespace#Using-declarations "cpp/language/namespace")) 3) any declaration that is not a function or a function template (e.g. a function object or another variable whose name conflicts with the name of the function that's being looked up) Otherwise, for every argument in a function call expression its type is examined to determine the *associated set of namespaces and classes* that it will add to the lookup. 1) For arguments of fundamental type, the associated set of namespaces and classes is empty 2) For arguments of class type (including union), the set consists of a) The class itself b) All of its direct and indirect base classes c) If the class is a [member of another class](nested_types "cpp/language/nested types"), the class of which it is a member d) The innermost enclosing namespaces of the classes added to the set 3) For arguments whose type is a [class template](class_template "cpp/language/class template") specialization, in addition to the class rules, the following types are examined and their associated classes and namespaces are added to the set a) The types of all template arguments provided for type template parameters (skipping non-type template parameters and skipping template template parameters) b) The namespaces in which any template template arguments are members c) The classes in which any template template arguments are members (if they happen to be class member templates) 4) For arguments of enumeration type, the innermost enclosing namespace of the declaration of the enumeration type is defined is added to the set. If the enumeration type is a member of a class, that class is added to the set. 5) For arguments of type pointer to T or pointer to an array of T, the type T is examined and its associated set of classes and namespaces is added to the set. 6) For arguments of function type, the function parameter types and the function return type are examined and their associated set of classes and namespaces are added to the set. 7) For arguments of type pointer to member function F of class X, the function parameter types, the function return type, and the class X are examined and their associated set of classes and namespaces are added to the set. 8) For arguments of type pointer to data member T of class X, the member type and the type X are both examined and their associated set of classes and namespaces are added to the set. 9) If the argument is the name or the [address-of expression for a set of overloaded functions](overloaded_address "cpp/language/overloaded address") (or function templates), every function in the overload set is examined and its associated set of classes and namespaces is added to the set. * Additionally, if the set of overloads is named by a [template-id](templates#template-id "cpp/language/templates"), all of its type template arguments and template template arguments (but not non-type template arguments) are examined and their associated set of classes and namespaces are added to the set. | | | | --- | --- | | If any namespace in the associated set of classes and namespaces is an [inline namespace](namespace "cpp/language/namespace"), its enclosing namespace is also added to the set. If any namespace in the associated set of classes and namespaces directly contains an inline namespace, that inline namespace is added to the set. | (since C++11) | After the associated set of classes and namespaces is determined, all declarations found in classes of this set are discarded for the purpose of further ADL processing, except namespace-scoped friend functions and function templates, as stated in point 2 below . The set of declarations found by ordinary [unqualified lookup](lookup "cpp/language/lookup") and the set of declarations found in all elements of the associated set produced by ADL, are merged, with the following special rules. 1) [using-directives](namespace#Using-directives "cpp/language/namespace") in the associated namespaces are ignored 2) namespace-scoped friend functions (and function templates) that are declared in an associated class are visible through ADL even if they are not visible through ordinary lookup 3) all names except for the functions and function templates are ignored (no collision with variables) ### Notes Because of argument-dependent lookup, non-member functions and non-member operators defined in the same namespace as a class are considered part of the public interface of that class (if they are found through ADL) [[2]](#cite_note-2). ADL is the reason behind the established idiom for swapping two objects in generic code: ``` using std::swap; swap(obj1, obj2); ``` because calling `[std::swap](http://en.cppreference.com/w/cpp/algorithm/swap)(obj1, obj2)` directly would not consider the user-defined swap() functions that could be defined in the same namespace as the types of obj1 or obj2, and just calling the unqualified `swap(obj1, obj2)` would call nothing if no user-defined overload was provided. In particular, `[std::iter\_swap](../algorithm/iter_swap "cpp/algorithm/iter swap")` and all other standard library algorithms use this approach when dealing with [Swappable](../named_req/swappable "cpp/named req/Swappable") types. Name lookup rules make it impractical to declare operators in global or user-defined namespace that operate on types from the std namespace, e.g. a custom `operator>>` or `operator+` for `[std::vector](../container/vector "cpp/container/vector")` or for `[std::pair](../utility/pair "cpp/utility/pair")` (unless the element types of the vector/pair are user-defined types, which would add their namespace to ADL). Such operators would not be looked up from template instantiations, such as the standard library algorithms. See [dependent names](dependent_name "cpp/language/dependent name") for further details. ADL can find a [friend function](friend "cpp/language/friend") (typically, an overloaded operator) that is defined entirely within a class or class template, even if it was never declared at namespace level. ``` template<typename T> struct number { number(int); friend number gcd(number x, number y) { return 0; }; // definition within // a class template }; // unless a matching declaration is provided gcd is // an invisible (except through ADL) member of this namespace void g() { number<double> a(3), b(4); a = gcd(a, b); // finds gcd because number<double> is an associated class, // making gcd visible in its namespace (global scope) // b = gcd(3, 4); // Error; gcd is not visible } ``` | | | | --- | --- | | Although a function call can be resolved through ADL even if ordinary lookup finds nothing, a function call to a [function template](function_template "cpp/language/function template") with explicitly-specified template arguments requires that there is a declaration of the template found by ordinary lookup (otherwise, it is a syntax error to encounter an unknown name followed by a less-than character). ``` namespace N1 { struct S {}; template<int X> void f(S); } namespace N2 { template<class T> void f(T t); } void g(N1::S s) { f<3>(s); // Syntax error until C++20 (unqualified lookup finds no f) N1::f<3>(s); // OK, qualified lookup finds the template 'f' N2::f<3>(s); // Error: N2::f does not take a non-type parameter // N1::f is not looked up because ADL only works // with unqualified names using N2::f; f<3>(s); // OK: Unqualified lookup now finds N2::f // then ADL kicks in because this name is unqualified // and finds N1::f } ``` | (until C++20) | In the following contexts ADL-only lookup (that is, lookup in associated namespaces only) takes place: | | | | --- | --- | | * the lookup of non-member functions `begin` and `end` performed by the [range-for](range-for "cpp/language/range-for") loop if member lookup fails | (since C++11) | * the [dependent name lookup](dependent_name#Lookup_rules "cpp/language/dependent name") from the point of template instantiation. | | | | --- | --- | | * the lookup of non-member function `get` performed by [structured binding declaration](structured_binding "cpp/language/structured binding") for tuple-like types | (since C++17) | ### Examples Example from <http://www.gotw.ca/gotw/030.htm>. ``` namespace A { struct X; struct Y; void f(int); void g(X); } namespace B { void f(int i) { f(i); // calls B::f (endless recursion) } void g(A::X x) { g(x); // Error: ambiguous between B::g (ordinary lookup) // and A::g (argument-dependent lookup) } void h(A::Y y) { h(y); // calls B::h (endless recursion): ADL examines the A namespace // but finds no A::h, so only B::h from ordinary lookup is used } } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 33](https://cplusplus.github.io/CWG/issues/33.html) | C++98 | the associated namespaces or classes are unspecified if an argument used forlookup is the address of a group of overloaded functions or a function template | specified | | [CWG 90](https://cplusplus.github.io/CWG/issues/90.html) | C++98 | the associated classes of a nested non-union class did not include itsenclosing class, but a nested union was associated with its enclosing class | non-unions also associated | | [CWG 239](https://cplusplus.github.io/CWG/issues/239.html) | C++98 | a block-scope function declaration found in the ordinaryunqualified lookup did not prevent ADL from happening | ADL not considered exceptfor using-declarations | | [CWG 997](https://cplusplus.github.io/CWG/issues/997.html) | C++98 | dependent parameter types and return types were excluded from considerationin determining the associated classes and namespaces of a function template | included | | [CWG 1690](https://cplusplus.github.io/CWG/issues/1690.html) | C++98C++11 | ADL could not find lambdas (C++11) or objectsof local class types (C++98) that are returned | they can be found | | [CWG 1691](https://cplusplus.github.io/CWG/issues/1691.html) | C++11 | ADL had surprising behaviors for opaque enumeration declarations | fixed | | [CWG 1692](https://cplusplus.github.io/CWG/issues/1692.html) | C++98 | doubly-nested classes did not have associated namespaces(their enclosing classes are not members of any namespace) | associated namespaces areextended to the innermostenclosing namespaces | ### See also * [Name lookup](lookup "cpp/language/lookup") * [Template argument deduction](function_template "cpp/language/function template") * [Overload resolution](overload_resolution "cpp/language/overload resolution") ### External links 1. Andrew Koenig: ["A Personal Note About Argument-Dependent Lookup"](https://www.drdobbs.com/cpp/a-personal-note-about-argument-dependent/232901443) 2. H. Sutter (1998) ["What's In a Class? - The Interface Principle"](http://www.gotw.ca/publications/mill02.htm) in C++ Report, 10(3) cpp Copy initialization Copy initialization =================== Initializes an object from another object. ### Syntax | | | | | --- | --- | --- | | T object `=` other`;` | (1) | | | T object `=` `{`other`};` | (2) | (until C++11) | | f`(`other`)` | (3) | | | `return` other`;` | (4) | | | `throw` object`;` `catch (`T object`)`. | (5) | | | T array`[`N`] = {`other-sequence`};` | (6) | | ### Explanation Copy initialization is performed in the following situations: 1) when a named variable (automatic, static, or thread-local) of a non-reference type `T` is declared with the initializer consisting of an equals sign followed by an expression. 2) (until C++11) when a named variable of a scalar type `T` is declared with the initializer consisting of an equals sign followed by a brace-enclosed expression (Note: as of C++11, this is classified as [list initialization](list_initialization "cpp/language/list initialization"), and narrowing conversion is not allowed). 3) when [passing an argument](operator_other#Built-in_function_call_operator "cpp/language/operator other") to a function by value 4) when [returning](return "cpp/language/return") from a function that returns by value 5) when [throwing](throw "cpp/language/throw") or [catching](try_catch "cpp/language/try catch") an exception by value 6) as part of [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization"), to initialize each element for which an initializer is provided The effects of copy initialization are: | | | | --- | --- | | * First, if `T` is a class type and the initializer is a [prvalue](value_category "cpp/language/value category") expression whose cv-unqualified type is the same class as `T`, the initializer expression itself, rather than a temporary materialized from it, is used to initialize the destination object: see [copy elision](copy_elision "cpp/language/copy elision") | (since C++17) | * If `T` is a class type and the cv-unqualified version of the type of other is `T` or a class derived from `T`, the [non-explicit constructors](converting_constructor "cpp/language/converting constructor") of `T` are examined and the best match is selected by overload resolution. The constructor is then called to initialize the object. * If `T` is a class type, and the cv-unqualified version of the type of other is not `T` or derived from `T`, or if `T` is non-class type, but the type of other is a class type, [user-defined conversion sequences](implicit_cast "cpp/language/implicit cast") that can convert from the type of other to `T` (or to a type derived from T if T is a class type and a conversion function is available) are examined and the best one is selected through overload resolution. The result of the conversion, which is a rvalue temporary (until C++11)prvalue temporary (since C++11)(until C++17)prvalue expression (since C++17) of the cv-unqualified version of `T` if a [converting constructor](converting_constructor "cpp/language/converting constructor") was used, is then used to [direct-initialize](direct_initialization "cpp/language/direct initialization") the object. The last step is usually [optimized out](copy_elision "cpp/language/copy elision") and the result of the conversion is constructed directly in the memory allocated for the target object, but the appropriate constructor (move or copy) is required to be accessible even though it's not used. (until C++17) * Otherwise (if neither `T` nor the type of other are class types), [standard conversions](implicit_cast "cpp/language/implicit cast") are used, if necessary, to convert the value of other to the cv-unqualified version of `T`. ### Notes Copy-initialization is less permissive than direct-initialization: [explicit constructors](explicit "cpp/language/explicit") are not [converting constructors](converting_constructor "cpp/language/converting constructor") and are not considered for copy-initialization. ``` struct Exp { explicit Exp(const char*) {} }; // not convertible from const char* Exp e1("abc"); // OK Exp e2 = "abc"; // Error, copy-initialization does not consider explicit constructor struct Imp { Imp(const char*) {} }; // convertible from const char* Imp i1("abc"); // OK Imp i2 = "abc"; // OK ``` In addition, the implicit conversion in copy-initialization must produce `T` directly from the initializer, while, e.g. direct-initialization expects an implicit conversion from the initializer to an argument of `T`'s constructor. ``` struct S { S(std::string) {} }; // implicitly convertible from std::string S s("abc"); // OK: conversion from const char[4] to std::string S s = "abc"; // Error: no conversion from const char[4] to S S s = "abc"s; // OK: conversion from std::string to S ``` If other is an rvalue expression, [move constructor](move_constructor "cpp/language/move constructor") will be selected by overload resolution and called during copy-initialization. There is no such term as move-initialization. [Implicit conversion](implicit_cast "cpp/language/implicit cast") is defined in terms of copy-initialization: if an object of type `T` can be copy-initialized with expression `E`, then `E` is implicitly convertible to `T`. The equals sign, `=`, in copy-initialization of a named variable is not related to the assignment operator. Assignment operator overloads have no effect on copy-initialization. ### Example ``` #include <string> #include <utility> #include <memory> struct A { operator int() { return 12;} }; struct B { B(int) {} }; int main() { std::string s = "test"; // OK: constructor is non-explicit std::string s2 = std::move(s); // this copy-initialization performs a move // std::unique_ptr<int> p = new int(1); // error: constructor is explicit std::unique_ptr<int> p(new int(1)); // OK: direct-initialization int n = 3.14; // floating-integral conversion const int b = n; // const doesn't matter int c = b; // ...either way A a; B b0 = 12; // B b1 = a; // < error: conversion from 'A' to non-scalar type 'B' requested B b2{a}; // < identical, calling A::operator int(), then B::B(int) B b3 = {a}; // < auto b4 = B{a}; // < // b0 = a; // < error, assignment operator overload needed } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 5](https://cplusplus.github.io/CWG/issues/5.html) | C++98 | the cv-qualification of the destination type is applied tothe temporary initialized by a converting constructor | the temporary is not cv-qualified | | [CWG 177](https://cplusplus.github.io/CWG/issues/177.html) | C++98 | the value category of the temporary created duringcopy-initialization of a class object is unspecified | specified as rvalue | ### See also * [copy elision](copy_elision "cpp/language/copy elision") * [converting constructor](converting_constructor "cpp/language/converting constructor") * [copy assignment](copy_assignment "cpp/language/copy assignment") * [copy constructor](copy_constructor "cpp/language/copy constructor") * [default constructor](default_constructor "cpp/language/default constructor") * [destructor](destructor "cpp/language/destructor") * [`explicit`](explicit "cpp/language/explicit") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [default initialization](default_initialization "cpp/language/default initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [initializer list](initializer_list "cpp/language/initializer list") + [list initialization](list_initialization "cpp/language/list initialization") + [reference initialization](reference_initialization "cpp/language/reference initialization") + [value initialization](value_initialization "cpp/language/value initialization") + [zero initialization](zero_initialization "cpp/language/zero initialization") * [move assignment](move_assignment "cpp/language/move assignment") * [move constructor](move_constructor "cpp/language/move constructor") * [`new`](new "cpp/language/new")
programming_docs
cpp explicit specifier `explicit` specifier ===================== | | | | | --- | --- | --- | | `explicit` | (1) | | | `explicit (` expression `)` | (2) | (since C++20) | | | | | | --- | --- | --- | | expression | - | [contextually converted constant expression of type `bool`](constant_expression#Converted_constant_expression "cpp/language/constant expression") | 1) Specifies that a constructor or conversion function (since C++11) or [deduction guide](ctad "cpp/language/ctad") (since C++17) is explicit, that is, it cannot be used for [implicit conversions](implicit_cast "cpp/language/implicit cast") and [copy-initialization](copy_initialization "cpp/language/copy initialization"). | | | | --- | --- | | 2) The `explicit` specifier may be used with a constant expression. The function is explicit if and only if that constant expression evaluates to `true`. | (since C++20) | The explicit specifier may only appear within the decl-specifier-seq of the declaration of a constructor or conversion function (since C++11) within its class definition. ### Notes A constructor with a single non-default parameter (until C++11) that is declared without the function specifier `explicit` is called a [converting constructor](converting_constructor "cpp/language/converting constructor"). Both constructors (other than [copy](copy_constructor "cpp/language/copy constructor")/[move](move_constructor "cpp/language/move constructor")) and user-defined conversion functions may be function templates; the meaning of `explicit` doesn't change. | | | | --- | --- | | A `(` token that follows `explicit` is parsed as part of the explicit specifier: ``` struct S { explicit (S)(const S&); // error in C++20, OK in C++17 explicit (operator int)(); // error in C++20, OK in C++17 }; ``` | (since C++20) | ### Example ``` struct A { A(int) { } // converting constructor A(int, int) { } // converting constructor (C++11) operator bool() const { return true; } }; struct B { explicit B(int) { } explicit B(int, int) { } explicit operator bool() const { return true; } }; int main() { A a1 = 1; // OK: copy-initialization selects A::A(int) A a2(2); // OK: direct-initialization selects A::A(int) A a3 {4, 5}; // OK: direct-list-initialization selects A::A(int, int) A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int) A a5 = (A)1; // OK: explicit cast performs static_cast if (a1) ; // OK: A::operator bool() bool na1 = a1; // OK: copy-initialization selects A::operator bool() bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization // B b1 = 1; // error: copy-initialization does not consider B::B(int) B b2(2); // OK: direct-initialization selects B::B(int) B b3 {4, 5}; // OK: direct-list-initialization selects B::B(int, int) // B b4 = {4, 5}; // error: copy-list-initialization does not consider B::B(int,int) B b5 = (B)1; // OK: explicit cast performs static_cast if (b2) ; // OK: B::operator bool() // bool nb1 = b2; // error: copy-initialization does not consider B::operator bool() bool nb2 = static_cast<bool>(b2); // OK: static_cast performs direct-initialization } ``` ### See also * [converting constructor](converting_constructor "cpp/language/converting constructor") * [initialization](initialization "cpp/language/initialization") * [copy initialization](copy_initialization "cpp/language/copy initialization") * [direct initialization](direct_initialization "cpp/language/direct initialization") cpp Floating-point literal Floating-point literal ====================== Floating-point literal defines a compile-time constant whose value is specified in the source file. ### Syntax | | | | | --- | --- | --- | | digit-sequence decimal-exponent suffix(optional) | (1) | | | digit-sequence `.` decimal-exponent(optional) suffix(optional) | (2) | | | digit-sequence(optional) `.` digit-sequence decimal-exponent(optional) suffix(optional) | (3) | | | `0x` | `0X` hex-digit-sequence hex-exponent suffix(optional) | (4) | (since C++17) | | `0x` | `0X` hex-digit-sequence `.` hex-exponent suffix(optional) | (5) | (since C++17) | | `0x` | `0X` hex-digit-sequence(optional) `.` hex-digit-sequence hex-exponent suffix(optional) | (6) | (since C++17) | 1) digit-sequence representing a whole number without a decimal separator, in this case the exponent is not optional: `1e10`, `1e-5L` 2) digit-sequence representing a whole number with a decimal separator, in this case the exponent is optional: `1.`, `1.e-2` 3) digit-sequence representing a fractional number. The exponent is optional: `3.14`, `.1f`, `0.1e-1L` 4) Hexadecimal digit-sequence representing a whole number without a radix separator. The exponent is never optional for hexadecimal floating-point literals: `0x1ffp10`, `0X0p-1` 5) Hexadecimal digit-sequence representing a whole number with a radix separator. The exponent is never optional for hexadecimal floating-point literals: `0x1.p0`, `0xf.p-1` 6) Hexadecimal digit-sequence representing a fractional number with a radix separator. The exponent is never optional for hexadecimal floating-point literals: `0x0.123p-1`, `0xa.bp10l` decimal-exponent has the form. | | | | | --- | --- | --- | | `e` | `E` exponent-sign(optional) digit-sequence | | | hex-exponent has the form. | | | | | --- | --- | --- | | `p` | `P` exponent-sign(optional) digit-sequence | | (since C++17) | exponent-sign, if present, is either `+` or `-` suffix, if present, is one of `f`, `F`, `l`, or `L`. The suffix determines the type of the floating-point literal: * (no suffix) defines `double` * `f F` defines `float` * `l L` defines `long double` | | | | --- | --- | | Optional single quotes (`'`) may be inserted between the digits as a separator; they are ignored during compilation. | (since C++14) | ### Explanation Decimal scientific notation is used, meaning that the value of the floating-point literal is the significand multiplied by the number 10 raised to the power of decimal-exponent. E.g. the mathematical meaning of `123e4` is *123×104*. | | | | --- | --- | | If the floating literal begins with the character sequence `0x` or `0X`, the floating literal is a *hexadecimal floating literal*. Otherwise, it is a *decimal floating literal*. For a *hexadecimal floating literal*, the significand is interpreted as a hexadecimal rational number, and the digit-sequence of the exponent is interpreted as the (decimal) integer power of 2 by which the significand has to be scaled. ``` double d = 0x1.4p3; // hex fraction 1.4 (decimal 1.25) scaled by 2^3, that is 10.0 ``` | (since C++17) | ### Notes The hexadecimal floating-point literals were not part of C++ until C++17, although they can be parsed and printed by the I/O functions since C++11: both C++ I/O streams when `[std::hexfloat](http://en.cppreference.com/w/cpp/io/manip/fixed)` is enabled and the C I/O streams: `[std::printf](http://en.cppreference.com/w/cpp/io/c/fprintf)`, `[std::scanf](http://en.cppreference.com/w/cpp/io/c/fscanf)`, etc. See `[std::strtof](http://en.cppreference.com/w/cpp/string/byte/strtof)` for the format description. ### Example ``` #include <iostream> #include <iomanip> #include <limits> #include <typeinfo> int main() { std::cout << "Literal " << "Printed value" << "\n58. " << 58. // double << "\n4e2 " << 4e2 // double << "\n123.456e-67 " << 123.456e-67 // double << "\n123.456e-67f " << 123.456e-67f // float, truncated to zero << "\n.1E4f " << .1E4f // float << "\n0x10.1p0 " << 0x10.1p0 // double << "\n0x1p5 " << 0x1p5 // double << "\n0x1e5 " << 0x1e5 // integer literal, not floating-point << "\n3.14'15'92 " << 3.14'15'92 // double, single quotes ignored (C++14) << "\n1.18e-4932l " << 1.18e-4932l // long double << std::setprecision(39) << "\n3.4028234e38f " << 3.4028234e38f // float << "\n3.4028234e38 " << 3.4028234e38 // double << "\n3.4028234e38l " << 3.4028234e38l // long double << '\n'; static_assert(3.4028234e38f == std::numeric_limits<float>::max()); static_assert(3.4028234e38f == // ends with 4 3.4028235e38f); // ends with 5 static_assert(3.4028234e38 != // ends with 4 3.4028235e38); // ends with 5 // Both floating-point constants below are 3.4028234e38 static_assert(3.4028234e38f != // a float (then promoted to double) 3.4028234e38); // a double } ``` Possible output: ``` Literal Printed value 58. 58 4e2 400 123.456e-67 1.23456e-65 123.456e-67f 0 .1E4f 1000 0x10.1p0 16.0625 0x1p5 32 0x1e5 485 3.14'15'92 3.14159 1.18e-4932l 1.18e-4932 3.4028234e38f 340282346638528859811704183484516925440 3.4028234e38 340282339999999992395853996843190976512 3.4028234e38l 340282339999999999995912555211526242304 ``` ### See also | | | | --- | --- | | [user-defined literals](user_literal "cpp/language/user literal")(C++11) | literals with user-defined suffix | | [C documentation](https://en.cppreference.com/w/c/language/floating_constant "c/language/floating constant") for Floating constant | cpp User-defined literals (since C++11) User-defined literals (since C++11) =================================== Allows integer, floating-point, character, and string literals to produce objects of user-defined type by defining a user-defined suffix. ### Syntax A user-defined literal is an expression of any of the following forms. | | | | | --- | --- | --- | | decimal-literal ud-suffix | (1) | | | octal-literal ud-suffix | (2) | | | hex-literal ud-suffix | (3) | | | binary-literal ud-suffix | (4) | | | fractional-constant exponent-part(optional) ud-suffix | (5) | | | digit-sequence exponent-part ud-suffix | (6) | | | character-literal ud-suffix | (7) | | | string-literal ud-suffix | (8) | | 1-4) user-defined integer literals, such as `12_km` 5-6) user-defined floating-point literals, such as `0.5_Pa` 7) user-defined character literal, such as `'c'_X` 8) user-defined string literal, such as `"abd"_L` or `u"xyz"_M` | | | | | --- | --- | --- | | decimal-literal | - | same as in [integer literal](integer_literal "cpp/language/integer literal"), a non-zero decimal digit followed by zero or more decimal digits | | octal-literal | - | same as in [integer literal](integer_literal "cpp/language/integer literal"), a zero followed by zero or more octal digits | | hex-literal | - | same as in [integer literal](integer_literal "cpp/language/integer literal"), `0x` or `0X` followed by one or more hexadecimal digits | | binary-literal | - | same as in [integer literal](integer_literal "cpp/language/integer literal"), `0b` or `0B` followed by one or more binary digits | | digit-sequence | - | same as in [floating literal](floating_literal "cpp/language/floating literal"), a sequence of decimal digits | | fractional-constant | - | same as in [floating literal](floating_literal "cpp/language/floating literal"), either a digit-sequence followed by a dot (`123.`) or an optional digit-sequence followed by a dot and another digit-sequence (`1.0` or `.12`) | | exponent-part | - | same as in [floating literal](floating_literal "cpp/language/floating literal"), the letter `e` or the letter `E` followed by optional sign, followed by digit-sequence | | character-literal | - | same as in [character literal](character_literal "cpp/language/character literal") | | string-literal | - | same as in [string literal](string_literal "cpp/language/string literal"), including raw string literals | | ud-suffix | - | an identifier, introduced by a *literal operator* or a *literal operator template* declaration (see below). All ud-suffixes introduced by a program must begin with the underscore character `_`. The standard library ud-suffixes do not begin with underscores. | | | | | --- | --- | | In the integer and floating-point digit sequences, optional separators `'` are allowed between any two digits and are ignored. | (since C++14) | If a token matches a user-defined literal syntax and a regular literal syntax, it is assumed to be a regular literal (that is, it's impossible to overload `LL` in `123LL`). When the compiler encounters a user-defined literal with ud-suffix `X`, it performs [unqualified name lookup](lookup#Unqualified_name_lookup "cpp/language/lookup"), looking for a function with the name `operator "" X`. If the lookup does not find a declaration, the program is ill-formed. Otherwise, 1) For user-defined integer literals a) if the overload set includes a literal operator with the parameter type `unsigned long long`, the user-defined literal expression is treated as a function call `operator "" X(nULL)`, where n is the literal without ud-suffix b) otherwise, the overload set must include either, but not both, a raw literal operator or a numeric literal operator template. If the overload set includes a raw literal operator, the user-defined literal expression is treated as a function call `operator "" X("n")` c) otherwise, if the overload set includes a numeric literal operator template, the user-defined literal expression is treated as a function call `operator "" X<'c1', 'c2', 'c3'..., 'ck'>()`, where c1..ck are the individual characters of `n` and all of them are from the [basic source character set](charset#Basic_source_character_set "cpp/language/charset") (until C++23)[basic character set](charset#Basic_character_set "cpp/language/charset") (since C++23). 2) For user-defined floating-point literals, a) If the overload set includes a literal operator with the parameter type `long double`, the user-defined literal expression is treated as a function call `operator "" X(fL)`, where `f` is the literal without ud-suffix b) otherwise, the overload set must include either, but not both, a raw literal operator or a numeric literal operator template. If the overload set includes a raw literal operator, the user-defined literal expression is treated as a function call `operator "" X("f")` c) otherwise, if the overload set includes a numeric literal operator template, the user-defined literal expression is treated as a function call `operator "" X<'c1', 'c2', 'c3'..., 'ck'>()`, where c1..ck are the individual characters of `f` and all of them are from the [basic source character set](charset#Basic_source_character_set "cpp/language/charset") (until C++23)[basic character set](charset#Basic_character_set "cpp/language/charset") (since C++23). 3) For user-defined string literals, let `str` be the literal without ud-suffix: | | | | --- | --- | | a) If the overload set includes a string literal operator template with a non-type template parameter for which `str` is a well-formed template argument, then the user-defined literal expression is treated as a function call `operator "" X<str>()`, | (since C++20) | b) otherwise, the user-defined literal expression is treated as a function call `operator "" X (str, len)`, where `len` is the length of the string literal, excluding the terminating null character 4) For user-defined character literals, the user-defined literal expression is treated as a function call `operator "" X(ch)`, where `ch` is the literal without ud-suffix ``` long double operator "" _w(long double); std::string operator "" _w(const char16_t*, size_t); unsigned operator "" _w(const char*); int main() { 1.2_w; // calls operator "" _w(1.2L) u"one"_w; // calls operator "" _w(u"one", 3) 12_w; // calls operator "" _w("12") "two"_w; // error: no applicable literal operator } ``` When string literal concatenation takes place in [translation phase 6](translation_phases#Phase_6 "cpp/language/translation phases"), user-defined string literals are concatenated as well, and their ud-suffixes are ignored for the purpose of concatenation, except that only one suffix may appear on all concatenated literals: ``` int main() { L"A" "B" "C"_x; // OK: same as L"ABC"_x "P"_x "Q" "R"_y; // error: two different ud-suffixes (_x and _y) } ``` ### Literal operators The function called by a user-defined literal is known as *literal operator* (or, if it's a template, *literal operator template*). It is declared just like any other [function](function "cpp/language/function") or [function template](function_template "cpp/language/function template") at namespace scope (it may also be a friend function, an explicit instantiation or specialization of a function template, or introduced by a using-declaration), except for the following restrictions: The name of this function can have one of the two forms: | | | | | --- | --- | --- | | `operator` `""` identifier | | | | `operator` user-defined-string-literal | | | | | | | | --- | --- | --- | | identifier | - | the identifier to use as the ud-suffix for the user-defined literals that will call this function. Must begin with the underscore `_`: the suffixes that do not begin with the underscore are reserved for the literal operators provided by the standard library. | | user-defined-string-literal | - | the character sequence `""` followed, without a space, by the character sequence that becomes the ud-suffix. This special syntax makes it possible to use language keywords and [reserved identifiers](../keywords "cpp/keywords") as ud-suffixes, and is used by the declaration of `operator ""if` from the header `<complex>`. Note that using this form does not change the rules that user-defined literal operators must begin with an underscore: declarations such as `operator ""if` may only appear as part of a standard library header. However, it allows the use of an underscore followed by a capital letter (which is otherwise a [reserved identifier](identifiers "cpp/language/identifiers")) | If the literal operator is a template, it must have an empty parameter list and can have only one template parameter, which must be a non-type template parameter pack with element type `char` (in which case it is known as a *numeric literal operator template*). ``` template<char...> double operator "" _x(); ``` | | | | --- | --- | | or a non-type template parameter of class type (in which case it is known as a *string literal operator template*). ``` struct A { constexpr A(const char *); }; template<A a> A operator ""_a(); ``` | (since C++20) | Only the following parameter lists are allowed on literal operators: | | | | | --- | --- | --- | | `(` `const char *` `)` | (1) | | | `(` `unsigned long long int` `)` | (2) | | | `(` `long double` `)` | (3) | | | `(` `char` `)` | (4) | | | `(` `wchar_t` `)` | (5) | | | `(` `char8_t` `)` | (6) | (since C++20) | | `(` `char16_t` `)` | (7) | | | `(` `char32_t` `)` | (8) | | | `(` `const char *` `,` `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)` `)` | (9) | | | `(` `const wchar_t *` `,` `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)` `)` | (10) | | | `(` `const char8_t *` `,` `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)` `)` | (11) | (since C++20) | | `(` `const char16_t *` `,` `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)` `)` | (12) | | | `(` `const char32_t *` `,` `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)` `)` | (13) | | 1) Literal operators with this parameter list are the *raw literal operators*, used as fallbacks for integer and floating-point user-defined literals (see above) 2) Literal operators with these parameter lists are the first-choice literal operator for user-defined integer literals 3) Literal operators with these parameter lists are the first-choice literal operator for user-defined floating-point literals 4-8) Literal operators with these parameter lists are called by user-defined character literals 9-13) Literal operators with these parameter lists are called by user-defined string literals [Default arguments](default_arguments "cpp/language/default arguments") are not allowed. C [language linkage](language_linkage "cpp/language/language linkage") is not allowed. Other than the restrictions above, literal operators and literal operator templates are normal functions (and function templates), they can be declared inline or constexpr, they may have internal or external linkage, they can be called explicitly, their addresses can be taken, etc. ``` #include <string> void operator "" _km(long double); // OK, will be called for 1.0_km std::string operator "" _i18n(const char*, std::size_t); // OK template<char...> double operator "" _π(); // OK float operator ""_e(const char*); // OK // error: suffix must begin with underscore float operator ""Z(const char*); // error: all names that begin with underscore followed by uppercase // letter are reserved (NOTE: a space between "" and _). double operator"" _Z(long double); // OK. NOTE: no space between "" and _. double operator""_Z(long double); // OK: literal operators can be overloaded double operator ""_Z(const char* args); int main() {} ``` ### Notes Since the introduction of user-defined literals, the code that uses [format macro constants for fixed-width integer types](https://en.cppreference.com/w/c/types/integer "c/types/integer") with no space after the preceding string literal became invalid: `[std::printf](http://en.cppreference.com/w/cpp/io/c/fprintf)("%"[PRId64](http://en.cppreference.com/w/cpp/types/integer)"\n",[INT64\_MIN](http://en.cppreference.com/w/cpp/types/integer));` has to be replaced by `[std::printf](http://en.cppreference.com/w/cpp/io/c/fprintf)("%" [PRId64](http://en.cppreference.com/w/cpp/types/integer)"\n",[INT64\_MIN](http://en.cppreference.com/w/cpp/types/integer));` Due to [maximal munch](translation_phases#maximal_munch "cpp/language/translation phases"), user-defined integer and floating point literals ending in `p`, `P`, (since C++17) `e` and `E`, when followed by the operators `+` or `-`, must be separated from the operator with whitespace or parentheses in the source: ``` long double operator""_E(long double); long double operator""_a(long double); int operator""_p(unsigned long long); auto x = 1.0_E+2.0; // error auto y = 1.0_a+2.0; // OK auto z = 1.0_E +2.0; // OK auto q = (1.0_E)+2.0; // OK auto w = 1_p+2; // error auto u = 1_p +2; // OK ``` Same applies to dot operator following an integer or floating-point user-defined literal: ``` #include <chrono> using namespace std::literals; auto a = 4s.count(); // Error auto b = 4s .count(); // OK auto c = (4s).count(); // OK ``` Otherwise, a single invalid preprocessing number token (e.g., `1.0_E+2.0` or `4s.count`) is formed, which causes compilation to fail. ### Examples ``` #include <cstddef> #include <algorithm> #include <iostream> #include <numbers> #include <string> // used as conversion from degrees (input param) to radians (returned output) constexpr long double operator"" _deg_to_rad(long double deg) { long double radians = deg * std::numbers::pi_v<long double> / 180; return radians; } // used with custom type struct mytype { unsigned long long m; }; constexpr mytype operator"" _mytype(unsigned long long n) { return mytype{n}; } // used for side-effects void operator"" _print(const char* str) { std::cout << str << '\n'; } #if __cpp_nontype_template_args < 201911 std::string operator"" _x2 (const char* str, std::size_t) { return std::string{str} + str; } #else // C++20 string literal operator template template<std::size_t N> struct DoubleString { char p[N*2-1]{}; constexpr DoubleString(char const(&pp)[N]) { std::ranges::copy(pp, p); std::ranges::copy(pp, p + N - 1); }; }; template<DoubleString A> constexpr auto operator"" _x2() { return A.p; } #endif // C++20 int main() { double x_rad = 90.0_deg_to_rad; std::cout << std::fixed << x_rad << '\n'; mytype y = 123_mytype; std::cout << y.m << '\n'; 0x123ABC_print; std::cout << "abc"_x2 << '\n'; } ``` Output: ``` 1.570796 123 0x123ABC abcabc ``` ### Standard library The following literal operators are defined in the standard library: | Defined in inline namespace `std::literals::complex_literals` | | --- | | [operator""ifoperator""ioperator""il](../numeric/complex/operator%22%22i "cpp/numeric/complex/operator\"\"i") (C++14) | A `[std::complex](../numeric/complex "cpp/numeric/complex")` literal representing pure imaginary number (function) | | Defined in inline namespace `std::literals::chrono_literals` | | [operator""h](../chrono/operator%22%22h "cpp/chrono/operator\"\"h") (C++14) | A `[std::chrono::duration](../chrono/duration "cpp/chrono/duration")` literal representing hours (function) | | [operator""min](../chrono/operator%22%22min "cpp/chrono/operator\"\"min") (C++14) | A `[std::chrono::duration](../chrono/duration "cpp/chrono/duration")` literal representing minutes (function) | | [operator""s](../chrono/operator%22%22s "cpp/chrono/operator\"\"s") (C++14) | A `[std::chrono::duration](../chrono/duration "cpp/chrono/duration")` literal representing seconds (function) | | [operator""ms](../chrono/operator%22%22ms "cpp/chrono/operator\"\"ms") (C++14) | A `[std::chrono::duration](../chrono/duration "cpp/chrono/duration")` literal representing milliseconds (function) | | [operator""us](../chrono/operator%22%22us "cpp/chrono/operator\"\"us") (C++14) | A `[std::chrono::duration](../chrono/duration "cpp/chrono/duration")` literal representing microseconds (function) | | [operator""ns](../chrono/operator%22%22ns "cpp/chrono/operator\"\"ns") (C++14) | A `[std::chrono::duration](../chrono/duration "cpp/chrono/duration")` literal representing nanoseconds (function) | | [operator""y](../chrono/operator%22%22y "cpp/chrono/operator\"\"y") (C++20) | A `std::chrono::year` literal representing a particular year (function) | | [operator""d](../chrono/operator%22%22d "cpp/chrono/operator\"\"d") (C++20) | A `std::chrono::day` literal representing a day of a month (function) | | Defined in inline namespace `std::literals::string_literals` | | [operator""s](../string/basic_string/operator%22%22s "cpp/string/basic string/operator\"\"s") (C++14) | Converts a character array literal to `basic_string` (function) | | Defined in inline namespace `std::literals::string_view_literals` | | [operator""sv](../string/basic_string_view/operator%22%22sv "cpp/string/basic string view/operator\"\"sv") (C++17) | Creates a string view of a character array literal (function) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1473](https://cplusplus.github.io/CWG/issues/1473.html) | C++11 | whitespace between `""` and ud-suffix wasrequired in the declaration of literal operators | made optional | | [CWG 1479](https://cplusplus.github.io/CWG/issues/1479.html) | C++11 | literal operators could have default arguments | prohibited |
programming_docs
cpp return statement `return` statement =================== Terminates the current function and returns the specified value (if any) to the caller. ### Syntax | | | | | --- | --- | --- | | attr(optional) `return` expression(optional) `;` | (1) | | | attr(optional) `return` braced-init-list `;` | (2) | (since C++11) | | attr(optional) `co_return` expression(optional) `;` | (3) | (since C++20) | | attr(optional) `co_return` braced-init-list `;` | (4) | (since C++20) | | | | | | --- | --- | --- | | attr | - | (since C++11) sequence of any number of [attributes](attributes "cpp/language/attributes") | | expression | - | [expression](expressions "cpp/language/expressions"), convertible to the function return type | | braced-init-list | - | brace-enclosed list of initializers and other braced-init-lists | ### Explanation 1) Evaluates the expression, terminates the current function and returns the result of the expression to the caller, after [implicit conversion](implicit_cast "cpp/language/implicit cast") to the function return type. The expression is optional in functions whose return type is (possibly cv-qualified) `void`, and disallowed in constructors and in destructors. 2) Uses [copy-list-initialization](list_initialization "cpp/language/list initialization") to construct the return value of the function. 3,4) In a coroutine, the keyword `co_return` must be used instead of `return` for the final suspension point (see [coroutines](coroutines "cpp/language/coroutines") for details). ### Notes If control reaches the end of. * a function with the return type (possibly cv-qualified) `void`, * a constructor, * a destructor, or * a [function-try-block](function-try-block "cpp/language/function-try-block") for a function with the return type (possibly cv-qualified) `void` without encountering a return statement, `return;` is executed. If control reaches the end of the [main function](main_function "cpp/language/main function"), `return 0;` is executed. Flowing off the end of a value-returning function (except `main`) without a return statement is undefined behavior. In a function returning (possibly cv-qualified) `void`, the return statement with expression can be used, if the expression type is (possibly cv-qualified) `void`. | | | | --- | --- | | If the return type of a function is specified as a [placeholder type](auto "cpp/language/auto"), it will be [deduced](function#Return_type_deduction "cpp/language/function") from the return value. The copy-initialization of the result of the function call is [sequenced-before](eval_order "cpp/language/eval order") the destruction of all temporaries at the end of expression, which, in turn, is *sequenced-before* the destruction of local variables of the block enclosing the return statement. | (since C++14) | Returning by value may involve construction and copy/move of a temporary object, unless [copy elision](copy_elision "cpp/language/copy elision") is used. Specifically, the conditions for copy/move are as follows: | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | Automatic move from local variables and parameters The expression is *move-eligible* If it is a (possibly parenthesized) [id-expression](identifiers "cpp/language/identifiers") that names a variable whose type is.* a non-volatile object type | | | | --- | --- | | * or a non-volatile rvalue reference to object type | (since C++20) | and that variable is declared. * in the body or * as a parameter of the innermost enclosing function or lambda expression. | | | | | | --- | --- | --- | --- | | If the expression is move-eligible, [overload resolution](overload_resolution "cpp/language/overload resolution") to select the constructor to use for initialization of the returned value or, for `co_return`, to select the overload of `promise.return_value()` (since C++20) is performed *twice*:* first as if expression were an rvalue expression (thus it may select the [move constructor](move_constructor "cpp/language/move constructor")), and + if the first overload resolution failed or | | | | --- | --- | | * it succeeded, but did not select the [move constructor](move_constructor "cpp/language/move constructor") (formally, the first parameter of the selected constructor was not an rvalue reference to the (possibly cv-qualified) type of expression) | (until C++20) | * then overload resolution is performed as usual, with expression considered as an lvalue (so it may select the [copy constructor](copy_constructor "cpp/language/copy constructor")). | (until C++23) | | If the expression is move-eligible, it is treated as an xvalue (thus overload resolution may select the [move constructor](move_constructor "cpp/language/move constructor")). | (since C++23) | | (since C++11) | | | | | --- | --- | | Guaranteed copy elision If expression is a prvalue, the result object is initialized directly by that expression. This does not involve a copy or move constructor when the types match (see [copy elision](copy_elision "cpp/language/copy elision")). | (since C++17) | ### Keywords [`return`](../keyword/return "cpp/keyword/return"), [`co_return`](../keyword/co_return "cpp/keyword/co return"). ### Example ``` #include <iostream> #include <string> #include <utility> void fa(int i) { if (i == 2) return; std::cout << i << '\n'; } // implied return; int fb(int i) { if (i > 4) return 4; std::cout << i << '\n'; return 2; } std::pair<std::string, int> fc(const char* p, int x) { return {p, x}; } void fd() { return fa(10); // fa(10) is a void expression } int main() { fa(2); // returns, does nothing when i==2 fa(1); // prints its argument, then returns int i = fb(5); // returns 4 i = fb(i); // prints its argument, returns 2 std::cout << i << '\n' << fc("Hello", 7).second << '\n'; fd(); } ``` Output: ``` 1 4 2 7 10 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1541](https://cplusplus.github.io/CWG/issues/1541.html) | C++98 | expression could not be omitted if the return type is cv-qualified `void` | it can be omitted | | [CWG 1579](https://cplusplus.github.io/CWG/issues/1579.html) | C++11 | return by converting move constructor was not allowed | converting moveconstructor lookup enabled | | [CWG 1885](https://cplusplus.github.io/CWG/issues/1885.html) | C++14 | sequencing of the destruction of automatic variables was not explicit | sequencing rules added | ### See also * [copy elision](copy_elision "cpp/language/copy elision") | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/return "c/language/return") for `return` statement | cpp Nested classes Nested classes ============== A declaration of a [class/struct](class "cpp/language/class") or [union](union "cpp/language/union") may appear within another class. Such declaration declares a *nested class*. ### Explanation The name of the nested class exists in the scope of the enclosing class, and name lookup from a member function of a nested class visits the scope of the enclosing class after examining the scope of the nested class. Like any member of its enclosing class, the nested class has access to all names (private, protected, etc) to which the enclosing class has access, but it is otherwise independent and has no special access to the [`this` pointer](this "cpp/language/this") of the enclosing class. | | | | --- | --- | | Declarations in a nested class can use only type names, static members, and enumerators from the enclosing class. | (until C++11) | | Declarations in a nested class can use any members of the enclosing class, following the [usual usage rules](data_members#Usage "cpp/language/data members") for the non-static members. | (since C++11) | ``` int x,y; // globals class enclose // enclosing class { // note: private members int x; static int s; public: struct inner // nested class { void f(int i) { x = i; // Error: can't write to non-static enclose::x without instance int a = sizeof x; // Error until C++11, // OK in C++11: operand of sizeof is unevaluated, // this use of the non-static enclose::x is allowed. s = i; // OK: can assign to the static enclose::s ::x = i; // OK: can assign to global x y = i; // OK: can assign to global y } void g(enclose* p, int i) { p->x = i; // OK: assign to enclose::x } }; }; ``` [Friend](friend "cpp/language/friend") functions defined within a nested class have no special access to the members of the enclosing class even if lookup from the body of a member function that is defined within a nested class can find the private members of the enclosing class. Out-of-class definitions of the members of a nested class appear in the namespace of the enclosing class: ``` struct enclose { struct inner { static int x; void f(int i); }; }; int enclose::inner::x = 1; // definition void enclose::inner::f(int i) {} // definition ``` Nested classes can be forward-declared and later defined, either within the same enclosing class body, or outside of it: ``` class enclose { class nested1; // forward declaration class nested2; // forward declaration class nested1 {}; // definition of nested class }; class enclose::nested2 { }; // definition of nested class ``` Nested class declarations obey [member access](access "cpp/language/access") specifiers, a private member class cannot be named outside the scope of the enclosing class, although objects of that class may be manipulated: ``` class enclose { struct nested // private member { void g() {} }; public: static nested f() { return nested{}; } }; int main() { //enclose::nested n1 = enclose::f(); // error: 'nested' is private enclose::f().g(); // OK: does not name 'nested' auto n2 = enclose::f(); // OK: does not name 'nested' n2.g(); } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 45](https://cplusplus.github.io/CWG/issues/45.html) | C++98 | the members of a nested class cannotaccess the enclosing class and its friends | they have the same access rights asother members of the enclosing class(also resolves CWG issues #8 and #10) | ### References * C++20 standard (ISO/IEC 14882:2020): + 11.4.10 Nested class declarations [class.nest] * C++17 standard (ISO/IEC 14882:2017): + 12.2.5 Nested class declarations [class.nest] * C++14 standard (ISO/IEC 14882:2014): + 9.7 Nested class declarations [class.nest] * C++11 standard (ISO/IEC 14882:2011): + 9.7 Nested class declarations [class.nest] * C++98 standard (ISO/IEC 14882:1998): + 9.7 Nested class declarations [class.nest] cpp Extending the namespace std Extending the namespace `std` ============================= ### Adding declarations to `std` It is undefined behavior to add declarations or definitions to `namespace std` or to any namespace nested within `std`, with a few exceptions noted below. ``` #include <utility> namespace std { // a function definition added to namespace std: undefined behavior pair<int, int> operator+(pair<int, int> a, pair<int, int> b) { return {a.first + b.first, a.second + b.second}; } } ``` ### Adding template specializations #### Class templates It is allowed to add template specializations for any standard library class template to the namespace `std` only if the declaration depends on at least one program-defined type and the specialization satisfies all requirements for the original template, except where such specializations are prohibited. ``` // Get the declaration of the primary std::hash template. // We are not permitted to declare it ourselves. // <typeindex> is guaranteed to provide such a declaration, // and is much cheaper to include than <functional>. #include <typeindex> // Specialize std::hash so that MyType can be used as a key in // std::unordered_set and std::unordered_map. Opening namespace // std can accidentally introduce undefined behavior, and is not // necessary for specializing class templates. template<> struct std::hash<MyType> { std::size_t operator()(const MyType& t) const { return t.hash(); } }; ``` * Specializing the template `[std::complex](../numeric/complex "cpp/numeric/complex")` for any type other than float, double, and long double is unspecified. * Specializations of `[std::numeric\_limits](../types/numeric_limits "cpp/types/numeric limits")` must define all members declared `static const` (until C++11)`static constexpr` (since C++11) in the primary template, in such a way that they are usable as [integral constant expressions](constant_expression "cpp/language/constant expression"). | | | | --- | --- | | * None of the templates defined in [`<type_traits>`](../header/type_traits "cpp/header/type traits") may be specialized for a program-defined type, except for `[std::common\_type](../types/common_type "cpp/types/common type")` and [`std::basic_common_reference`](../types/common_reference#Helper_types "cpp/types/common reference") (since C++20). This includes the [type traits](../types "cpp/types") and the class template `[std::integral\_constant](../types/integral_constant "cpp/types/integral constant")`. * Specializations of `[std::hash](../utility/hash "cpp/utility/hash")` for program-defined types must satisfy [Hash](../named_req/hash "cpp/named req/Hash") requirements. * Specializations of `[std::atomic](../atomic/atomic "cpp/atomic/atomic")` must have a deleted copy constructor, a deleted copy assignment operator, and a constexpr value constructor. * Specializations of `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` and `[std::weak\_ptr](../memory/weak_ptr "cpp/memory/weak ptr")` must be [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"). In addition, specializations of `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` must be [LessThanComparable](../named_req/lessthancomparable "cpp/named req/LessThanComparable"), and convertible to `bool`. * Specializations of `[std::istreambuf\_iterator](../iterator/istreambuf_iterator "cpp/iterator/istreambuf iterator")` must have a trivial copy constructor, a constexpr default constructor, and a trivial destructor. | (since C++11) | | | | | --- | --- | | * `[std::unary\_function](../utility/functional/unary_function "cpp/utility/functional/unary function")` and `[std::binary\_function](../utility/functional/binary_function "cpp/utility/functional/binary function")` may not be specialized. | (until C++17) | It is undefined behavior to declare a full or partial specialization of any member class template of a standard library class or class template. #### Function templates and member functions of templates | | | | --- | --- | | It is allowed to add template specializations for any standard library function template to the namespace `std` only if the declaration depends on at least one program-defined type and the specialization satisfies all requirements for the original template, except where such specializations are prohibited. | (until C++20) | | It is undefined behavior to declare a full specialization of any standard library function template. | (since C++20) | It is undefined behavior to declare a full specialization of any member function of a standard library class template: It is undefined behavior to declare a full specialization of any member function template of a standard library class or class template: #### Variable templates | | | | --- | --- | | It is undefined behavior to declare a full or partial specialization of any standard library variable template, except where explicitly allowed. | (since C++14) | | | | | --- | --- | | * Specializations of `[std::disable\_sized\_sentinel\_for](../iterator/sized_sentinel_for "cpp/iterator/sized sentinel for")`, `[std::ranges::disable\_sized\_range](../ranges/sized_range "cpp/ranges/sized range")`, `[std::ranges::enable\_view](../ranges/view "cpp/ranges/view")` and `[std::ranges::enable\_borrowed\_range](../ranges/borrowed_range "cpp/ranges/borrowed range")` shall be usable in constant expressions and have type `const bool`. And + `std::disable_sized_sentinel_for` may be specialized for cv-unqualified non-array object types `S` and `I` at least one of which is a program-defined type. + `std::ranges::disable_sized_range`, `std::ranges::enable_view` and `std::ranges::enable_borrowed_range` may be specialized for cv-unqualified program-defined types. * Every [mathematical constant variable template](../numeric/constants "cpp/numeric/constants") may be partially or explicitly specialized, provided that the specialization depends on a program-defined type. | (since C++20) | ### Explicit instantiation of templates It is allowed to explicitly instantiate a class (since C++20)template defined in the standard library only if the declaration depends on the name of at least one program-defined type and the instantiation meets the standard library requirements for the original template. ### Program-defined types *Program-defined specializations* are explicit template specializations or partial specializations that are not part of the C++ standard library and not defined by the implementation. *Program-defined types* are non-closure [class types](class "cpp/language/class") or [enumeration types](enum "cpp/language/enum") that are not part of the C++ standard library and not defined by the implementation, or [closure type](lambda "cpp/language/lambda") of non-implementation-provided lambda expressions (since C++11), or instantiation of program-defined specializations. ### Other restrictions The namespace `std` may not be declared as an [inline namespace](namespace#Inline_namespaces "cpp/language/namespace"). | | | | --- | --- | | Addressing restriction The behavior of a C++ program is unspecified (possibly ill-formed) if it explicitly or implicitly attempts to form a pointer, reference (for free functions and static member functions) or pointer-to-member (for non-static member functions) to a standard library function or an instantiation of a standard library function template, unless it is designated an *addressable function* (see below). Following code was well-defined in C++17, but leads to unspecified behaviors and possibly fails to compile since C++20: ``` #include <cmath> #include <memory> int main() { auto fptr0 = &std::betaf; // by unary operator& auto fptr1 = std::addressof(std::betal) // by std::addressof auto fptr2 = std::riemann_zetaf; // by function-to-pointer implicit conversion auto &fref = std::riemann_zetal; // forming a reference } ``` Designated addressable functions* [I/O manipulators](../io/manip "cpp/io/manip"): + `fmtflags` manipulators: - `[std::boolalpha](../io/manip/boolalpha "cpp/io/manip/boolalpha")` - `[std::noboolalpha](../io/manip/boolalpha "cpp/io/manip/boolalpha")` - `[std::showbase](../io/manip/showbase "cpp/io/manip/showbase")` - `[std::noshowbase](../io/manip/showbase "cpp/io/manip/showbase")` - `[std::showpoint](../io/manip/showpoint "cpp/io/manip/showpoint")` - `[std::noshowpoint](../io/manip/showpoint "cpp/io/manip/showpoint")` - `[std::showpos](../io/manip/showpos "cpp/io/manip/showpos")` - `[std::noshowpos](../io/manip/showpos "cpp/io/manip/showpos")` - `[std::skipws](../io/manip/skipws "cpp/io/manip/skipws")` - `[std::noskipws](../io/manip/skipws "cpp/io/manip/skipws")` - `[std::uppercase](../io/manip/uppercase "cpp/io/manip/uppercase")` - `[std::nouppercase](../io/manip/uppercase "cpp/io/manip/uppercase")` - `[std::unitbuf](../io/manip/unitbuf "cpp/io/manip/unitbuf")` - `[std::nounitbuf](../io/manip/unitbuf "cpp/io/manip/unitbuf")` + `adjustfield` manipulators: - `[std::internal](../io/manip/left "cpp/io/manip/left")` - `[std::left](../io/manip/left "cpp/io/manip/left")` - `[std::right](../io/manip/left "cpp/io/manip/left")` + `basefield` manipulators: - `[std::dec](../io/manip/hex "cpp/io/manip/hex")` - `[std::hex](../io/manip/hex "cpp/io/manip/hex")` - `[std::oct](../io/manip/hex "cpp/io/manip/hex")` + `floatfield` manipulators: - `[std::fixed](../io/manip/fixed "cpp/io/manip/fixed")` - `[std::scientific](../io/manip/fixed "cpp/io/manip/fixed")` - `[std::hexfloat](../io/manip/fixed "cpp/io/manip/fixed")` - `[std::defaultfloat](../io/manip/fixed "cpp/io/manip/fixed")` + `basic_istream` manipulators: - `[std::ws](../io/manip/ws "cpp/io/manip/ws")` + `basic_ostream` manipulators: - `[std::endl](../io/manip/endl "cpp/io/manip/endl")` - `[std::ends](../io/manip/ends "cpp/io/manip/ends")` - `[std::flush](../io/manip/flush "cpp/io/manip/flush")` - [`std::emit_on_flush`](../io/manip/emit_on_flush "cpp/io/manip/emit on flush") - [`std::noemit_on_flush`](../io/manip/emit_on_flush "cpp/io/manip/emit on flush") - [`std::flush_emit`](../io/manip/flush_emit "cpp/io/manip/flush emit") | (since C++20) |
programming_docs
cpp Explicit type conversion Explicit type conversion ======================== Converts between types using a combination of explicit and implicit conversions. ### Syntax | | | | | --- | --- | --- | | `(` new-type `)` expression | (1) | | | new-type `(` expression-list(optional) `)` | (2) | | | new-type `{` expression-list(optional) `}` | (3) | (since C++11) | | template-name `(` expression-list(optional) `)` | (4) | (since C++17) | | template-name `{` expression-list(optional) `}` | (5) | (since C++17) | | `auto` `(` expression `)` | (6) | (since C++23) | | `auto` `{` expression `}` | (7) | (since C++23) | Returns a value of type new-type. ### Explanation 1) When the *C-style cast expression* is encountered, the compiler attempts to interpret it as the following cast expressions, in this order: a) `[const\_cast](const_cast "cpp/language/const cast")<new-type>(expression)`; b) `[static\_cast](static_cast "cpp/language/static cast")<new-type>(expression)`, with extensions: pointer or reference to a [derived class](derived_class "cpp/language/derived class") is additionally allowed to be cast to pointer or reference to unambiguous base class (and vice versa) even if the base class is [inaccessible](access "cpp/language/access") (that is, this cast ignores the private inheritance specifier). Same applies to casting [pointer to member](pointer "cpp/language/pointer") to pointer to member of unambiguous non-virtual base; c) `static_cast` (with extensions) followed by `const_cast`; d) `[reinterpret\_cast](reinterpret_cast "cpp/language/reinterpret cast")<new-type>(expression)`; e) `reinterpret_cast` followed by `const_cast`. The first choice that satisfies the requirements of the respective cast operator is selected, even if it cannot be compiled (see example). If the cast can be interpreted in more than one way as `static_cast` followed by a `const_cast`, it cannot be compiled. In addition, C-style cast notation is allowed to cast from, to, and between pointers to incomplete class type. If both expression and new-type are pointers to incomplete class types, it's unspecified whether `static_cast` or `reinterpret_cast` gets selected. 2) The *functional-style cast expression* consists of a simple type specifier or a typedef specifier (in other words, a single-word type name, that is, cases such as `unsigned int(expression)` and `int*(expression)` are not valid), followed by a comma-separated list of expressions in parentheses. * If there is exactly one expression in parentheses, this cast expression is exactly equivalent to the corresponding C-style cast expression. * If there are more than one expression or [braced-init-list](list_initialization "cpp/language/list initialization") (since C++11) in parentheses, new-type must be a class with a suitably declared [constructor](constructor "cpp/language/constructor"). This expression is a prvalue of type new-type designating a temporary (until C++17)whose result object is (since C++17) [direct-initialized](direct_initialization "cpp/language/direct initialization") with expression-list. * If there's no expression in parentheses: if new-type names a non-array complete object type, this expression is an prvalue of type new-type, designating a temporary (until C++17)whose result object is (possibly with added cv-qualifiers) (since C++17) of that type. If new-type is an object type, the object is [value-initialized](value_initialization "cpp/language/value initialization"). If new-type is (possibly [cv-qualified](cv "cpp/language/cv")) `void`, the expression is a `void` prvalue without a result object (since C++17). 3) A single-word type name followed by a *braced-init-list* is a prvalue of the specified type designating a temporary (until C++17)whose result object is (since C++17) [direct-list-initialized](list_initialization "cpp/language/list initialization") with the specified *braced-init-list*. If new-type is (possibly [cv-qualified](cv "cpp/language/cv")) `void`, the expression is a `void` prvalue without a result object (since C++17). This is the only cast expression that can create an [array prvalue](array#Array_rvalues "cpp/language/array"). (until C++20) 4,5) Same as (2,3), except first performs [class template argument deduction](class_template_argument_deduction "cpp/language/class template argument deduction"). 6,7) The [`auto`](auto "cpp/language/auto") specifier is replaced with the deduced type of the invented variable `x` declared with `auto x(expression);` (which is never interpreted as a function declaration) or `auto x{expression};` respectively. The result is always a prvalue of an object type. As with all cast expressions, the result is: | | | | --- | --- | | * an lvalue if new-type is a reference type; * an rvalue otherwise. | (until C++11) | | * an lvalue if new-type is an lvalue reference type or an rvalue reference to function type; * an xvalue if new-type is an rvalue reference to object type; * a prvalue otherwise. | (since C++11) | ### Ambiguity Resolution In the case of an ambiguity between a expression statement with a function-style cast expression as its leftmost subexpression and a declaration statement, the ambiguity is resolved by treating it as a declaration. This disambiguation is purely syntactic: it does not consider the meaning of names occurring in the statement other than whether they are type names: ``` struct M {}; struct L { L(M&); }; M n; void f() { M(m); // declaration, equivalent to M m; L(n); // ill-formed declaration L(l)(m); // still a declaration } ``` The ambiguity above can also occur in the context of a declaration. In that context, the choice is between a function declaration with a redundant set of parentheses around a parameter name and an object declaration with a function-style cast as the initializer. The resolution is also to consider any construct that could possibly be a declaration a declaration: ``` struct S { S(int); }; void foo(double a) { S w(int(a)); // function declaration: has a parameter `a` of type int S x(int()); // function declaration: has an unnamed parameter of type int // Ways to avoid ambiguity: S y((int(a))); // object declaration: extra pair of parentheses S y((int)a); // object declaration: C-style cast S z = int(a); // object declaration: no ambiguity for this syntax } ``` An ambiguity can arise from the similarity between a function-style cast and a [type-id](type#Type_naming "cpp/language/type"). The resolution is that any construct that could possibly be a type-id in its syntactic context shall be considered a type-id: ``` // `int()` and `int(unsigned(a))` can both be parsed as type-id: // `int()` represents a function returning int // and taking no argument // `int(unsigned(a))` represents a function returning int // and taking an argument of type unsigned void foo(signed char a) { sizeof(int()); // type-id (ill-formed) sizeof(int(a)); // expression sizeof(int(unsigned(a))); // type-id (ill-formed) (int()) + 1; // type-id (ill-formed) (int(a)) + 1; // expression (int(unsigned(a))) + 1; // type-id (ill-formed) } ``` ### Example ``` #include <cassert> #include <iostream> double f = 3.14; unsigned int n1 = (unsigned int)f; // C-style cast unsigned int n2 = unsigned(f); // function-style cast class C1; class C2; C2* foo(C1* p) { return (C2*)p; // casts incomplete type to incomplete type } void cpp23_decay_copy_demo() { auto inc_print = [](int& x, const int& y) { ++x; std::cout << "x:" << x << ", y:" << y << '\n'; }; int p{1}; inc_print(p, p); // prints x:2 y:2, because param y here is an alias of p int q{1}; inc_print(q, auto{q}); // prints x:2 y:1, auto{q} (C++23) casts to prvalue, // so the param y is a copy of q (not an alias of q) } // In this example, C-style cast is interpreted as static_cast // even though it would work as reinterpret_cast struct A {}; struct I1 : A {}; struct I2 : A {}; struct D : I1, I2 {}; int main() { D* d = nullptr; // A* a = (A*)d; // compile-time error A* a = reinterpret_cast<A*>(d); // this compiles assert(a == nullptr); cpp23_decay_copy_demo(); } ``` Output: ``` x:2 y:2 x:2 y:1 ``` ### References * C++20 standard (ISO/IEC 14882:2020): + 7.6.1.4 Explicit type conversion (functional notation) [expr.type.conv] + 7.6.3 Explicit type conversion (cast notation) [expr.cast] * C++17 standard (ISO/IEC 14882:2017): + 8.2.3 Explicit type conversion (functional notation) [expr.type.conv] + 8.4 Explicit type conversion (cast notation) [expr.cast] * C++14 standard (ISO/IEC 14882:2014): + 5.2.3 Explicit type conversion (functional notation) [expr.type.conv] + 5.4 Explicit type conversion (cast notation) [expr.cast] * C++11 standard (ISO/IEC 14882:2011): + 5.2.3 Explicit type conversion (functional notation) [expr.type.conv] + 5.4 Explicit type conversion (cast notation) [expr.cast] * C++03 standard (ISO/IEC 14882:2003): + 5.2.3 Explicit type conversion (functional notation) [expr.type.conv] + 5.4 Explicit type conversion (cast notation) [expr.cast] * C++98 standard (ISO/IEC 14882:1998): + 5.2.3 Explicit type conversion (functional notation) [expr.type.conv] + 5.4 Explicit type conversion (cast notation) [expr.cast] ### See also | | | | --- | --- | | [`const_cast` conversion](const_cast "cpp/language/const cast") | adds or removes const | | [`static_cast` conversion](static_cast "cpp/language/static cast") | performs basic conversions | | [`dynamic_cast` conversion](dynamic_cast "cpp/language/dynamic cast") | performs checked polymorphic conversions | | [`reinterpret_cast` conversion](reinterpret_cast "cpp/language/reinterpret cast") | performs general low-level conversions | | [standard conversions](implicit_cast "cpp/language/implicit cast") | implicit conversions from one type to another | | [C documentation](https://en.cppreference.com/w/c/language/cast "c/language/cast") for cast operator | cpp Structured binding declaration (since C++17) Structured binding declaration (since C++17) ============================================ Binds the specified names to subobjects or elements of the initializer. Like a reference, a structured binding is an alias to an existing object. Unlike a reference, a structured binding does not have to be of a reference type. | | | | | --- | --- | --- | | attr(optional) cv-auto ref-qualifier(optional) `[` identifier-list `] =` expression `;` | (1) | | | attr(optional) cv-auto ref-qualifier(optional) `[` identifier-list `]{` expression `};` | (2) | | | attr(optional) cv-auto ref-qualifier(optional) `[` identifier-list `](` expression `);` | (3) | | | | | | | --- | --- | --- | | attr | - | sequence of any number of [attributes](attributes "cpp/language/attributes") | | cv-auto | - | possibly cv-qualified type specifier `auto`, may also include [storage-class-specifier](storage_duration "cpp/language/storage duration") `static` or `thread_local`; including `volatile` in cv-qualifiers is deprecated (since C++20) | | ref-qualifier | - | either `&` or `&&` | | identifier-list | - | list of comma-separated identifiers introduced by this declaration | | expression | - | an expression that does not have the comma operator at the top level (grammatically, an *assignment-expression*), and has either array or non-union class type. If expression refers to any of the names from identifier-list, the declaration is ill-formed. | A structured binding declaration introduces all identifiers in the identifier-list as names in the surrounding scope and binds them to subobjects or elements of the object denoted by expression. The bindings so introduced are called *structured bindings*. A structured binding declaration first introduces a uniquely-named variable (here denoted by `*e*`) to hold the value of the initializer, as follows: * If expression has array type `A` and no ref-qualifier is present, then `*e*` has type *cv* `A`, where *cv* is the cv-qualifiers in the cv-auto sequence, and each element of `*e*` is copy- (for (1)) or direct- (for (2,3)) initialized from the corresponding element of expression. * Otherwise `*e*` is defined as if by using its name instead of `[` identifier-list `]` in the declaration. We use `*E*` to denote the type of the expression `e`. (In other words, `*E*` is the equivalent of `[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<decltype((e))>`.). A structured binding declaration then performs the binding in one of three possible ways, depending on `*E*`: * Case 1: if `*E*` is an array type, then the names are bound to the array elements. * Case 2: if `*E*` is a non-union class type and `[std::tuple\_size](http://en.cppreference.com/w/cpp/utility/tuple/tuple_size)<E>` is a complete type with a member named `value` (regardless of the type or accessibility of such member), then the "tuple-like" binding protocol is used. * Case 3: if `*E*` is a non-union class type but `[std::tuple\_size](http://en.cppreference.com/w/cpp/utility/tuple/tuple_size)<E>` is not a complete type, then the names are bound to the accessible data members of `*E*`. Each of the three cases is described in more detail below. Each structured binding has a *referenced type*, defined in the description below. This type is the type returned by [`decltype`](decltype "cpp/language/decltype") when applied to an unparenthesized structured binding. #### Case 1: binding an array Each identifier in the identifier-list becomes the name of an lvalue that refers to the corresponding element of the array. The number of identifiers must equal the number of array elements. The *referenced type* for each identifier is the array element type. Note that if the array type `*E*` is cv-qualified, so is its element type. ``` int a[2] = {1, 2}; auto [x, y] = a; // creates e[2], copies a into e, // then x refers to e[0], y refers to e[1] auto& [xr, yr] = a; // xr refers to a[0], yr refers to a[1] ``` #### Case 2: binding a tuple-like type The expression `[std::tuple\_size](http://en.cppreference.com/w/cpp/utility/tuple/tuple_size)<E>::value` must be a well-formed integer constant expression, and the number of identifiers must equal `[std::tuple\_size](http://en.cppreference.com/w/cpp/utility/tuple/tuple_size)<E>::value`. For each identifier, a variable whose type is "reference to `[std::tuple\_element](http://en.cppreference.com/w/cpp/utility/tuple/tuple_element)<i, E>::type`" is introduced: lvalue reference if its corresponding initializer is an lvalue, rvalue reference otherwise. The initializer for the i-th variable is. * `e.get<i>()`, if lookup for the identifier `get` in the scope of `*E*` by class member access lookup finds at least one declaration that is a function template whose first template parameter is a non-type parameter * Otherwise, `get<i>(e)`, where `get` is looked up by [argument-dependent lookup](adl "cpp/language/adl") only, ignoring non-ADL lookup. In these initializer expressions, `e` is an lvalue if the type of the entity `*e*` is an lvalue reference (this only happens if the ref-qualifier is `&` or if it is `&&` and the initializer expression is an lvalue) and an xvalue otherwise (this effectively performs a kind of perfect forwarding), `i` is a `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)` prvalue, and `<i>` is always interpreted as a template parameter list. The variable has the same [storage duration](storage_duration "cpp/language/storage duration") as `*e*`. The identifier then becomes the name of an lvalue that refers to the object bound to said variable. The *referenced type* for the i-th identifier is `[std::tuple\_element](http://en.cppreference.com/w/cpp/utility/tuple/tuple_element)<i, E>::type`. ``` float x{}; char y{}; int z{}; std::tuple<float&, char&&, int> tpl(x, std::move(y), z); const auto& [a, b, c] = tpl; // using Tpl = const std::tuple<float&, char&&, int>; // a names a structured binding that refers to x (initialized from get<0>(tpl)) // decltype(a) is std::tuple_element<0, Tpl>::type, i.e. float& // b names a structured binding that refers to y (initialized from get<1>(tpl)) // decltype(b) is std::tuple_element<1, Tpl>::type, i.e. char&& // c names a structured binding that refers to the third component of tpl, get<2>(tpl) // decltype(c) is std::tuple_element<2, Tpl>::type, i.e. const int ``` #### Case 3: binding to data members Every non-static data member of `*E*` must be a direct member of `*E*` or the same base class of `*E*`, and must be well-formed in the context of the structured binding when named as `***e***.*name*`. `*E*` may not have an anonymous union member. The number of identifiers must equal the number of non-static data members. Each identifier in identifier-list becomes the name of an lvalue that refers to the next member of `*e*` in declaration order (bit fields are supported); the type of the lvalue is that of `e.m_i`, where `m_i` refers to the i-th member. The *referenced type* of the i-th identifier is the type of `e.m_i` if it is not a reference type, or the declared type of `m_i` otherwise. ``` #include <iostream> struct S { mutable int x1 : 2; volatile double y1; }; S f() { return S{1, 2.3}; } int main() { const auto [x, y] = f(); // x is an int lvalue identifying the 2-bit bit field // y is a const volatile double lvalue std::cout << x << ' ' << y << '\n'; // 1 2.3 x = -2; // OK // y = -2.; // Error: y is const-qualified std::cout << x << ' ' << y << '\n'; // -2 2.3 } ``` Output: ``` 1 2.3 -2 2.3 ``` ### Notes The lookup for member `get` ignores accessibility as usual and also ignores the exact type of the non-type template parameter. A private `template<char*> void get();` member will cause the member interpretation to be used, even though it is ill-formed. The portion of the declaration preceding `[` applies to the hidden variable `*e*`, not to the introduced identifiers. ``` int a = 1, b = 2; const auto& [x, y] = std::tie(a, b); // x and y are of type int& auto [z, w] = std::tie(a, b); // z and w are still of type int& assert(&z == &a); // passes ``` The tuple-like interpretation is always used if `[std::tuple\_size](http://en.cppreference.com/w/cpp/utility/tuple/tuple_size)<E>` is a complete type, even if that would cause the program to be ill-formed: ``` struct A { int x; }; namespace std { template<> struct tuple_size<::A> {}; } auto [x] = A{}; // error; the "data member" interpretation is not considered. ``` The usual rules for reference-binding to temporaries (including lifetime-extension) apply if a ref-qualifier is present and the expression is a prvalue. In those cases the hidden variable `*e*` is a reference that binds to the temporary variable [materialized](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion") from the prvalue expression, extending its lifetime. As usual, the binding will fail if `*e*` is a non-const lvalue reference: ``` int a = 1; const auto& [x] = std::make_tuple(a); // OK, not dangling auto& [y] = std::make_tuple(a); // error, cannot bind auto& to rvalue std::tuple auto&& [z] = std::make_tuple(a); // also OK ``` `decltype(x)`, where `x` denotes a structured binding, names the *referenced type* of that structured binding. In the tuple-like case, this is the type returned by `[std::tuple\_element](http://en.cppreference.com/w/cpp/utility/tuple/tuple_element)`, which may not be a reference even though a hidden reference is always introduced in this case. This effectively emulates the behavior of binding to a struct whose non-static data members have the types returned by `tuple_element`, with the referenceness of the binding itself being a mere implementation detail. ``` std::tuple<int, int&> f(); auto [x, y] = f(); // decltype(x) is int // decltype(y) is int& const auto [z, w] = f(); // decltype(z) is const int // decltype(w) is int& ``` | | | | --- | --- | | Structured bindings cannot be captured by [lambda expressions](lambda "cpp/language/lambda"). | (until C++20) | ``` #include <cassert> int main() { struct S { int p{6}, q{7}; }; const auto& [b, d] = S{}; auto l = [b, d] { return b * d; }; // valid since C++20 assert(l() == 42); } ``` ### Example ``` #include <set> #include <string> #include <iomanip> #include <iostream> int main() { std::set<std::string> myset{"hello"}; for (int i{2}; i; --i) { if (auto [iter, success] = myset.insert("Hello"); success) std::cout << "Insert is successful. The value is " << std::quoted(*iter) << ".\n"; else std::cout << "The value " << std::quoted(*iter) << " already exists in the set.\n"; } struct BitFields { // C++20: default member initializer for bit-fields int b : 4 {1}, d : 4 {2}, p : 4 {3}, q : 4 {4}; }; { const auto [b, d, p, q] = BitFields{}; std::cout << b << ' ' << d << ' ' << p << ' ' << q << '\n'; } { const auto [b, d, p, q] = []{ return BitFields{4, 3, 2, 1}; }(); std::cout << b << ' ' << d << ' ' << p << ' ' << q << '\n'; } { BitFields s; auto& [b, d, p, q] = s; std::cout << b << ' ' << d << ' ' << p << ' ' << q << '\n'; b = 4, d = 3, p = 2, q = 1; std::cout << s.b << ' ' << s.d << ' ' << s.p << ' ' << s.q << '\n'; } } ``` Output: ``` Insert is successful. The value is "Hello". The value "Hello" already exists in the set. 1 2 3 4 4 3 2 1 1 2 3 4 4 3 2 1 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 2285](https://cplusplus.github.io/CWG/issues/2285.html) | C++17 | expression could refer to the names from identifier-list | the declaration is ill-formed in this case | | [P0961R1](https://wg21.link/P0961R1) | C++17 | in the tuple-like case, member `get` is usedif lookup finds a `get` of whatever kind | only if lookup finds a function templatewith a non-type parameter | | [P0969R0](https://wg21.link/P0969R0) | C++17 | in the binding-to-members case,the members are required to be public | only required to be accessiblein the context of the declaration | | [CWG 2312](https://cplusplus.github.io/CWG/issues/2312.html) | C++17 | the meaning of `mutable` was lostin the binding-to-members case | its meaning is still kept | | [CWG 2386](https://cplusplus.github.io/CWG/issues/2386.html) | C++17 | the "tuple-like" binding protocol is usedwhenever `tuple_size<E>` is a complete type | used only when `tuple_size<E>`has a member `value` | ### References * C++20 standard (ISO/IEC 14882:2020): + 9.6 Structured binding declarations [dcl.struct.bind] (p: 219-220) * C++17 standard (ISO/IEC 14882:2017): + 11.5 Structured binding declarations [dcl.struct.bind] (p: 219-220) ### See also | | | | --- | --- | | [tie](../utility/tuple/tie "cpp/utility/tuple/tie") (C++11) | creates a `[tuple](../utility/tuple "cpp/utility/tuple")` of lvalue references or unpacks a tuple into individual objects (function template) |
programming_docs
cpp user-defined conversion function user-defined conversion function ================================ Enables [implicit conversion](implicit_cast "cpp/language/implicit cast") or [explicit conversion](explicit_cast "cpp/language/explicit cast") from a [class type](class "cpp/language/class") to another type. ### Syntax Conversion function is declared like a [non-static member function](member_functions "cpp/language/member functions") or member [function template](function_template "cpp/language/function template") with no parameters, no explicit return type, and with the name of the form: | | | | | --- | --- | --- | | `operator` conversion-type-id | (1) | | | `explicit` `operator` conversion-type-id | (2) | (since C++11) | | `explicit (` expression `)` `operator` conversion-type-id | (3) | (since C++20) | 1) Declares a user-defined conversion function that participates in all [implicit](implicit_cast "cpp/language/implicit cast") and [explicit conversions](explicit_cast "cpp/language/explicit cast"). 2) Declares a user-defined conversion function that participates in [direct-initialization](direct_initialization "cpp/language/direct initialization") and [explicit conversions](explicit_cast "cpp/language/explicit cast") only. 3) Declares a user-defined conversion function that is [conditionally explicit](explicit "cpp/language/explicit"). conversion-type-id is a [type-id](type#Type_naming "cpp/language/type") except that function and array operators `[]` or `()` are not allowed in its declarator (thus conversion to types such as pointer to array requires a type alias/typedef or an identity template: see below). Regardless of typedef, conversion-type-id cannot represent an array or a function type. Although the return type is not allowed in the declaration of a user-defined conversion function, the decl-specifier-seq of [the declaration grammar](declarations#Specifiers "cpp/language/declarations") may be present and may include any specifier other than type-specifier or the keyword `static`, In particular, besides [`explicit`](explicit "cpp/language/explicit"), the specifiers [`inline`](inline "cpp/language/inline"), [`virtual`](virtual "cpp/language/virtual"), [`constexpr`](constexpr "cpp/language/constexpr") (since C++11), [`consteval`](consteval "cpp/language/consteval") (since C++20), and [`friend`](friend "cpp/language/friend") are also allowed (note that `friend` requires a qualified name: `friend A::operator B();`). When such member function is declared in class X, it performs conversion from X to conversion-type-id: ``` struct X { // implicit conversion operator int() const { return 7; } // explicit conversion explicit operator int*() const { return nullptr; } // Error: array operator not allowed in conversion-type-id // operator int(*)[3]() const { return nullptr; } using arr_t = int[3]; operator arr_t*() const { return nullptr; } // OK if done through typedef // operator arr_t () const; // Error: conversion to array not allowed in any case }; int main() { X x; int n = static_cast<int>(x); // OK: sets n to 7 int m = x; // OK: sets m to 7 int* p = static_cast<int*>(x); // OK: sets p to null // int* q = x; // Error: no implicit conversion int (*pa)[3] = x; // OK } ``` ### Explanation User-defined conversion function is invoked in the second stage of the [implicit conversion](implicit_cast "cpp/language/implicit cast"), which consists of zero or one [converting constructor](converting_constructor "cpp/language/converting constructor") or zero or one user-defined conversion function. If both conversion functions and converting constructors can be used to perform some user-defined conversion, the conversion functions and constructors are both considered by [overload resolution](overload_resolution "cpp/language/overload resolution") in [copy-initialization](copy_initialization "cpp/language/copy initialization") and [reference-initialization](reference_initialization "cpp/language/reference initialization") contexts, but only the constructors are considered in [direct-initialization](direct_initialization "cpp/language/direct initialization") contexts. ``` struct To { To() = default; To(const struct From&) {} // converting constructor }; struct From { operator To() const {return To();} // conversion function }; int main() { From f; To t1(f); // direct-initialization: calls the constructor // Note: if converting constructor is not available, implicit copy constructor // will be selected, and conversion function will be called to prepare its argument // To t2 = f; // copy-initialization: ambiguous // Note: if conversion function is from a non-const type, e.g. // From::operator To();, it will be selected instead of the ctor in this case To t3 = static_cast<To>(f); // direct-initialization: calls the constructor const To& r = f; // reference-initialization: ambiguous } ``` Conversion function to its own (possibly cv-qualified) class (or to a reference to it), to the base of its own class (or to a reference to it), and to the type `void` can be defined, but can not be executed as part of the conversion sequence, except, in some cases, through [virtual](virtual "cpp/language/virtual") dispatch: ``` struct D; struct B { virtual operator D() = 0; }; struct D : B { operator D() override { return D(); } }; int main() { D obj; D obj2 = obj; // does not call D::operator D() B& br = obj; D obj3 = br; // calls D::operator D() through virtual dispatch } ``` It can also be called using member function call syntax: ``` struct B {}; struct X : B { operator B&() { return *this; }; }; int main() { X x; B& b1 = x; // does not call X::operatorB&() B& b2 = static_cast<B&>(x); // does not call X::operatorB& B& b3 = x.operator B&(); // calls X::operatorB& } ``` When making an explicit call to the conversion function, conversion-type-id is greedy: it is the longest sequence of tokens that could possibly form a conversion-type-id (including attributes, if any) (since C++11): ``` & x.operator int * a; // error: parsed as & (x.operator int*) a, // not as & (x.operator int) * a operator int [[noreturn]] (); // error: noreturn attribute applied to a type ``` | | | | --- | --- | | The placeholder [auto](auto "cpp/language/auto") can be used in conversion-type-id, indicating a [deduced return type](function#Return_type_deduction "cpp/language/function"): ``` struct X { operator int(); // OK operator auto() -> short; // error: trailing return type not part of syntax operator auto() const { return 10; } // OK: deduced return type }; ``` Note: a [conversion function template](member_template#Conversion_function_templates "cpp/language/member template") is not allowed to have a deduced return type. | (since C++14) | Conversion functions can be inherited and can be [virtual](virtual "cpp/language/virtual"), but cannot be [static](static "cpp/language/static"). A conversion function in the derived class does not hide a conversion function in the base class unless they are converting to the same type. Conversion function can be a template member function, for example, [`std::auto_ptr<T>::operator auto_ptr<Y>`](../memory/auto_ptr/operator_auto_ptr "cpp/memory/auto ptr/operator auto ptr"). See [member template](member_template#Conversion_function_templates "cpp/language/member template") and [template argument deduction](template_argument_deduction#conversion_function_template "cpp/language/template argument deduction") for applicable special rules. ### Defect Reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 296](https://cplusplus.github.io/CWG/issues/296.html) | C++98 | conversion functions could be static | they cannot be declared static | | [CWG 2016](https://cplusplus.github.io/CWG/issues/2016.html) | C++98 | conversion functions could not specify return types,but the types are present in conversion-type-id | return types cannot be specified in thedeclaration specifiers of conversion functions | | [CWG 2175](https://cplusplus.github.io/CWG/issues/2175.html) | C++11 | it was unclear whether the `[[noreturn]]` in`operator int [[noreturn]] ();` is parsed as a part ofnoptr-declarator (of function declarator) or conversion-type-id | it is parsed as a part ofconversion-type-id | cpp Value initialization Value initialization ==================== This is the initialization performed when an object is constructed with an empty initializer. ### Syntax | | | | | --- | --- | --- | | T `()` | (1) | | | `new` T `()` | (2) | | | Class`::`Class`(`...`)` `:` member `()` `{` ... `}` | (3) | | | T object `{};` | (4) | (since C++11) | | T `{}` | (5) | (since C++11) | | `new` T `{}` | (6) | (since C++11) | | Class`::`Class`(`...`)` `:` member `{}` `{` ... `}` | (7) | (since C++11) | ### Explanation Value initialization is performed in these situations: 1,5) when a nameless temporary object is created with the initializer consisting of an empty pair of parentheses or braces (since C++11); 2,6) when an object with dynamic storage duration is created by a [new-expression](new "cpp/language/new") with the initializer consisting of an empty pair of parentheses or braces (since C++11); 3,7) when a non-static data member or a base class is initialized using a [member initializer](initializer_list "cpp/language/initializer list") with an empty pair of parentheses or braces (since C++11); | | | | --- | --- | | 4) when a named object (automatic, static, or thread-local) is declared with the initializer consisting of a pair of braces. | (since C++11) | In all cases, if the empty pair of braces `{}` is used and `T` is an *aggregate type*, [aggregate-initialization](aggregate_initialization "cpp/language/aggregate initialization") is performed instead of value-initialization. | | | | --- | --- | | If `T` is a class type that has no default constructor but has a constructor taking `[std::initializer\_list](http://en.cppreference.com/w/cpp/utility/initializer_list)`, [list-initialization](list_initialization "cpp/language/list initialization") is performed. | (since C++11) | The effects of value initialization are: 1) if `T` is a class type with no [default constructor](default_constructor "cpp/language/default constructor") or with a user-declared (until C++11)[user-provided](function#User-provided_functions "cpp/language/function") or deleted (since C++11) default constructor, the object is [default-initialized](default_initialization "cpp/language/default initialization"); 2) if `T` is a class type with a default constructor that is not user-declared (until C++11)neither user-provided nor deleted (since C++11) (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is [zero-initialized](zero_initialization "cpp/language/zero initialization") and the semantic constraints for default-initialization are checked, and if `T` has a non-trivial default constructor, the object is [default-initialized](default_initialization "cpp/language/default initialization"); 3) if `T` is an array type, each element of the array is value-initialized; 4) otherwise, the object is [zero-initialized](zero_initialization "cpp/language/zero initialization"). ### Notes The syntax `T object();` does not initialize an object; it declares a function that takes no arguments and returns `T`. The way to value-initialize a named variable before C++11 was `T object = T();`, which value-initializes a temporary and then copy-initializes the object: most compilers [optimize out the copy](copy_elision "cpp/language/copy elision") in this case. References cannot be value-initialized. As described in [functional cast](explicit_cast "cpp/language/explicit cast"), the syntax `T()` (1) is prohibited for arrays, while `T{}` (5) is allowed. All standard containers (`[std::vector](../container/vector "cpp/container/vector")`, `[std::list](../container/list "cpp/container/list")`, etc.) value-initialize their elements when constructed with a single `size_type` argument or when grown by a call to `resize()`, unless their allocator customizes the behavior of `construct`. The standard specifies that zero-initialization is not performed when the class has a user-provided or deleted default constructor, which implies that whether said default constructor is selected by overload resolution is not considered. All known compilers performs additional zero-initialization if a non-deleted defaulted default constructor is selected. ``` struct A { A() = default; template<class = void> A(int = 0) {} // A has a user-provided default constructor, which is not selected int x; }; constexpr int test(A a) { return a.x; // the behavior is undefined if a's value is indeterminate } constexpr int zero = test(A()); // ill-formed: the parameter is not zero-initialized according to the standard, // which results in undefined behavior that makes the program ill-formed in contexts // where constant evaluation is required. // However, such code is accepted by all known compilers. void f() { A a = A(); // not zero-initialized according to the standard // but implementations generate code for zero-initialization nonetheless } ``` ### Example ``` #include <string> #include <vector> #include <iostream> struct T1 { int mem1; std::string mem2; }; // implicit default constructor struct T2 { int mem1; std::string mem2; T2(const T2&) {} // user-provided copy constructor }; // no default constructor struct T3 { int mem1; std::string mem2; T3() {} // user-provided default constructor }; std::string s{}; // class => default-initialization, the value is "" int main() { int n{}; // scalar => zero-initialization, the value is 0 double f = double(); // scalar => zero-initialization, the value is 0.0 int* a = new int[10](); // array => value-initialization of each element // the value of each element is 0 T1 t1{}; // class with implicit default constructor => // t1.mem1 is zero-initialized, the value is 0 // t1.mem2 is default-initialized, the value is "" // T2 t2{}; // error: class with no default constructor T3 t3{}; // class with user-provided default constructor => // t3.mem1 is default-initialized to indeterminate value // t3.mem2 is default-initialized, the value is "" std::vector<int> v(3); // value-initialization of each element // the value of each element is 0 std::cout << s.size() << ' ' << n << ' ' << f << ' ' << a[9] << ' ' << v[2] << '\n'; std::cout << t1.mem1 << ' ' << t3.mem1 << '\n'; delete[] a; } ``` Possible output: ``` 0 0 0 0 0 0 4199376 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 178](https://cplusplus.github.io/CWG/issues/178.html) | C++98 | there was no value-initialization; empty initializer invoked default-initialization (though `new T()` also performs zero-initialization) | empty initializer invokevalue-initialization | | [CWG 543](https://cplusplus.github.io/CWG/issues/543.html) | C++98 | value-initialization for a class object without anyuser-provided constructors was equivalent to value-initializing each subobject (which need not zero-initialize a member with user-provided default constructor) | zero-initializesthe entire object,then calls thedefault constructor | | [CWG 1301](https://cplusplus.github.io/CWG/issues/1301.html) | C++11 | value-initialization of unions with deleteddefault constructors led to zero-initialization | they aredefault-initialized | | [CWG 1368](https://cplusplus.github.io/CWG/issues/1368.html) | C++98 | any user-provided constructor causedzero-initialization to be skipped | only a user-provideddefault constructorskips zero-initialization | | [CWG 1502](https://cplusplus.github.io/CWG/issues/1502.html) | C++11 | value-initializing a union without a user-provideddefault constructor only zero-initialized theobject, despite default member initializers | performs default-initialization afterzero-initialization | | [CWG 1507](https://cplusplus.github.io/CWG/issues/1507.html) | C++98 | value-initialization for a class object without anyuser-provided constructors did not check the validityof the default constructor when the latter is trivial | the validity of trivialdefault constructoris checked | ### See also * [default constructor](default_constructor "cpp/language/default constructor") * [`explicit`](explicit "cpp/language/explicit") * [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") * [list initialization](list_initialization "cpp/language/list initialization") cpp Move constructors Move constructors ================= A move constructor of class `T` is a non-template [constructor](initializer_list "cpp/language/initializer list") whose first parameter is `T&&`, `const T&&`, `volatile T&&`, or `const volatile T&&`, and either there are no other parameters, or the rest of the parameters all have default values. ### Syntax | | | | | --- | --- | --- | | class-name `(` class-name `&& )` | (1) | (since C++11) | | class-name `(` class-name `&& ) = default;` | (2) | (since C++11) | | class-name `(` class-name `&& ) = delete;` | (3) | (since C++11) | Where class-name must name the current class (or current instantiation of a class template), or, when declared at namespace scope or in a friend declaration, it must be a qualified class name. ### Explanation 1) Typical declaration of a move constructor. 2) Forcing a move constructor to be generated by the compiler. 3) Avoiding implicit move constructor. The move constructor is typically called when an object is [initialized](initialization "cpp/language/initialization") (by [direct-initialization](direct_initialization "cpp/language/direct initialization") or [copy-initialization](copy_initialization "cpp/language/copy initialization")) from [rvalue](value_category#rvalue "cpp/language/value category") (xvalue or prvalue) (until C++17)xvalue (since C++17) of the same type, including. * initialization: `T a = std::move(b);` or `T a(std::move(b));`, where `b` is of type `T`; * function argument passing: `f(std::move(a));`, where `a` is of type `T` and `f` is `void f(T t)`; * function return: `return a;` inside a function such as `T f()`, where `a` is of type `T` which has a move constructor. When the initializer is a prvalue, the move constructor call is often optimized out (until C++17)never made (since C++17), see [copy elision](copy_elision "cpp/language/copy elision"). Move constructors typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc.) rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. For example, moving from a `[std::string](../string/basic_string "cpp/string/basic string")` or from a `[std::vector](../container/vector "cpp/container/vector")` may result in the argument being left empty. However, this behavior should not be relied upon. For some types, such as `[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")`, the moved-from state is fully specified. ### Implicitly-declared move constructor If no user-defined move constructors are provided for a class type (`struct`, `class`, or `union`), and all of the following is true: * there are no user-declared [copy constructors](copy_constructor "cpp/language/copy constructor"); * there are no user-declared [copy assignment operators](copy_assignment "cpp/language/copy assignment"); * there are no user-declared [move assignment operators](move_assignment "cpp/language/move assignment"); * there is no user-declared [destructor](destructor "cpp/language/destructor"). then the compiler will declare a move constructor as a non-[explicit](explicit "cpp/language/explicit") `inline public` member of its class with the signature `T::T(T&&)`. A class can have multiple move constructors, e.g. both `T::T(const T&&)` and `T::T(T&&)`. If some user-defined move constructors are present, the user may still force the generation of the implicitly declared move constructor with the keyword `default`. The implicitly-declared (or defaulted on its first declaration) move constructor has an exception specification as described in [dynamic exception specification](except_spec "cpp/language/except spec") (until C++17)[noexcept specification](noexcept_spec "cpp/language/noexcept spec") (since C++17). ### Deleted implicitly-declared move constructor The implicitly-declared or defaulted move constructor for class `T` is defined as *deleted* if any of the following is true: * `T` has non-static data members that cannot be moved (have deleted, inaccessible, or ambiguous move constructors); * `T` has direct or virtual base class that cannot be moved (has deleted, inaccessible, or ambiguous move constructors); * `T` has direct or virtual base class or a non-static data member with a deleted or inaccessible destructor; * `T` is a union-like class and has a variant member with non-trivial move constructor. A defaulted move constructor that is deleted is ignored by [overload resolution](overload_resolution "cpp/language/overload resolution") (otherwise it would prevent copy-initialization from rvalue). ### Trivial move constructor The move constructor for class `T` is trivial if all of the following is true: * it is not user-provided (meaning, it is implicitly-defined or defaulted); * `T` has no virtual member functions; * `T` has no virtual base classes; * the move constructor selected for every direct base of `T` is trivial; * the move constructor selected for every non-static class type (or array of class type) member of `T` is trivial. A trivial move constructor is a constructor that performs the same action as the trivial copy constructor, that is, makes a copy of the object representation as if by `[std::memmove](../string/byte/memmove "cpp/string/byte/memmove")`. All data types compatible with the C language (POD types) are trivially movable. ### Eligible move constructor | | | | --- | --- | | A move constructor is eligible if it is not deleted. | (until C++20) | | A move constructor is eligible if.* it is not deleted, and * its [associated constraints](constraints "cpp/language/constraints"), if any, are satisfied, and * no move constructor with the same first parameter type is [more constrained](constraints#Partial_ordering_of_constraints "cpp/language/constraints") than it. | (since C++20) | Triviality of eligible move constructors determines whether the class is an [implicit-lifetime type](lifetime#Implicit-lifetime_types "cpp/language/lifetime"), and whether the class is a [trivially copyable type](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"). ### Implicitly-defined move constructor If the implicitly-declared move constructor is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if [odr-used](definition#ODR-use "cpp/language/definition") or [needed for constant evaluation](constant_expression#Functions_and_variables_needed_for_constant_evaluation "cpp/language/constant expression"). For `union` types, the implicitly-defined move constructor copies the object representation (as by `[std::memmove](../string/byte/memmove "cpp/string/byte/memmove")`). For non-union class types (`class` and `struct`), the move constructor performs full member-wise move of the object's bases and non-static members, in their initialization order, using direct initialization with an [xvalue](value_category#xvalue "cpp/language/value category") argument. If this satisfies the requirements of a [constexpr constructor](constexpr "cpp/language/constexpr"), the generated move constructor is `constexpr`. ### Notes To make the [strong exception guarantee](exceptions#Exception_safety "cpp/language/exceptions") possible, user-defined move constructors should not throw exceptions. For example, `[std::vector](../container/vector "cpp/container/vector")` relies on `[std::move\_if\_noexcept](../utility/move_if_noexcept "cpp/utility/move if noexcept")` to choose between move and copy when the elements need to be relocated. If both copy and move constructors are provided and no other constructors are viable, overload resolution selects the move constructor if the argument is an [rvalue](value_category "cpp/language/value category") of the same type (an [xvalue](value_category "cpp/language/value category") such as the result of `std::move` or a [prvalue](value_category "cpp/language/value category") such as a nameless temporary (until C++17)), and selects the copy constructor if the argument is an [lvalue](value_category "cpp/language/value category") (named object or a function/operator returning lvalue reference). If only the copy constructor is provided, all argument categories select it (as long as it takes a reference to const, since rvalues can bind to const references), which makes copying the fallback for moving, when moving is unavailable. A constructor is called a 'move constructor' when it takes an rvalue reference as a parameter. It is not obligated to move anything, the class is not required to have a resource to be moved and a 'move constructor' may not be able to move a resource as in the allowable (but maybe not sensible) case where the parameter is a const rvalue reference (const T&&). ### Example ``` #include <string> #include <iostream> #include <iomanip> #include <utility> struct A { std::string s; int k; A() : s("test"), k(-1) {} A(const A& o) : s(o.s), k(o.k) { std::cout << "move failed!\n"; } A(A&& o) noexcept : s(std::move(o.s)), // explicit move of a member of class type k(std::exchange(o.k, 0)) // explicit move of a member of non-class type {} }; A f(A a) { return a; } struct B : A { std::string s2; int n; // implicit move constructor B::(B&&) // calls A's move constructor // calls s2's move constructor // and makes a bitwise copy of n }; struct C : B { ~C() {} // destructor prevents implicit move constructor C::(C&&) }; struct D : B { D() {} ~D() {} // destructor would prevent implicit move constructor D::(D&&) D(D&&) = default; // forces a move constructor anyway }; int main() { std::cout << "Trying to move A\n"; A a1 = f(A()); // return by value move-constructs the target // from the function parameter std::cout << "Before move, a1.s = " << std::quoted(a1.s) << " a1.k = " << a1.k << '\n'; A a2 = std::move(a1); // move-constructs from xvalue std::cout << "After move, a1.s = " << std::quoted(a1.s) << " a1.k = " << a1.k << '\n'; std::cout << "Trying to move B\n"; B b1; std::cout << "Before move, b1.s = " << std::quoted(b1.s) << "\n"; B b2 = std::move(b1); // calls implicit move constructor std::cout << "After move, b1.s = " << std::quoted(b1.s) << "\n"; std::cout << "Trying to move C\n"; C c1; C c2 = std::move(c1); // calls copy constructor std::cout << "Trying to move D\n"; D d1; D d2 = std::move(d1); } ``` Output: ``` Trying to move A Before move, a1.s = "test" a1.k = -1 After move, a1.s = "" a1.k = 0 Trying to move B Before move, b1.s = "test" After move, b1.s = "" Trying to move C move failed! Trying to move D ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1402](https://cplusplus.github.io/CWG/issues/1402.html) | C++11 | a defaulted move constructor that would calla non-trivial copy constructor was defined asdeleted; a defaulted move constructor that isdeleted still participated in overload resolution | allows call to such copyconstructor; made ignoredin overload resolution | | [CWG 1491](https://cplusplus.github.io/CWG/issues/1491.html) | C++11 | a defaulted move constructor of a class with a non-static datamember of rvalue reference type was defined as deleted | not deleted in this case | | [CWG 2094](https://cplusplus.github.io/CWG/issues/2094.html) | C++11 | a volatile subobject made a defaultedmove constructor non-trivial ([CWG 496](https://cplusplus.github.io/CWG/issues/496.html)) | triviality not affected | ### See also * [converting constructor](converting_constructor "cpp/language/converting constructor") * [copy assignment](copy_assignment "cpp/language/copy assignment") * [copy constructor](copy_constructor "cpp/language/copy constructor") * [copy elision](copy_elision "cpp/language/copy elision") * [default constructor](default_constructor "cpp/language/default constructor") * [destructor](destructor "cpp/language/destructor") * [`explicit`](explicit "cpp/language/explicit") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [constant initialization](constant_initialization "cpp/language/constant initialization") + [copy initialization](copy_initialization "cpp/language/copy initialization") + [default initialization](default_initialization "cpp/language/default initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [initializer list](initializer_list "cpp/language/initializer list") + [list initialization](list_initialization "cpp/language/list initialization") + [reference initialization](reference_initialization "cpp/language/reference initialization") + [value initialization](value_initialization "cpp/language/value initialization") + [zero initialization](zero_initialization "cpp/language/zero initialization") * [move assignment](move_assignment "cpp/language/move assignment") * [`new`](new "cpp/language/new")
programming_docs
cpp Injected-class-name Injected-class-name =================== The injected-class-name is the name of a class within the scope of said class. In a [class template](class_template "cpp/language/class template"), the injected-class-name can be used either as a template name that refers to the current template, or as a class name that refers to the current instantiation. ### Explanation In a class scope, the name of the current class is treated as if it were a public member name; this is called *injected-class-name*. The point of declaration of the name is immediately following the opening brace of the class definition. ``` int X; struct X { void f() { X* p; // OK. X refers to the injected-class-name ::X* q; // Error: name lookup finds a variable name, which hides the struct name } }; ``` Like other members, injected-class-names are inherited. In the presence of private or protected inheritance, the injected-class-name of an indirect base class might end up being inaccessible in a derived class. ``` struct A {}; struct B : private A {}; struct C : public B { A* p; // Error: injected-class-name A is inaccessible ::A* q; // OK, does not use the injected-class-name }; ``` ### In class template Like other classes, class templates have an injected-class-name. The injected-class-name can be used as a template-name or a type-name. In the following cases, the injected-class-name is treated as a template-name of the class template itself: * it is followed by `<` * it is used as a [template template argument](template_parameters#Template_template_arguments "cpp/language/template parameters") * it is the final identifier in the [elaborated class specifier](elaborated_type_specifier "cpp/language/elaborated type specifier") of a friend class template declaration. Otherwise, it is treated as a type-name, and is equivalent to the template-name followed by the template-parameters of the class template enclosed in `<>`. ``` template<template<class, class> class> struct A; template<class T1, class T2> struct X { X<T1, T2>* p; // OK, X is treated as a template-name using a = A<X>; // OK, X is treated as a template-name template<class U1, class U2> friend class X; // OK, X is treated as a template-name X* q; // OK, X is treated as a type-name, equivalent to X<T1, T2> }; ``` Within the scope of a class [template specialization](template_specialization "cpp/language/template specialization") or [partial specialization](partial_specialization "cpp/language/partial specialization"), when the injected-class-name is used as a type-name, it is equivalent to the template-name followed by the template-arguments of the class template specialization or partial specialization enclosed in `<>`. ``` template<> struct X<void, void> { X* p; // OK, X is treated as a type-name, equivalent to X<void, void> template<class, class> friend class X; // OK, X is treated as a template-name (same as in primary template) X<void, void>* q; // OK, X is treated as a template-name }; template<class T> struct X<char, T> { X* p, q; // OK, X is treated as a type-name, equivalent to X<char, T> using r = X<int, int>; // OK, can be used to name another specialization }; ``` The injected-class-name of a class template or class template specialization can be used either as a template-name or a type-name wherever it is in scope. ``` template<> class X<int, char> { class B { X a; // meaning X<int, char> template<class, class> friend class X; // meaning ::X }; }; template<class T> struct Base { Base* p; // OK: Base means Base<T> }; template<class T> struct Derived : public Base<T*> { typename Derived::Base* p; // OK: Derived::Base means Derived<T>::Base, // which is Base<T*> }; template<class T, template<class> class U = T::template Base> struct Third {}; Third<Derived<int>> t; // OK: default argument uses injected-class-name as a template ``` A lookup that finds an injected-class-name can result in an ambiguity in certain cases (for example, if it is found in more than one base class). If all of the injected-class-names that are found refer to specializations of the same class template, and if the name is used as a template-name, the reference refers to the class template itself and not a specialization thereof, and is not ambiguous. ``` template<class T> struct Base {}; template<class T> struct Derived: Base<int>, Base<char> { typename Derived::Base b; // error: ambiguous typename Derived::Base<double> d; // OK }; ``` ### injected-class-name and constructors Constructors do not have names, but the injected-class-name of the enclosing class is considered to name a constructor in constructor declarations and definitions. In a qualified name `C::D`, if. * name lookup does not ignore function names, and * lookup of `D` in the scope of the class `C` finds its injected-class-name the qualified name is always considered to name `C`'s constructor. Such a name can only be used in the declaration of a constructor (e.g. in a friend constructor declaration, a constructor template specialization, constructor template instantiation, or constructor definition) or be used to inherit constructors (since C++11). ``` struct A { A(); A(int); template<class T> A(T) {} }; using A_alias = A; A::A() {} A_alias::A(int) {} template A::A(double); struct B : A { using A_alias::A; }; A::A a; // Error: A::A is considered to name a constructor, not a type struct A::A a2; // OK, same as 'A a2;' B::A b; // OK, same as 'A b;' ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1004](https://cplusplus.github.io/CWG/issues/1004.html) | C++98 | an injected-class-name could notbe a template template argument | allowed, it refers to the classtemplate itself in this case | cpp Zero-overhead principle Zero-overhead principle ======================= The *zero-overhead principle* is a C++ design principle that states: 1. You don't pay for what you don't use. 2. What you do use is just as efficient as what you could reasonably write by hand. In general, this means that no feature should be added to C++ that would impose any overhead, whether in time or space, greater than a programmer would introduce without using the feature. The only two features in the language that do not follow the zero-overhead principle are [runtime type identification](typeid "cpp/language/typeid") and [exceptions](exceptions "cpp/language/exceptions"), and are why most compilers include a switch to turn them off. ### External links * [Foundations of C++](http://www.stroustrup.com/ETAPS-corrected-draft.pdf) - Bjarne Stroustrup. * [C++ exceptions and alternatives](https://wg21.link/p1947) - Bjarne Stroustrup. * [De-fragmenting C++](https://youtu.be/ARYP83yNAWk) - Making [Exceptions](exceptions "cpp/language/exceptions") and [RTTI](types "cpp/language/types") More Affordable and Usable - Herb Sutter. * [Bjarne Stroustrup: C++ | Artificial Intelligence (AI) Podcast](https://youtu.be/uTxRF5ag27A?t=2478). cpp Expressions Expressions =========== An expression is a sequence of *operators* and their *operands*, that specifies a computation. Expression evaluation may produce a result (e.g., evaluation of `2 + 2` produces the result `4`) and may generate side-effects (e.g. evaluation of `[std::printf](http://en.cppreference.com/w/cpp/io/c/fprintf)("%d",4)` prints the character `'4'` on the standard output). Each C++ expression is characterized by two independent properties: A type and a value category. #### General * [value categories](value_category "cpp/language/value category") (lvalue, rvalue, glvalue, prvalue, xvalue (since C++11)) classify expressions by their values * [order of evaluation](eval_order "cpp/language/eval order") of arguments and subexpressions specify the order in which intermediate results are obtained ### Operators | Common operators | | --- | | [assignment](operator_assignment "cpp/language/operator assignment") | [incrementdecrement](operator_incdec "cpp/language/operator incdec") | [arithmetic](operator_arithmetic "cpp/language/operator arithmetic") | [logical](operator_logical "cpp/language/operator logical") | [comparison](operator_comparison "cpp/language/operator comparison") | [memberaccess](operator_member_access "cpp/language/operator member access") | [other](operator_other "cpp/language/operator other") | | `a = b a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<= b a >>= b`. | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a | b a ^ b a << b a >> b`. | `!a a && b a || b`. | `a == b a != b a < b a > b a <= b a >= b a <=> b`. | `a[b] *a &a a->b a.b a->*b a.*b`. | `a(...) a, b a ? b : c`. | | Special operators | | [`static_cast`](static_cast "cpp/language/static cast") converts one type to another related type [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") converts within inheritance hierarchies [`const_cast`](const_cast "cpp/language/const cast") adds or removes [cv](cv "cpp/language/cv") qualifiers [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") converts type to unrelated type [C-style cast](explicit_cast "cpp/language/explicit cast") converts one type to another by a mix of `static_cast`, `const_cast`, and `reinterpret_cast` [`new`](new "cpp/language/new") creates objects with dynamic storage duration [`delete`](delete "cpp/language/delete") destructs objects previously created by the new expression and releases obtained memory area [`sizeof`](sizeof "cpp/language/sizeof") queries the size of a type [`sizeof...`](sizeof... "cpp/language/sizeof...") queries the size of a [parameter pack](parameter_pack "cpp/language/parameter pack") (since C++11) [`typeid`](typeid "cpp/language/typeid") queries the type information of a type [`noexcept`](noexcept "cpp/language/noexcept") checks if an expression can throw an exception (since C++11) [`alignof`](alignof "cpp/language/alignof") queries alignment requirements of a type (since C++11). | * [operator precedence](operator_precedence "cpp/language/operator precedence") defines the order in which operators are bound to their arguments * [alternative representations](operator_alternative "cpp/language/operator alternative") are alternative spellings for some operators * [operator overloading](operators "cpp/language/operators") makes it possible to specify the behavior of the operators with user-defined classes. #### Conversions * [standard conversions](implicit_conversion "cpp/language/implicit conversion") implicit conversions from one type to another * [`const_cast` conversion](const_cast "cpp/language/const cast") * [`static_cast` conversion](static_cast "cpp/language/static cast") * [`dynamic_cast` conversion](dynamic_cast "cpp/language/dynamic cast") * [`reinterpret_cast` conversion](reinterpret_cast "cpp/language/reinterpret cast") * [explicit cast](explicit_cast "cpp/language/explicit cast") conversion using C-style cast notation and function-style notation * [user-defined conversion](cast_operator "cpp/language/cast operator") makes it possible to specify conversion from user-defined classes #### Memory allocation * [new expression](new "cpp/language/new") allocates memory dynamically * [delete expression](delete "cpp/language/delete") deallocates memory dynamically #### Other * [constant expressions](constant_expression "cpp/language/constant expression") can be evaluated at compile time and used in compile-time context (template arguments, array sizes, etc) * [`sizeof`](sizeof "cpp/language/sizeof") * [`alignof`](alignof "cpp/language/alignof") * [`typeid`](typeid "cpp/language/typeid") * [throw-expression](throw "cpp/language/throw") ### Primary expressions The operands of any operator may be other expressions or primary expressions (e.g. in `1 + 2 * 3`, the operands of operator+ are the [subexpression](#Full-expressions) `2 * 3` and the primary expression `1`). Primary expressions are any of the following: * [`this`](this "cpp/language/this") * literals (e.g. `2` or `"Hello, world"`) * id-expressions, including + suitably declared [unqualified identifiers](identifiers#Unqualified_identifiers "cpp/language/identifiers") (e.g. `n` or `cout`), + suitably declared [qualified identifiers](identifiers#Qualified_identifiers "cpp/language/identifiers") (e.g. `[std::string::npos](../string/basic_string/npos "cpp/string/basic string/npos")`), and + identifiers to be declared in [declarators](declarations#Declarators "cpp/language/declarations") | | | | --- | --- | | * [lambda-expressions](lambda "cpp/language/lambda") | (since C++11) | | * [fold-expressions](fold "cpp/language/fold") | (since C++17) | | * [requires-expressions](requires "cpp/language/requires") | (since C++20) | Any expression in parentheses is also classified as a primary expression: this guarantees that the parentheses have higher precedence than any operator. Parentheses preserve value, type, and value category. #### Literals Literals are the tokens of a C++ program that represent constant values embedded in the source code. * [integer literals](integer_literal "cpp/language/integer literal") are decimal, octal, hexadecimal or binary numbers of integer type. * [character literals](character_literal "cpp/language/character literal") are individual characters of type + `char` or `wchar_t` | | | | --- | --- | | * `char16_t` or `char32_t` | (since C++11) | | * `char8_t` | (since C++20) | * [floating-point literals](floating_literal "cpp/language/floating literal") are values of type `float`, `double`, or `long double` * [string literals](string_literal "cpp/language/string literal") are sequences of characters of type + `const char[]` or `const wchar_t[]` | | | | --- | --- | | * `const char16_t[]` or `const char32_t[]` | (since C++11) | | * `const char8_t[]` | (since C++20) | * [boolean literals](bool_literal "cpp/language/bool literal") are values of type `bool`, that is `true` and `false` | | | | --- | --- | | * [`nullptr`](nullptr "cpp/language/nullptr") is the pointer literal which specifies a null pointer value * [user-defined literals](user_literal "cpp/language/user literal") are constant values of user-specified type | (since C++11) | ### Full-expressions | | | | --- | --- | | A *constituent expression* is defined as follows:* The constituent expression of an expression is that expression. * The constituent expressions of a braced-init-list or of a (possibly parenthesized) expression list are the constituent expressions of the elements of the respective list. * The constituent expressions of a brace-or-equal-initializer of the form `=` initializer-clause are the constituent expressions of the initializer-clause. ``` int num1 = 0; num1 += 1; // Case 1: the constitunent expression of `num += 1` is `num += 1` int arr2[2] = {2, 22} // Case 2: the constitunent expressions // of `{2, 22}` are `2` and `22` // Case 3: the constitunent expressions of ` = {2, 22}` // are the constitunent expressions of `{2, 22}` // (i.e. also `2` and `22`) ``` The *immediate subexpressions* of an expression `E` are.* the constituent expressions of `E`’s operands, * any function call that `E` implicitly invokes, * if `E` is a [lambda expression](lambda "cpp/language/lambda"), the initialization of the entities captured by copy and the constituent expressions of the initializer of the captures, * if `E` is a function call or implicitly invokes a function, the constituent expressions of each [default argument](default_arguments "cpp/language/default arguments") used in the call, or * if `E` creates an [aggregate](aggregate_initialization#Definitions "cpp/language/aggregate initialization") object, the constituent expressions of each [default member initializer](data_members#Member_initialization "cpp/language/data members") used in the initialization. A *subexpression* of an expression `E` is an immediate subexpression of `E` or a subexpression of an immediate subexpression of `E`. Note that expressions appearing in the 'function body' of lambda expressions are not subexpressions of the lambda expression. | (since C++17) | | | | | --- | --- | | A *full-expression* is an expression that is not a subexpression of another expression. In some contexts, such as [unevaluated operands](#Unevaluated_expressions), a syntactic subexpression is considered a full-expression. (since C++14). | (until C++17) | | A *full-expression* is.* an [unevaluated operand](#Unevaluated_expressions), * a [constant expression](constant_expression "cpp/language/constant expression"), | | | | --- | --- | | * an [immediate invocation](consteval "cpp/language/consteval"), | (since C++20) | * a declarator of a [simple declaration](declarations#Simple_declaration "cpp/language/declarations") or a [member initializer](constructor "cpp/language/constructor"), including the constituent expressions of the initializer, * an invocation of a [destructor](destructor "cpp/language/destructor") generated at the end of the [lifetime](lifetime "cpp/language/lifetime") of an object other than a temporary object whose lifetime has not been extended, or * an expression that is not a subexpression of another expression and that is not otherwise part of a full-expression. | (since C++17) | If a language construct is defined to produce an implicit call of a function, a use of the language construct is considered to be an expression for the purposes of this definition. Conversions applied to the result of an expression in order to satisfy the requirements of the language construct in which the expression appears are also considered to be part of the full-expression. | | | | --- | --- | | A call to a destructor generated at the end of the lifetime of an object other than a temporary object whose lifetime has not been extended is an implicit full-expression. | (since C++11)(until C++17) | | For an initializer, performing the initialization of the entity (including evaluating default member initializers of an aggregate) is also considered part of the full-expression. | (since C++17) | ### Unevaluated expressions The operands of the operators [`typeid`](typeid "cpp/language/typeid"), [`sizeof`](sizeof "cpp/language/sizeof"), [`noexcept`](noexcept "cpp/language/noexcept"), and [`decltype`](decltype "cpp/language/decltype") (since C++11) are expressions that are not evaluated (unless they are polymorphic glvalues and are the operands of `typeid`), since these operators only query the compile-time properties of their operands. Thus, `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t) n = sizeof([std::cout](http://en.cppreference.com/w/cpp/io/cout) << 42);` does not perform console output. | | | | --- | --- | | The [requires-expressions](requires "cpp/language/requires") are also unevaluated expressions. | (since C++20) | ### Discarded-value expressions A *discarded-value expression* is an expression that is used for its side-effects only. The value calculated from such expression is discarded. Such expressions include the full-expression of any [expression statement](statements#Expression_statements "cpp/language/statements"), the left-hand operand of the built-in comma operator, or the operand of a cast-expression that casts to the type `void`. Array-to-pointer and function-to-pointer conversions are never applied to the value calculated by a discarded-value expression. The lvalue-to-rvalue conversion is applied if and only if the expression is a [volatile-qualified](cv "cpp/language/cv") lvalue (until C++11)glvalue (since C++11) and has one of the following forms (built-in meaning required, possibly parenthesized): * id-expression, * array subscript expression, * class member access expression, * indirection, * pointer-to-member operation, * conditional expression where both the second and the third operands are one of these expressions, * comma expression where the right operand is one of these expressions. In addition, if the lvalue is of volatile-qualified class type, a volatile copy constructor is required to initialize the resulting rvalue temporary. | | | | --- | --- | | If the expression is a non-void prvalue (after any lvalue-to-rvalue conversion that might have taken place), [temporary materialization](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion") occurs. Compilers may issue warnings when an expression other than cast to `void` discards a value declared `[[[nodiscard](attributes/nodiscard "cpp/language/attributes/nodiscard")]]`. | (since C++17) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1054](https://cplusplus.github.io/CWG/issues/1054.html) | C++98 | assigning a value to a volatile variable mightresult in an unnecessary read due to the lvalue-to-rvalue conversion applied to the assignment result | introduce discarded-value expressionsand exclude this case from the listof cases that require the conversion | | [CWG 1383](https://cplusplus.github.io/CWG/issues/1383.html) | C++98 | the list of expressions where lvalue-to-rvalueconversion is applied to discarded-valueexpressions also covered overloaded operators | only cover operatorswith built-in meaning | | [CWG 1576](https://cplusplus.github.io/CWG/issues/1576.html) | C++11 | lvalue-to-rvalue conversions were not appliedto discarded-value volatile xvalue expressions | apply the conversionin this case | | [CWG 2249](https://cplusplus.github.io/CWG/issues/2249.html) | C++98 | identifiers to be declared in declarators were not id-expressions | they are | | [CWG 2431](https://cplusplus.github.io/CWG/issues/2431.html) | C++11 | the invocations of the destructors of temporaries thatare bound to references were not full-expressions | they are | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/expressions "c/language/expressions") for Expressions |
programming_docs
cpp Constant expressions Constant expressions ==================== Defines an [expression](expressions "cpp/language/expressions") that can be evaluated at compile time. Such expressions can be used as non-type template arguments, array sizes, and in other contexts that require constant expressions, e.g. ``` int n = 1; std::array<int, n> a1; // error: n is not a constant expression const int cn = 2; std::array<int, cn> a2; // OK: cn is a constant expression ``` ### Core constant expressions A *core constant expression* is any expression whose evaluation *would not* evaluate any one of the following: 1. the [`this`](this "cpp/language/this") pointer, except in a `constexpr` function that is being evaluated as part of the expression 2. (since C++23) a control flow that passes through a declaration of a variable with static or thread [storage duration](storage_duration "cpp/language/storage duration") 3. a function call expression that calls a function (or a constructor) that is not declared [constexpr](constexpr "cpp/language/constexpr") ``` constexpr int n = std::numeric_limits<int>::max(); // OK: max() is constexpr constexpr int m = std::time(nullptr); // Error: std::time() is not constexpr ``` 4. a function call to a `constexpr` function which is declared, but not defined 5. a function call to a `constexpr` function/constructor template instantiation where the instantiation fails to satisfy [constexpr function/constructor](constexpr "cpp/language/constexpr") requirements. 6. a function call to a constexpr virtual function, invoked on an object not [usable in constant expressions](#Usable_in_constant_expressions) and whose lifetime began outside this expression. 7. an expression that would exceed the implementation-defined limits 8. an expression whose evaluation leads to any form of core language undefined behavior (including signed integer overflow, division by zero, pointer arithmetic outside array bounds, etc). Whether standard library undefined behavior is detected is unspecified. ``` constexpr double d1 = 2.0/1.0; // OK constexpr double d2 = 2.0/0.0; // Error: not defined constexpr int n = std::numeric_limits<int>::max() + 1; // Error: overflow int x, y, z[30]; constexpr auto e1 = &y - &x; // Error: undefined constexpr auto e2 = &z[20] - &z[3]; // OK constexpr std::bitset<2> a; constexpr bool b = a[2]; // UB, but unspecified if detected ``` 9. (until C++17) a [lambda expression](lambda "cpp/language/lambda") 10. an lvalue-to-rvalue [implicit conversion](implicit_conversion "cpp/language/implicit conversion") unless.... 1. applied to a non-volatile glvalue that designates an object that is [usable in constant expressions](#Usable_in_constant_expressions), ``` int main() { const std::size_t tabsize = 50; int tab[tabsize]; // OK: tabsize is a constant expression // because tabsize is usable in constant expressions // because it has const-qualified integral type, and // its initializer is a constant initializer std::size_t n = 50; const std::size_t sz = n; int tab2[sz]; // error: sz is not a constant expression // because sz is not usable in constant expressions // because its initializer was not a constant initializer } ``` 2. or applied to a non-volatile glvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of this expression 11. an lvalue-to-rvalue [implicit conversion](implicit_conversion "cpp/language/implicit conversion") or modification applied to a non-active member of a [union](union "cpp/language/union") or its subobject (even if it shares a common initial sequence with the active member) 12. (since C++20) an lvalue-to-rvalue implicit conversion applied to an object with an [indeterminate value](default_initialization "cpp/language/default initialization") 13. an invocation of an implicitly-defined copy/move constructor or copy/move assignment operator for a union whose active member (if any) is mutable, unless the lifetime of the union object began within the evaluation of this expression 14. (since C++17) (until C++20) an assignment expression or invocation of an overloaded assignment operator that would change the active member of a union 15. an id-expression referring to a variable or a data member of reference type, unless the reference is [usable in constant expressions](#Usable_in_constant_expressions) or its lifetime began within the evaluation of this expression 16. conversion from `cv void*` to any pointer-to-object type 17. (until C++20) [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") 18. [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") 19. (until C++20) pseudo-destructor call 20. (until C++14) an increment or a decrement operator 21. (since C++14) modification of an object, unless the object has non-volatile literal type and its lifetime began within the evaluation of the expression. ``` constexpr int incr(int& n) { return ++n; } constexpr int g(int k) { constexpr int x = incr(k); // error: incr(k) is not a core constant // expression because lifetime of k // began outside the expression incr(k) return x; } constexpr int h(int k) { int x = incr(k); // OK: x is not required to be initialized // with a core constant expression return x; } constexpr int y = h(1); // OK: initializes y with the value 2 // h(1) is a core constant expression because // the lifetime of k begins inside the expression h(1) ``` 22. (since C++20) a destructor call or pseudo destructor call for an object whose lifetime did not begin within the evaluation of this expression 23. (until C++20) a [`typeid`](typeid "cpp/language/typeid") expression applied to a glvalue of polymorphic type 24. a [new-expression](new "cpp/language/new"), unless the selected [allocation function](../memory/new/operator_new "cpp/memory/new/operator new") is a replaceable global allocation function and the allocated storage is deallocated within the evaluation of this expression (since C++20) 25. a [delete-expression](delete "cpp/language/delete"), unless it deallocates a region of storage allocated within the evaluation of this expession (since C++20) 26. (since C++20) a call to `[std::allocator<T>::allocate](../memory/allocator/allocate "cpp/memory/allocator/allocate")`, unless the allocated storage is deallocated within the evaluation of this expression 27. (since C++20) a call to `[std::allocator<T>::deallocate](../memory/allocator/deallocate "cpp/memory/allocator/deallocate")`, unless it deallocates a region of storage allocated within the evaluation of this expession 28. (since C++20) an [await-expression](coroutines#co_await "cpp/language/coroutines") or a [yield-expression](coroutines#co_yield "cpp/language/coroutines") 29. (since C++20) a [three-way comparison](operator_comparison#Three-way_comparison "cpp/language/operator comparison") when the result is unspecified 30. an equality or relational operator when the result is unspecified 31. (until C++14) an assignment or a compound assignment operator 32. a throw expression 33. (since C++20) an [asm-declaration](asm "cpp/language/asm") 34. (since C++14) an invocation of the `[va\_arg](../utility/variadic/va_arg "cpp/utility/variadic/va arg")` macro, whether an invocation of the `[va\_start](../utility/variadic/va_start "cpp/utility/variadic/va start")` macro can be evaluated is unspecified 35. (since C++23) a [`goto`](goto "cpp/language/goto") statement 36. (since C++20) a [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") or [`typeid`](typeid "cpp/language/typeid") expression that would throw an exception 37. inside a lambda-expression, a reference to `this` or to a variable defined outside that lambda, if that reference would be an odr-use ``` void g() { const int n = 0; constexpr int j = *&n; // OK: outside of a lambda-expression [=] { constexpr int i = n; // OK: 'n' is not odr-used and not captured here. constexpr int j = *&n; // Ill-formed: '&n' would be an odr-use of 'n'. }; } ``` | | | | --- | --- | | note that if the ODR-use takes place in a function call to a closure, it does not refer to `this` or to an enclosing variable, since it accesses a closure's data member instead. ``` // OK: 'v' & 'm' are odr-used but do not occur in a constant-expression // within the nested lambda auto monad = [](auto v){ return [=]{ return v; }; }; auto bind = [](auto m){ return [=](auto fvm){ return fvm(m()); }; }; // OK to have captures to automatic objects created during constant expression evaluation. static_assert(bind(monad(2))(monad)() == monad(2)()); ``` | (since C++17) | Note: Just being a *core constant expression* does not have any direct semantic meaning: an expression has to be one of the subsets of constant expressions (see below) to be used in certain contexts. ### Constant expression A *constant expression* is either. * an lvalue (until C++14)a glvalue (since C++14) *core constant expression* that refers to + an object with static storage duration that is not a temporary, or | | | | --- | --- | | * an object with static storage duration that is a temporary, but whose value satisfies the constraints for prvalues below, or | (since C++14) | * a non-[immediate](consteval "cpp/language/consteval") (since C++20) function * a prvalue *core constant expression* whose value satisfies the following constraints: * if the value is an object of class type, each non-static data member of reference type refers to an entity that satisfies the constraints for lvalues (until C++14)glvalues (since C++14) above * if the value is of pointer type, it holds + address of an object with static storage duration + address past the end of an object with static storage duration + address of a non-[immediate](consteval "cpp/language/consteval") (since C++20) function + a null pointer value | | | | --- | --- | | * if the value is of pointer-to-member-function type, it does not designate an [immediate function](consteval "cpp/language/consteval") | (since C++20) | * if the value is an object of class or array type, each subobject satisfies these constraints for values ``` void test() { static const int a = std::random_device{}(); constexpr const int& ra = a; // OK: a is a glvalue constant expression constexpr int ia = a; // Error: a is not a prvalue constant expression const int b = 42; constexpr const int& rb = b; // Error: b is not a glvalue constant expression constexpr int ib = b; // OK: b is a prvalue constant expression } ``` #### Integral constant expression *Integral constant expression* is an expression of integral or unscoped enumeration type implicitly converted to a prvalue, where the converted expression is a *core constant expression*. If an expression of class type is used where an integral constant expression is expected, the expression is [contextually implicitly converted](implicit_cast "cpp/language/implicit cast") to an integral or unscoped enumeration type. The following contexts require an *integral constant expression*: | | | | --- | --- | | * [array bounds](array "cpp/language/array") * the dimensions in [new-expressions](new "cpp/language/new") other than the first | (until C++14) | * [bit-field lengths](bit_field "cpp/language/bit field") * enumeration initializers when the underlying type is not fixed * [alignments](alignas "cpp/language/alignas"). #### Converted constant expression A *converted constant expression* of type `T` is an expression [implicitly converted](implicit_cast "cpp/language/implicit cast") to type T, where the converted expression is a constant expression, and the implicit conversion sequence contains only: * constexpr user-defined conversions (so a class can be used where integral type is expected) * lvalue-to-rvalue conversions * integral promotions * non-narrowing integral conversions | | | | --- | --- | | * array-to-pointer conversions * function-to-pointer conversions * function pointer conversions (pointer to noexcept function to pointer to function) * qualification conversions * null pointer conversions from `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` * null member pointer conversions from `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` | (since C++17) | * And if any [reference binding](reference_initialization "cpp/language/reference initialization") takes place, it is direct binding (not one that constructs a temporary object) The following contexts require a *converted constant expression*: * [case expressions](switch "cpp/language/switch") * [enumerator initializers](enum "cpp/language/enum") when the underlying type is fixed | | | | --- | --- | | * [array bounds](array "cpp/language/array") * the dimensions in [new-expressions](new "cpp/language/new") other than the first | (since C++14) | * integral and enumeration (until C++17)non-type [template arguments](template_parameters "cpp/language/template parameters"). A *contextually converted constant expression of type `bool`* is an expression, [contextually converted to `bool`](implicit_cast#Contextual_conversions "cpp/language/implicit cast"), where the converted expression is a constant expression and the conversion sequence contains only the conversions above. The following contexts require a *contextually converted constant expression of type `bool`*: * [`noexcept` specifications](noexcept_spec "cpp/language/noexcept spec") | | | | --- | --- | | * [`static_assert` declarations](static_assert "cpp/language/static assert") | (until C++23) | | | | | --- | --- | | * [constexpr `if` statements](if#Constexpr_if "cpp/language/if") | (since C++17)(until C++23) | | | | | --- | --- | | * [conditional `explicit` specifiers](explicit "cpp/language/explicit") | (since C++20) | #### Historical categories Categories of constant expressions listed below are no longer used in the standard since C++14: * A *literal constant expression* is a prvalue *core constant expression* of non-pointer literal type (after conversions as required by context). A literal constant expression of array or class type requires that each subobject is initialized with a constant expression. * A *reference constant expression* is an lvalue core constant expression that designates an object with static storage duration or a function. * An *address constant expression* is a prvalue core constant expression (after conversions required by context) of type `[std::nullptr\_t](http://en.cppreference.com/w/cpp/types/nullptr_t)` or of a pointer type, which points to an object with static storage duration, one past the end of an array with static storage duration, to a function, or is a null pointer. ### Usable in constant expressions In the list above, a variable is *usable in constant expressions* at a point `P` if. * the variable is * a constexpr variable, or * it is a [constant-initialized](constant_initialization "cpp/language/constant initialization") variable + of reference type or + of const-qualified integral or enumeration type * and the definition of the variable is reachable from `P` | | | | --- | --- | | * and, if `P` is not in the same translation unit as the definition of the variable (that is, the definition is [imported](modules "cpp/language/modules")), the variable is not initialized to point to, or refer to, or have a (possibly recursive) subobject that points to or refers to, a [translation-unit-local entity](tu_local "cpp/language/tu local") that is usable in constant expressions | (since C++20) | An object or reference is *usable in constant expressions* if it is. * a variable that is usable in constant expressions, or | | | | --- | --- | | * a [template parameter object](template_parameters#template_parameter_object "cpp/language/template parameters"), or | (since C++20) | * a string literal object, or * a non-mutable subobject or reference member of any of the above, or * a temporary object of non-volatile const-qualified literal type whose lifetime is [extended](reference_initialization#Lifetime_of_a_temporary "cpp/language/reference initialization") to that of a variable that is usable in constant expressions. ``` const std::size_t sz = 10; // sz is usable in constant expressions ``` ### Manifestly constant-evaluated expressions The following expressions (including conversions to the destination type) are *manifestly constant-evaluated*: * Where a constant expression is grammatically required, including: + [array bounds](array "cpp/language/array") + the dimensions in [new-expressions](new "cpp/language/new") other than the first + [bit-field lengths](bit_field "cpp/language/bit field") + [enumeration initializers](enum "cpp/language/enum") + [alignments](alignas "cpp/language/alignas") + [`case` expressions](switch "cpp/language/switch") + non-type [template arguments](template_parameters "cpp/language/template parameters") + expressions in [`noexcept` specifications](noexcept_spec "cpp/language/noexcept spec") + expressions in [`static_assert` declarations](static_assert "cpp/language/static assert") | | | | --- | --- | | * expressions in [conditional `explicit` specifiers](explicit "cpp/language/explicit") | (since C++20) | | | | | --- | --- | | * conditions of [constexpr if statements](if#Constexpr_if "cpp/language/if") | (since C++17) | | | | | --- | --- | | * [immediate invocations](consteval "cpp/language/consteval") * constraint expressions in [concept](constraints#Concepts "cpp/language/constraints") definitions, [nested requirements](constraints#Nested_requirements "cpp/language/constraints"), and [requires clauses](constraints#Requires_clauses "cpp/language/constraints") | (since C++20) | * initializers of variables that are [usable in constant expressions](#Usable_in_constant_expressions), including: + initializers of [constexpr variables](constexpr "cpp/language/constexpr") + initializers of variables with reference type or const-qualified integral or enumeration type, when the initializers are constant expressions * initializers of static and thread local variables, when all subexpressions of the initializers (including constructor calls and implicit conversions) are constant expressions (that is, when the initializers are [constant initializers](constant_initialization "cpp/language/constant initialization")) Note the context of the last two cases also accept non-constant expressions. | | | | --- | --- | | Whether an evaluation occurs in a manifestly constant-evaluated context can be detected by `[std::is\_constant\_evaluated](../types/is_constant_evaluated "cpp/types/is constant evaluated")` and [`if consteval`](if#Consteval_if "cpp/language/if") (since C++23). To test the last two conditions, compilers may first perform a trial constant evaluation of the initializers. It is not recommended to depend on the result in this case. | (since C++20) | ### Functions and variables needed for constant evaluation Following expressions or conversions are *potentially constant evaluated*: * manifestly constant-evaluated expressions * potentially-evaluated expressions * immediate subexpressions of a braced-init-list (constant evaluation may be necessary to determine whether [a conversion is narrowing](list_initialization#Narrowing_conversions "cpp/language/list initialization")) * address-of (unary `&`) expressions that occur within a [templated entity](templates#Templated_entity "cpp/language/templates") (constant evaluation may be necessary to determine whether such an expression is [value-dependent](dependent_name#Value-dependent_expressions "cpp/language/dependent name")) * subexpressions of one of the above that are not a subexpression of a nested [unevaluated operand](expressions#Unevaluated_expressions "cpp/language/expressions") A function is *needed for constant evaluation* if it is a constexpr function and [named by](definition#Naming_a_function "cpp/language/definition") an expression that is potentially constant evaluated. A variable is *needed for constant evaluation* if it is either a constexpr variable or is of non-volatile const-qualified integral type or of reference type and the [id-expression](expressions#Primary_expressions "cpp/language/expressions") that denotes it is potentially constant evaluated. Definition of a defaulted function and instantiation of a [function template](function_template "cpp/language/function template") specialization or [variable template](variable_template "cpp/language/variable template") specialization (since C++14) are triggered if the function or variable (since C++14) is needed for constant evaluation. ### Notes Implementations are not permitted to declare library functions as `constexpr` unless the standard says the function is `constexpr`. [Named return value optimization](copy_elision "cpp/language/copy elision") (NRVO) is not permitted in constant expressions, while return value optimization (RVO) is mandatory. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1293](https://cplusplus.github.io/CWG/issues/1293.html) | C++11 | it was unspecified whether string literalsare usable in constant expressions | they are usable | | [CWG 1311](https://cplusplus.github.io/CWG/issues/1311.html) | C++11 | volatile glvalues could be used in constant expressions | prohibited | | [CWG 1312](https://cplusplus.github.io/CWG/issues/1312.html) | C++11 | `reinterpret_cast` is prohibited in constant expressions,but casting to and from void\* could achieve the same effect | prohibited conversionsfrom type `cv void*` toa pointer-to-object type | | [CWG 1313](https://cplusplus.github.io/CWG/issues/1313.html) | C++11 | undefined behavior was permitted;all pointer subtraction was prohibited | UB prohibited; same-arraypointer subtraction OK | | [CWG 1405](https://cplusplus.github.io/CWG/issues/1405.html) | C++11 | for objects that are usable in constant expressions,their mutable subobjects were also usable | they are not usable | | [CWG 1454](https://cplusplus.github.io/CWG/issues/1454.html) | C++11 | passing constants through constexprfunctions via references was not allowed | allowed | | [CWG 1455](https://cplusplus.github.io/CWG/issues/1455.html) | C++11 | converted constant expressions could only be prvalues | can be lvalues | | [CWG 1456](https://cplusplus.github.io/CWG/issues/1456.html) | C++11 | an address constant expression could notdesignate the address one past the end of an array | allowed | | [CWG 1535](https://cplusplus.github.io/CWG/issues/1535.html) | C++11 | a `typeid` expression whose operand is of apolymorphic class type was not a core constantexpression even if no runtime check is involved | the operand constraintis limited to glvalues ofpolymorphic class types | | [CWG 1581](https://cplusplus.github.io/CWG/issues/1581.html) | C++11 | functions needed for constant evaluation werenot required to be defined or instantiated | required | | [CWG 1694](https://cplusplus.github.io/CWG/issues/1694.html) | C++11 | binding the value of a temporary to a static storageduration reference was a constant expression | it is not aconstant expression | | [CWG 1952](https://cplusplus.github.io/CWG/issues/1952.html) | C++11 | standard library undefined behaviorswere required to be diagnosed | unspecified whetherthey are diagnosed | | [CWG 2126](https://cplusplus.github.io/CWG/issues/2126.html) | C++11 | constant initialized lifetime-extended temporaries of const-qualified literal types were not usable in constant expressions | usable | | [CWG 2167](https://cplusplus.github.io/CWG/issues/2167.html) | C++11 | non-member references local to an evaluationmade the evaluation non-constexpr | non-memberreferences allowed | | [CWG 2299](https://cplusplus.github.io/CWG/issues/2299.html) | C++14 | it was unclear whether macros in [`<cstdarg>`](../header/cstdarg "cpp/header/cstdarg")can be used in constant evaluation | `va_arg` forbidden,`va_start` unspecified | | [CWG 2400](https://cplusplus.github.io/CWG/issues/2400.html) | C++11 | invoking a constexpr virtual function on an object not usablein constant expressions and whose lifetime began outside theexpression containing the invocation could be a constant expression | it is not aconstant expression | | [CWG 2418](https://cplusplus.github.io/CWG/issues/2418.html) | C++11 | it was unspecified which object or reference thatare not variables are usable in constant expressions | specified | | [CWG 2490](https://cplusplus.github.io/CWG/issues/2490.html) | C++20 | (pseudo) destructor calls lackedrestrictions in constant evaluation | restriction added | ### See also | | | | --- | --- | | [`constexpr` specifier](constexpr "cpp/language/constexpr")(C++11) | specifies that the value of a variable or function can be computed at compile time | | [is\_literal\_type](../types/is_literal_type "cpp/types/is literal type") (C++11)(deprecated in C++17)(removed in C++20) | checks if a type is a literal type (class template) | | [C documentation](https://en.cppreference.com/w/c/language/constant_expression "c/language/constant expression") for Constant expressions |
programming_docs
cpp Default arguments Default arguments ================= Allows a function to be called without providing one or more trailing arguments. Indicated by using the following syntax for a parameter in the parameter-list of a [function declaration](function "cpp/language/function"). | | | | | --- | --- | --- | | attr(optional) decl-specifier-seq declarator `=` initializer | (1) | | | attr(optional) decl-specifier-seq abstract-declarator(optional) `=` initializer | (2) | | Default arguments are used in place of the missing trailing arguments in a function call: ``` void point(int x = 3, int y = 4); point(1, 2); // calls point(1, 2) point(1); // calls point(1, 4) point(); // calls point(3, 4) ``` In a function declaration, after a parameter with a default argument, all subsequent parameters must: * have a default argument supplied in this or a previous declaration from the same scope: ``` int x(int = 1, int); // Error: only the trailing arguments can have default values // (assuming there's no previous declaration of x) void f(int n, int k = 1); void f(int n = 0, int k); // OK: k's default supplied by previous decl in the same scope void g(int, int = 7); void h() { void g(int = 1, int); // Error: not the same scope } ``` | | | | --- | --- | | * ...unless the parameter was expanded from a parameter pack: ``` template<class... T> struct C { void f(int n = 0, T...); }; C<int> c; // OK; instantiates declaration void C::f(int n = 0, int) ``` * or be a function parameter pack: ``` template<class... T> void h(int i = 0, T... args); // OK ``` | (since C++11) | The ellipsis is not a parameter, and so can follow a parameter with a default argument: ``` int g(int n = 0, ...); // OK ``` Default arguments are only allowed in the parameter lists of [function declarations](function "cpp/language/function") and [lambda-expressions](lambda "cpp/language/lambda"), (since C++11) and are not allowed in the declarations of pointers to functions, references to functions, or in [typedef](typedef "cpp/language/typedef") declarations. Template parameter lists use similar syntax for their [default template arguments](template_parameters#Default_template_arguments "cpp/language/template parameters"). For non-template functions, default arguments can be added to a function that was already declared if the function is redeclared in the same scope. At the point of a function call, the defaults are a union of the defaults provided in all visible declarations for the function. A redeclaration cannot introduce a default for an argument for which a default is already visible (even if the value is the same). A re-declaration in an inner scope does not acquire the default arguments from outer scopes. ``` void f(int, int); // #1 void f(int, int = 7); // #2 OK: adds a default void h() { f(3); // #1 and #2 are in scope; makes a call to f(3,7) void f(int = 1, int); // Error: inner scope declarations don't acquire defaults } void m() { // new scope begins void f(int, int); // inner scope declaration; has no defaults. f(4); // Error: not enough arguments to call f(int, int) void f(int, int = 6); f(4); // OK: calls f(4,6); void f(int, int = 6); // Error: cannot redeclare a default in the same scope } void f(int = 1, int); // #3 OK, adds a default to #2 void n() { // new scope begins f(); // #1, #2, and #3 are in scope: calls f(1, 7); } ``` If an [inline](inline "cpp/language/inline") function is declared in different translation units, the accumulated sets of default arguments must be the same at the end of each translation unit. | | | | --- | --- | | If a non-inline function is declared in the same namespace scope in different translation units, the corresponding default arguments must be the same if present (but some default arguments can be absent in some TU). | (since C++20) | If a [friend](friend "cpp/language/friend") declaration specifies a default, it must be a friend function definition, and no other declarations of this function are allowed in the translation unit. The [using-declaration](namespace#Using-declarations "cpp/language/namespace") carries over the set of known default arguments, and if more arguments are added later to the function's namespace, those defaults are also visible anywhere the using-declaration is visible: ``` namespace N { void f(int, int = 1); } using N::f; void g() { f(7); // calls f(7, 1); f(); // error } namespace N { void f(int = 2, int); } void h() { f(); // calls f(2, 1); } ``` The names used in the default arguments are looked up, checked for [accessibility](access "cpp/language/access"), and bound at the point of declaration, but are executed at the point of the function call: ``` int a = 1; int f(int); int g(int x = f(a)); // lookup for f finds ::f, lookup for a finds ::a // the value of ::a, which is 1 at this point, is not used void h() { a = 2; // changes the value of ::a { int a = 3; g(); // calls f(2), then calls g() with the result } } ``` For a [member function](member_functions "cpp/language/member functions") of a non-template class, the default arguments are allowed on the out-of-class definition, and are combined with the default arguments provided by the declaration inside the class body. If these out-of-class defaults would turn a member function into a default constructor or copy/move (since C++11) constructor/assignment operator, the program is ill-formed. For member functions of class templates, all defaults must be provided in the initial declaration of the member function. ``` class C { void f(int i = 3); void g(int i, int j = 99); C(int arg); // non-default constructor }; void C::f(int i = 3) {} // error: default argument already // specified in class scope void C::g(int i = 88, int j) {} // OK: in this translation unit, // C::g can be called with no argument C::C(int arg = 1) {} // Error: turns this into a default constructor ``` The overriders of [virtual](virtual "cpp/language/virtual") functions do not acquire the default arguments from the base class declarations, and when the virtual function call is made, the default arguments are decided based on the static type of the object (note: this can be avoided with [non-virtual interface](http://www.gotw.ca/publications/mill18.htm) pattern). ``` struct Base { virtual void f(int a = 7); }; struct Derived : Base { void f(int a) override; }; void m() { Derived d; Base& b = d; b.f(); // OK: calls Derived::f(7) d.f(); // Error: no default } ``` Local variables are not allowed in default arguments unless used in [unevaluated context](expressions#Unevaluated_expressions "cpp/language/expressions"): ``` void f() { int n = 1; extern void g(int x = n); // error: local variable cannot be a default extern void h(int x = sizeof n); // OK as of CWG 2082 } ``` The [this](this "cpp/language/this") pointer is not allowed in default arguments: ``` class A { void f(A* p = this) {} // error: this is not allowed }; ``` Non-static class members are not allowed in default arguments (even if they are not evaluated), except when used to form a pointer-to-member or in a member access expression: ``` int b; class X { int a; int mem1(int i = a); // error: non-static member cannot be used int mem2(int i = b); // OK: lookup finds X::b, the static member int mem3(int X::* i = &X::a); // OK: non-static member can be used int mem4(int i = x.a); // OK: in a member access expression static X x; static int b; }; ``` A default argument is evaluated each time the function is called with no argument for the corresponding parameter. Function parameters are not allowed in default arguments except if they are unevaluated. Note that parameters that appear earlier in the parameter list are in [scope](scope "cpp/language/scope"): ``` int a; int f(int a, int b = a); // Error: the parameter a used in a default argument int g(int a, int b = sizeof a); // Error until resolving CWG 2082 // OK after resolution: use in unevaluated context is OK ``` The default arguments are not part of the function type: ``` int f(int = 0); void h() { int j = f(1); int k = f(); // calls f(0); } int (*p1)(int) = &f; int (*p2)() = &f; // Error: the type of f is int(int) ``` Operator functions shall not have default arguments, except for the function call operator: ``` class C { int operator[](int i = 0); // ill-formed int operator()(int x = 0); // OK }; ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 217](https://cplusplus.github.io/CWG/issues/217.html) | C++98 | a default argument could be added to a non-template member function of a class template | prohibited | | [CWG 1344](https://cplusplus.github.io/CWG/issues/1344.html) | C++98 | default arguments added in the out-of-class definition of amember function could change it to a special member function | prohibited | | [CWG 1716](https://cplusplus.github.io/CWG/issues/1716.html) | C++98 | default arguments were evaluated each time the function is called,regardless of whether the caller have provided the arguments | only evaluated if noargument is provided for thecorresponding parameter | | [CWG 2082](https://cplusplus.github.io/CWG/issues/2082.html) | C++98 | default arguments were forbidden to use local variablesand preceding parameters in unevaluated context | unevaluated context use allowed | | [CWG 2233](https://cplusplus.github.io/CWG/issues/2233.html) | C++11 | parameters expanded from parameter packs couldnot appear after parameters with default arguments | allowed | cpp break statement break statement =============== Causes the enclosing [for](for "cpp/language/for"), [range-for](range-for "cpp/language/range-for"), [while](while "cpp/language/while") or [do-while](do "cpp/language/do") loop or [switch statement](switch "cpp/language/switch") to terminate. Used when it is otherwise awkward to terminate the loop using the condition expression and conditional statements. ### Syntax | | | | | --- | --- | --- | | attr(optional) `break` `;` | | | ### Explanation After this statement the control is transferred to the statement immediately following the enclosing loop or switch. As with any block exit, all automatic storage objects declared in enclosing compound statement or in the condition of a loop/switch are destroyed, in reverse order of construction, before the execution of the first line following the enclosing loop. ### Keywords [`break`](../keyword/break "cpp/keyword/break"). ### Notes A break statement cannot be used to break out of multiple nested loops. The [goto statement](goto "cpp/language/goto") may be used for this purpose. ### Example ``` #include <iostream> int main() { int i = 2; switch (i) { case 1: std::cout << "1"; //<---- maybe warning: fall through case 2: std::cout << "2"; //execution starts at this case label (+warning) case 3: std::cout << "3"; //<---- maybe warning: fall through case 4: //<---- maybe warning: fall through case 5: std::cout << "45"; // break; //execution of subsequent statements is terminated case 6: std::cout << "6"; } std::cout << '\n'; for (int j = 0; j < 2; j++) { for (int k = 0; k < 5; k++) { //only this loop is affected by break if (k == 2) break; // std::cout << j << k << ' '; // } } } ``` Possible output: ``` 2345 00 01 10 11 ``` ### See also | | | | --- | --- | | `[[[fallthrough](attributes/fallthrough "cpp/language/attributes/fallthrough")]]`(C++17) | indicates that the fall through from the previous case label is intentional and should not be diagnosed by a compiler that warns on fall-through | | [C documentation](https://en.cppreference.com/w/c/language/break "c/language/break") for `break` | cpp Escape sequences Escape sequences ================ Escape sequences are used to represent certain special characters within [string literals](string_literal "cpp/language/string literal") and [character literals](character_literal "cpp/language/character literal"). The following escape sequences are available: | Escape sequence | Description | Representation | | --- | --- | --- | | Simple escape sequences | | `\'` | single quote | byte `0x27` in ASCII encoding | | `\"` | double quote | byte `0x22` in ASCII encoding | | `\?` | question mark | byte `0x3f` in ASCII encoding | | `\\` | backslash | byte `0x5c` in ASCII encoding | | `\a` | audible bell | byte `0x07` in ASCII encoding | | `\b` | backspace | byte `0x08` in ASCII encoding | | `\f` | form feed - new page | byte `0x0c` in ASCII encoding | | `\n` | line feed - new line | byte `0x0a` in ASCII encoding | | `\r` | carriage return | byte `0x0d` in ASCII encoding | | `\t` | horizontal tab | byte `0x09` in ASCII encoding | | `\v` | vertical tab | byte `0x0b` in ASCII encoding | | Numeric escape sequences | | `\*nnn*` | arbitrary octal value | byte `*nnn*` | | `\x*nn*` | arbitrary hexadecimal value | byte `*nn*` | | Conditional escape sequences[[1]](#cite_note-1) | | `\*c*` | Implementation-defined | Implementation-defined | | Universal character names | | `\u*nnnn*` | arbitrary [Unicode](https://en.wikipedia.org/wiki/Unicode "enwiki:Unicode") value;may result in several code units | code point `U+*nnnn*` | | `\U*nnnnnnnn*` | arbitrary [Unicode](https://en.wikipedia.org/wiki/Unicode "enwiki:Unicode") value;may result in several code units | code point `U+*nnnnnnnn*` | 1. Conditional escape sequences are conditionally-supported. The character `*c*` in each conditional escape sequence is a member of [basic source character set](charset#Basic_source_character_set "cpp/language/charset") (until C++23)[basic character set](charset#Basic_character_set "cpp/language/charset") (since C++23) that is not the character following the `\` in any other escape sequence. ### Range of universal character names | | | | --- | --- | | If a universal character name corresponds to a code point that is not 0x24 (`$`), 0x40 (`@`), nor 0x60 (```) and less than 0xA0, the program is ill-formed. In other words, members of [basic source character set](charset#Basic_source_character_set "cpp/language/charset") and control characters (in ranges 0x0-0x1F and 0x7F-0x9F) cannot be expressed in universal character names. | (until C++11) | | If a universal character name corresponding to a code point of a member of [basic source character set](charset#Basic_source_character_set "cpp/language/charset") or control characters appear outside a [character](character_literal "cpp/language/character literal") or [string literal](string_literal "cpp/language/string literal"), the program is ill-formed. If a universal character name corresponds surrogate code point (the range 0xD800-0xDFFF, inclusive), the program is ill-formed. If a universal character name used in a UTF-16/32 string literal does not correspond to a code point in ISO/IEC 10646 (the range 0x0-0x10FFFF, inclusive), the program is ill-formed. | (since C++11)(until C++20) | | If a universal character name corresponding to a code point of a member of [basic source character set](charset#Basic_source_character_set "cpp/language/charset") or control characters appear outside a [character](character_literal "cpp/language/character literal") or [string literal](string_literal "cpp/language/string literal"), the program is ill-formed. If a universal character name does not correspond to a code point in ISO/IEC 10646 (the range 0x0-0x10FFFF, inclusive) or corresponds to a surrogate code point (the range 0xD800-0xDFFF, inclusive), the program is ill-formed. | (since C++20)(until C++23) | | If a universal character name corresponding to a scalar value of a character in the [basic character set](charset#Basic_character_set "cpp/language/charset") or a control character appear outside a [character](character_literal "cpp/language/character literal") or [string literal](string_literal "cpp/language/string literal"), the program is ill-formed. If a universal character name does not correspond to a scalar value of a character in the [translation character set](charset#Translation_character_set "cpp/language/charset"), the program is ill-formed. | (since C++23) | ### Notes `\0` is the most commonly used octal escape sequence, because it represents the terminating null character in [null-terminated strings](../string#Null-terminated_strings "cpp/string"). The new-line character `\n` has special meaning when used in [text mode I/O](../io/c "cpp/io/c"): it is converted to the OS-specific newline representation, usually a byte or byte sequence. Some systems mark their lines with length fields instead. Octal escape sequences have a limit of three octal digits, but terminate at the first character that is not a valid octal digit if encountered sooner. Hexadecimal escape sequences have no length limit and terminate at the first character that is not a valid hexadecimal digit. If the value represented by a single hexadecimal escape sequence does not fit the range of values represented by the character type used in this string literal (`char`, `char8_t` (since C++20), `char16_t`, `char32_t` (since C++11), or `wchar_t`), the result is unspecified. | | | | --- | --- | | A universal character name in a narrow string literal or a 16-bit string literal may map to more than one code unit, e.g. `\U0001f34c` is 4 `char` code units in UTF-8 (`\xF0\x9F\x8D\x8C`) and 2 `char16_t` code units in UTF-16 (`\xD83C\xDF4C`). | (since C++11) | The question mark escape sequence `\?` is used to prevent [trigraphs](operator_alternative "cpp/language/operator alternative") from being interpreted inside string literals: a string such as `"??/"` is compiled as `"\"`, but if the second question mark is escaped, as in `"?\?/"`, it becomes `"??/"`. As trigraphs have been removed from C++, the question mark escape sequence is no longer necessary. It is preserved for compatibility with C++14 (and former revisions) and C. (since C++17). ### Example ``` #include <iostream> int main() { std::cout << "This\nis\na\ntest\n\nShe said, \"Sells she seashells on the seashore?\"\n"; } ``` Output: ``` This is a test She said, "Sells she seashells on the seashore?" ``` ### Defect Reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 505](https://cplusplus.github.io/CWG/issues/505.html) | C++98 | the behavior was undefined if the character followinga backslash was not one of those specified in the table | made conditionally supported(semantic is implementation-defined) | ### See also * [ASCII chart](ascii "cpp/language/ascii") | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/escape "c/language/escape") for Escape sequence | cpp Punctuation Punctuation =========== These are the punctuation symbols in C++. The meaning of each symbol is detailed in the linked pages. ### `{` `}` * In a [class/struct](class "cpp/language/class") or [union](union "cpp/language/union") definition, delimit the [member specification](class#Member_specification "cpp/language/class"). * In a [enum](enum "cpp/language/enum") definition, delimit the enumerator list. * Delimit a [compound statement](statements#Compound_statements "cpp/language/statements"). The compound statement may be part of + a [function definition](function#Function_definition "cpp/language/function") + a [try block or catch clause](try_catch "cpp/language/try catch") + a [function-try-block](function-try-block "cpp/language/function-try-block") + a [lambda expression](lambda "cpp/language/lambda") (since C++11) * In [initialization](initialization "cpp/language/initialization"), delimit the initializers. This kind of initialization is called [list-initialization](list_initialization "cpp/language/list initialization"). (since C++11) * In a [namespace definition](namespace "cpp/language/namespace"), delimit the namespace body. * In a [language linkage specification](language_linkage "cpp/language/language linkage"), delimit the declarations. * In a [requires-expression](constraints#Requires_expressions "cpp/language/constraints"), delimit the requirements. (since C++20) * In a [compound requirement](constraints#Compound_Requirements "cpp/language/constraints"), delimit the expression. (since C++20) * In a [export declaration](modules "cpp/language/modules"), delimit the declarations. (since C++20) ### `[` `]` * [Subscript operator](operator_member_access#Built-in_subscript_operator "cpp/language/operator member access"); part of `operator[]` in [operator overloading](operators#Array_subscript_operator "cpp/language/operators"). * Part of [array declarator](declarations#Declarators "cpp/language/declarations") in a [declaration](declarations "cpp/language/declarations") or a [type-id](type#Type_naming "cpp/language/type") (e.g. in a [new expression](new "cpp/language/new")) * Part of `new[]` operator in [operator overloading (allocation function)](../memory/new/operator_new "cpp/memory/new/operator new"). * Part of `delete[]` operator in [delete expression](delete "cpp/language/delete") and [operator overloading (deallocation function)](../memory/new/operator_delete "cpp/memory/new/operator delete"). * In a [lambda expression](lambda "cpp/language/lambda"), delimit the [captures](lambda#Lambda_capture "cpp/language/lambda"). (since C++11) * In a [attribute specifier](attributes "cpp/language/attributes"), delimit the attributes. (since C++11) * In a [structured binding declaration](structured_binding "cpp/language/structured binding"), delimit the identifier list. (since C++17) ### `#` * Introduce a [preprocessing directive](../preprocessor "cpp/preprocessor"). * The [preprocessing operator for stringification](../preprocessor/replace#.23_and_.23.23_operators "cpp/preprocessor/replace"). ### `##` * The [preprocessing operator for token pasting](../preprocessor/replace#.23_and_.23.23_operators "cpp/preprocessor/replace"). ### `(` `)` * In a expression, [indicate grouping](expressions#Primary_expressions "cpp/language/expressions"). * [Function call operator](operator_other#Built-in_function_call_operator "cpp/language/operator other"); part of `operator()` in [operator overloading](operators#Function_call_operator "cpp/language/operators"). * In a [function-style type cast](explicit_cast "cpp/language/explicit cast"), delimit the expression/initializers. * In a [`static_cast`](static_cast "cpp/language/static cast"), [`const_cast`](const_cast "cpp/language/const cast"), [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast"), or [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast"), delimit the expression. * In a [`typeid`](typeid "cpp/language/typeid"), [`sizeof`](sizeof "cpp/language/sizeof"), [`sizeof...`](sizeof... "cpp/language/sizeof..."), [`alignof`](alignof "cpp/language/alignof"), or [`noexcept`](noexcept "cpp/language/noexcept") (since C++11) expression, delimit the operand. * In a [placement new expression](new "cpp/language/new"), delimit the placement arguments. * In a [new expression](new "cpp/language/new"), optionally delimit the type-id. * In a [new expression](new "cpp/language/new"), delimit the initializers. * In a [C-style cast](explicit_cast "cpp/language/explicit cast"), delimit the type-id. * In a [declaration](declarations "cpp/language/declarations") or a [type-id](type#Type_naming "cpp/language/type"), indicate grouping. * Delimit the parameter list in + a [function declarator](function "cpp/language/function") (in a [declaration](declarations "cpp/language/declarations") or a [type-id](type#Type_naming "cpp/language/type")) + a [lambda expression](lambda "cpp/language/lambda") (since C++11) + a [user-defined deduction guide](class_template_argument_deduction "cpp/language/class template argument deduction") (since C++17) + a [requires-expression](constraints#Requires_expressions "cpp/language/constraints") (since C++20) * In [direct-initialization](direct_initialization "cpp/language/direct initialization"), delimit the initializers. * In a [asm declaration](asm "cpp/language/asm"), delimit the string literal. * In a [member initializer list](initializer_list "cpp/language/initializer list"), delimit the initializers to a base or member. * In a [`if`](if "cpp/language/if") (including `constexpr` `if`) (since C++17), [`switch`](switch "cpp/language/switch"), [`while`](while "cpp/language/while"), [`do-while`](do "cpp/language/do"), or [`for`](for "cpp/language/for") (including [range-based `for`](range-for "cpp/language/range-for")) (since C++11) statement, delimit the controlling clause. * In a [catch clause](try_catch "cpp/language/try catch"), delimit the parameter declaration. * In a [function-like macro definition](../preprocessor/replace#Function-like_macros "cpp/preprocessor/replace"), delimit the macro parameters. * Part of a `defined`, `__has_include` (since C++17), `__has_cpp_attribute` (since C++20) preprocessing operator. * In a [`static_assert`](static_assert "cpp/language/static assert") declaration, delimit the operands. (since C++11) * In a [`decltype`](decltype "cpp/language/decltype") specifier, [`noexcept`](noexcept_spec "cpp/language/noexcept spec") specifier, [`alignas`](alignas "cpp/language/alignas") specifier, [conditional `explicit` specifier](explicit "cpp/language/explicit") (since C++20), delimit the operand. (since C++11) * In a [attribute](attributes "cpp/language/attributes"), delimit the attribute arguments. (since C++11) * Part of [`decltype(auto)`](decltype "cpp/language/decltype") specifier. (since C++14) * Delimit a [fold expression](fold "cpp/language/fold"). (since C++17) * Part of [`__VA_OPT__`](../preprocessor/replace "cpp/preprocessor/replace") replacement in a variadic macro definition. (since C++20) ### `;` * Indicate the end of + a [statement](statements "cpp/language/statements") (including the init-statement of a for statement) + a [declaration](declarations "cpp/language/declarations") or [member declaration](class#Member_specification "cpp/language/class") + a [module declaration](modules "cpp/language/modules"), import declaration, global module fragment introducer, or private module fragment introducer (since C++20) + a [requirement](constraints#Requires_expressions "cpp/language/constraints") (since C++20) * Separate the second and third clauses of a [for statement](for "cpp/language/for"). ### `:` * Part of [conditional operator](operator_other#Conditional_operator "cpp/language/operator other"). * Part of [label declaration](statements#Labels "cpp/language/statements"). * In the class-head of a [class definition](class "cpp/language/class"), introduce the [base-clause](derived_class "cpp/language/derived class"). * Part of [access specifier](access "cpp/language/access") in member specification. * In a [bit-field member declaration](bitfield "cpp/language/bitfield"), introduce the width. * In a [constructor](constructor "cpp/language/constructor") definition, introduce the member initializer list. * In a [range-based for](range-for "cpp/language/range-for") statement, separate the range-declaration and the range-initializer. (since C++11) * Introduce a [enum base](enum "cpp/language/enum"), which specifies the underlying type of the enum. (since C++11) * In a [attribute specifier](attributes "cpp/language/attributes"), separate the attribute-using-prefix and the attribute list. (since C++17) * In a [module declaration](modules "cpp/language/modules") or import declaration of module partition, introduce the module partition name. (since C++20) * Part of a private module fragment introducer (`module :private;`). (since C++20) ### `...` * In the [parameter list](function#Parameter_list "cpp/language/function") of a function declarator or lambda expression (since C++11) or user-defined deduction guide (since C++17), signify a [variadic function](variadic_arguments "cpp/language/variadic arguments"). * In a [catch-clause](try_catch "cpp/language/try catch"), signify catch-all handler. * In a [macro definition](../preprocessor/replace "cpp/preprocessor/replace"), signify a variadic macro. (since C++11) * Indicate [pack](parameter_pack "cpp/language/parameter pack") declaration and expansion. (since C++11) ### `?` * Part of [conditional operator](operator_other#Conditional_operator "cpp/language/operator other"). ### `::` * Scope resolution operator in + a [qualified name](qualified_lookup "cpp/language/qualified lookup") + a [pointer-to-member declaration](pointer#Pointers_to_members "cpp/language/pointer") + a [new](new "cpp/language/new") or [delete](delete "cpp/language/delete") expression, to indicate that only global allocation or deallocation functions are looked up * In a [attribute](attributes "cpp/language/attributes"), indicate attribute scope. (since C++11) * Part of [nested namespace definition](namespace "cpp/language/namespace"). (since C++17) ### `.` * [Member access operator](operator_member_access#Built-in_member_access_operators "cpp/language/operator member access"). * In [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization"), introduce a designator. (since C++20) * Part of [module name or module partition name](modules "cpp/language/modules"). (since C++20) ### `.*` * [Pointer-to-member access operator](operator_member_access#Built-in_pointer-to-member_access_operators "cpp/language/operator member access"). ### `->` * [Member access operator](operator_member_access#Built-in_member_access_operators "cpp/language/operator member access"); part of `operator->` in [operator overloading](operators "cpp/language/operators"). * In a [function declarator](function "cpp/language/function") or [lambda expression](lambda "cpp/language/lambda"), introduce the trailing return type. (since C++11) * In a [user-defined deduction guide](class_template_argument_deduction "cpp/language/class template argument deduction"), introduce the result type. (since C++17) * In a [compound requirement](constraints#Compound_Requirements "cpp/language/constraints"), introduce the return type requirement. (since C++20) ### `->*` * [Pointer-to-member access operator](operator_member_access#Built-in_pointer-to-member_access_operators "cpp/language/operator member access"); part of `operator->*` in [operator overloading](operators#Rarely_overloaded_operators "cpp/language/operators"). ### `~` * [Unary complement operator (a.k.a. bitwise not operator)](operator_arithmetic#Bitwise_logic_operators "cpp/language/operator arithmetic"); part of `operator~` in [operator overloading](operators "cpp/language/operators"). * Part of a id-expression to name a [destructor](destructor "cpp/language/destructor") or pseudo-destructor. ### `!` * [Logical not operator](operator_logical "cpp/language/operator logical"); part of `operator!` in [operator overloading](operators "cpp/language/operators"). * Part of [reversed variant of a consteval `if` statement](if#Consteval_if "cpp/language/if"). (since C++23) ### `+` * [Unary plus operator](operator_arithmetic#Unary_arithmetic_operators "cpp/language/operator arithmetic"); part of `operator+` in [operator overloading](operators "cpp/language/operators"). * [Binary plus operator](operator_arithmetic#Additive_operators "cpp/language/operator arithmetic"); part of `operator+` in [operator overloading](operators "cpp/language/operators"). ### `-` * [Unary minus operator](operator_arithmetic#Unary_arithmetic_operators "cpp/language/operator arithmetic"); part of `operator-` in [operator overloading](operators "cpp/language/operators"). * [Binary minus operator](operator_arithmetic#Additive_operators "cpp/language/operator arithmetic"); part of `operator-` in [operator overloading](operators "cpp/language/operators"). ### `*` * [Indirection operator](operator_member_access#Built-in_indirection_operator "cpp/language/operator member access"); part of `operator*` in [operator overloading](operators "cpp/language/operators"). * [Multiplication operator](operator_arithmetic#Multiplicative_operators "cpp/language/operator arithmetic"); part of `operator*` in [operator overloading](operators "cpp/language/operators"). * Pointer operator or part of pointer-to-member operator in a [declarator](declarations#Declarators "cpp/language/declarations") or in a [type-id](type#Type_naming "cpp/language/type"). * Part of `*this` in a [lambda capture](lambda#Lambda_capture "cpp/language/lambda") list, to capture the current object by copy. (since C++17) ### `/` * [Division operator](operator_arithmetic#Multiplicative_operators "cpp/language/operator arithmetic"); part of `operator/` in [operator overloading](operators "cpp/language/operators"). ### `%` * [Modulo operator](operator_arithmetic#Multiplicative_operators "cpp/language/operator arithmetic"); part of `operator%` in [operator overloading](operators "cpp/language/operators"). ### `^` * [Bitwise xor operator](operator_arithmetic#Bitwise_logic_operators "cpp/language/operator arithmetic"); part of `operator^` in [operator overloading](operators "cpp/language/operators"). ### `&` * [Address-of operator](operator_member_access#Built-in_address-of_operator "cpp/language/operator member access"); part of `operator&` in [operator overloading](operators#Rarely_overloaded_operators "cpp/language/operators"). * [Bitwise and operator](operator_arithmetic#Bitwise_logic_operators "cpp/language/operator arithmetic"); part of `operator&` in [operator overloading](operators "cpp/language/operators"). * Lvalue-reference operator in a [declarator](declarations#Declarators "cpp/language/declarations") or in a [type-id](type#Type_naming "cpp/language/type"). * In a [lambda capture](lambda#Lambda_capture "cpp/language/lambda"), indicate by-reference capture. (since C++11) * [Ref-qualifier](member_functions#ref-qualified_member_functions "cpp/language/member functions") in [member function declaration](member_functions "cpp/language/member functions"). (since C++11) ### `|` * [Bitwise or operator](operator_arithmetic#Bitwise_logic_operators "cpp/language/operator arithmetic"); part of `operator|` in [operator overloading](operators "cpp/language/operators"). ### `=` * [Simple assignment operator](operator_assignment "cpp/language/operator assignment"); part of `operator=` in [operator overloading](operators#Assignment_operator "cpp/language/operators"), which might be a special member function ([copy assignment operator](copy_assignment "cpp/language/copy assignment") or [move assignment operator](move_assignment "cpp/language/move assignment") (since C++11)). * In [initialization](initialization "cpp/language/initialization"), indicate [copy-initialization](copy_initialization "cpp/language/copy initialization") or [copy-list-initialization](list_initialization "cpp/language/list initialization") (since C++11). * In a [function declaration](function "cpp/language/function"), introduce a [default argument](default_arguments "cpp/language/default arguments"). * In a [template parameter list](template_parameters "cpp/language/template parameters"), introduce a [default template argument](template_parameters#Default_template_arguments "cpp/language/template parameters"). * In a [namespace alias definition](namespace_alias "cpp/language/namespace alias"), separate the alias and the aliased namespace. * In a [enum definition](enum "cpp/language/enum"), introduce the value of enumerator. * Part of pure-specifier in a [pure virtual function declaration](abstract_class "cpp/language/abstract class"). * Capture default in [lambda capture](lambda#Lambda_capture "cpp/language/lambda"), to indicate by-copy capture. (since C++11) * Part of defaulted definition (`=default;`) or deleted definition (`=delete;`) in [function definition](function#Function_definition "cpp/language/function"). (since C++11) * In a [type alias declaration](type_alias "cpp/language/type alias"), separate the alias and the aliased type. (since C++11) * In a [concept definition](constraints "cpp/language/constraints"), separate the concept name and the constraint expression. (since C++20) ### `+=` * [Compound assignment operator](operator_assignment "cpp/language/operator assignment"); part of `operator+=` in [operator overloading](operators "cpp/language/operators"). ### `-=` * [Compound assignment operator](operator_assignment "cpp/language/operator assignment"); part of `operator-=` in [operator overloading](operators "cpp/language/operators"). ### `*=` * [Compound assignment operator](operator_assignment "cpp/language/operator assignment"); part of `operator*=` in [operator overloading](operators "cpp/language/operators"). ### `/=` * [Compound assignment operator](operator_assignment "cpp/language/operator assignment"); part of `operator/=` in [operator overloading](operators "cpp/language/operators"). ### `%=` * [Compound assignment operator](operator_assignment "cpp/language/operator assignment"); part of `operator%=` in [operator overloading](operators "cpp/language/operators"). ### `^=` * [Compound assignment operator](operator_assignment "cpp/language/operator assignment"); part of `operator^=` in [operator overloading](operators "cpp/language/operators"). ### `&=` * [Compound assignment operator](operator_assignment "cpp/language/operator assignment"); part of `operator&=` in [operator overloading](operators "cpp/language/operators"). ### `|=` * [Compound assignment operator](operator_assignment "cpp/language/operator assignment"); part of `operator|=` in [operator overloading](operators "cpp/language/operators"). ### `==` * [Equality operator](operator_comparison "cpp/language/operator comparison"); part of `operator==` in [operator overloading](operators#Comparison_operators "cpp/language/operators"). ### `!=` * [Inequality operator](operator_comparison "cpp/language/operator comparison"); part of `operator!=` in [operator overloading](operators#Comparison_operators "cpp/language/operators"). ### `<` * [Less-than operator](operator_comparison "cpp/language/operator comparison"); part of `operator<` in [operator overloading](operators#Comparison_operators "cpp/language/operators"). * In a [`static_cast`](static_cast "cpp/language/static cast"), [`const_cast`](const_cast "cpp/language/const cast"), [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast"), or [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast"), introduce the type-id. * Introduce a [template argument list](template_parameters#Template_arguments "cpp/language/template parameters"). * Introduce a [template parameter list](template_parameters "cpp/language/template parameters") in + a [template declaration](templates "cpp/language/templates") + a [partial specialization](partial_specialization "cpp/language/partial specialization") + a [lambda expression](lambda "cpp/language/lambda") (since C++20) * Part of `template<>` in [template specialization declaration](template_specialization "cpp/language/template specialization"). * Introduce a header name in + a [`#include` directive](../preprocessor/include "cpp/preprocessor/include") + a [`__has_include` preprocessing expression](../preprocessor/include "cpp/preprocessor/include") (since C++17) + a [`import` declaration](modules "cpp/language/modules") (since C++20) ### `>` * [Greater-than operator](operator_comparison "cpp/language/operator comparison"); part of `operator>` in [operator overloading](operators#Comparison_operators "cpp/language/operators"). * [`static_cast`](static_cast "cpp/language/static cast"), [`const_cast`](const_cast "cpp/language/const cast"), [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast"), or [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast"), indicate the end of type-id. * Indicate the end of a [template argument list](template_parameters#Template_arguments "cpp/language/template parameters"). * Indicate the end of a [template parameter list](template_parameters "cpp/language/template parameters") in + a [template declaration](templates "cpp/language/templates") + a [partial specialization](partial_specialization "cpp/language/partial specialization") + a [lambda expression](lambda "cpp/language/lambda") (since C++20) * Part of `template<>` in [template specialization declaration](template_specialization "cpp/language/template specialization"). * Indicate the end of a header name in + a [`#include` directive](../preprocessor/include "cpp/preprocessor/include") + a [`__has_include` preprocessing expression](../preprocessor/include "cpp/preprocessor/include") (since C++17) + a [`import` declaration](modules "cpp/language/modules") (since C++20) ### `<=` * [Less-than-or-equal-to operator](operator_comparison "cpp/language/operator comparison"); part of `operator<=` in [operator overloading](operators#Comparison_operators "cpp/language/operators"). ### `>=` * [Greater-than-or-equal-to operator](operator_comparison "cpp/language/operator comparison"); part of `operator>=` in [operator overloading](operators#Comparison_operators "cpp/language/operators"). ### `<=>` (since C++20) * [Three-way comparison (spaceship) operator](operator_comparison#Three-way_comparison "cpp/language/operator comparison"); part of `operator<=>` in [operator overloading](operators#Comparison_operators "cpp/language/operators"). ### `&&` * [Logical and operator](operator_logical "cpp/language/operator logical"); part of `operator&&` in [operator overloading](operators#Rarely_overloaded_operators "cpp/language/operators"). * Rvalue-reference operator in a [declarator](declarations#Declarators "cpp/language/declarations") or in a [type-id](type#Type_naming "cpp/language/type"). (since C++11) * [Ref-qualifier](member_functions#ref-qualified_member_functions "cpp/language/member functions") in [member function declaration](member_functions "cpp/language/member functions"). (since C++11) ### `||` * [Logical or operator](operator_logical "cpp/language/operator logical"); part of `operator||` in [operator overloading](operators#Rarely_overloaded_operators "cpp/language/operators"). ### `<<` * [Bitwise shift operator](operator_arithmetic#Bitwise_shift_operators "cpp/language/operator arithmetic"); part of `operator<<` in operator overloading ([bitwise operator](operators#Bitwise_arithmetic_operators "cpp/language/operators") or [stream insertion operator](operators#Stream_extraction_and_insertion "cpp/language/operators")). ### `>>` * [Bitwise shift operator](operator_arithmetic#Bitwise_shift_operators "cpp/language/operator arithmetic"); part of `operator>>` in operator overloading ([bitwise operator](operators#Bitwise_arithmetic_operators "cpp/language/operators") or [stream extraction operator](operators#Stream_extraction_and_insertion "cpp/language/operators")). * Can be reparsed as two `>` in a [`static_cast`](static_cast "cpp/language/static cast"), [`const_cast`](const_cast "cpp/language/const cast"), [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast"), or [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast"), a [template argument list](template_parameters#Template_arguments "cpp/language/template parameters"), or a [template parameter list](template_parameters "cpp/language/template parameters"). (since C++11) ### `<<=` * [Compound assignment operator](operator_assignment "cpp/language/operator assignment"); part of `operator<<=` in [operator overloading](operators "cpp/language/operators"). ### `>>=` * [Compound assignment operator](operator_assignment "cpp/language/operator assignment"); part of `operator>>=` in [operator overloading](operators "cpp/language/operators"). ### `++` * [Increment operator](operator_incdec "cpp/language/operator incdec"); part of `operator++` in [operator overloading](operators "cpp/language/operators"). ### `--` * [Decrement operator](operator_incdec "cpp/language/operator incdec"); part of `operator--` in [operator overloading](operators "cpp/language/operators"). ### `,` * [Comma operator](operator_other#Built-in_comma_operator "cpp/language/operator other"); part of `operator,` in [operator overloading](operators#Rarely_overloaded_operators "cpp/language/operators"). * List separator in + the declarator list in a [declaration](declarations "cpp/language/declarations") + initializer list in [initialization](initialization "cpp/language/initialization") + the placement argument list in a [placement new](new "cpp/language/new") + the argument list in a [function call expression](operator_other#Function_call_operator "cpp/language/operator other") + the argument list in a [multi-argument subscript expression](operator_member_access#Built-in_subscript_operator "cpp/language/operator member access") (since C++23) + the enumerator list in a [enum](enum "cpp/language/enum") declaration + the [base class](derived_class "cpp/language/derived class") list in a [class](class "cpp/language/class") declaration + the member initializer list in a [constructor](constructor "cpp/language/constructor") definition + a [function parameter list](function#Parameter_list "cpp/language/function") + a [template parameter list](template_parameters "cpp/language/template parameters") + a [template argument list](template_parameters#Template_arguments "cpp/language/template parameters") + the macro parameter list in a [function-like macro definition](../preprocessor/replace "cpp/preprocessor/replace") + a [lambda capture](lambda#Lambda_capture "cpp/language/lambda") list (since C++11) + a [attribute](attributes "cpp/language/attributes") list (since C++11) + the declarator list in a [using-declaration](namespace#Using-declarations "cpp/language/namespace") (since C++17) + the identifier list in a [structured binding](structured_binding "cpp/language/structured binding") declaration (since C++17) * In a [`static_assert`](static_assert "cpp/language/static assert") declaration, separate the arguments. (since C++11) ### References * C++20 standard (ISO/IEC 14882:2020): + 5.12 Operators and punctuators [lex.operators] * C++17 standard (ISO/IEC 14882:2017): + 5.12 Operators and punctuators [lex.operators] * C++14 standard (ISO/IEC 14882:2014): + 2.13 Operators and punctuators [lex.operators] * C++11 standard (ISO/IEC 14882:2011): + 2.13 Operators and punctuators [lex.operators] * C++03 standard (ISO/IEC 14882:2003): + 2.12 Operators and punctuators [lex.operators] * C++98 standard (ISO/IEC 14882:1998): + 2.12 Operators and punctuators [lex.operators] ### See also | | | | --- | --- | | [Alternative representations](operator_alternative "cpp/language/operator alternative") | alternative spellings for certain operators | | [C documentation](https://en.cppreference.com/w/c/language/punctuators "c/language/punctuators") for Punctuation |
programming_docs
cpp Class template Class template ============== A class template defines a family of classes. ### Syntax | | | | | --- | --- | --- | | `template` `<` parameter-list `>` class-declaration | (1) | | | `export` `template` `<` parameter-list `>` class-declaration | (2) | (removed in C++11) | ### Explanation | | | | | --- | --- | --- | | class-declaration | - | a [class declaration](class "cpp/language/class"). The class name declared becomes a template name. | | parameter-list | - | a non-empty comma-separated list of the [template parameters](template_parameters "cpp/language/template parameters"), each of which is either a [non-type parameter](template_parameters#Non-type_template_parameter "cpp/language/template parameters"), a [type parameter](template_parameters#Type_template_parameter "cpp/language/template parameters"), a [template parameter](template_parameters#Template_template_parameter "cpp/language/template parameters"), or a [parameter pack](parameter_pack "cpp/language/parameter pack") of any of those. | | | | | --- | --- | | `export` was an optional modifier which declared the template as *exported* (when used with a class template, it declared all of its members exported as well). Files that instantiated exported templates did not need to include their definitions: the declaration was sufficient. Implementations of `export` were rare and disagreed with each other on details. | (until C++11) | ### Class template instantiation A class template by itself is not a type, or an object, or any other entity. No code is generated from a source file that contains only template definitions. In order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class (or function, from a function template). #### Explicit instantiation | | | | | --- | --- | --- | | `template` class-key template-name `<` argument-list `>` `;` | (1) | | | `extern` `template` class-key template-name `<` argument-list `>` `;` | (2) | (since C++11) | | | | | | --- | --- | --- | | class-key | - | `class`, `struct` or `union` | 1) Explicit instantiation definition 2) Explicit instantiation declaration An explicit instantiation definition forces instantiation of the class, struct, or union they refer to. It may appear in the program anywhere after the template definition, and for a given argument-list, is only allowed to appear once in the entire program, no diagnostic required. | | | | --- | --- | | An explicit instantiation declaration (an extern template) skips implicit instantiation step: the code that would otherwise cause an implicit instantiation instead uses the explicit instantiation definition provided elsewhere (resulting in link errors if no such instantiation exists). This can be used to reduce compilation times by explicitly declaring a template instantiation in all but one of the source files using it, and explicitly defining it in the remaining file. | (since C++11) | Classes, functions, variables, (since C++14) and member template specializations can be explicitly instantiated from their templates. Member functions, member classes, and static data members of class templates can be explicitly instantiated from their member definitions. Explicit instantiation can only appear in the enclosing namespace of the template, unless it uses qualified-id: ``` namespace N { template<class T> class Y // template definition { void mf() {} }; } // template class Y<int>; // error: class template Y not visible in the global namespace using N::Y; // template class Y<int>; // error: explicit instantiation outside // of the namespace of the template template class N::Y<char*>; // OK: explicit instantiation template void N::Y<double>::mf(); // OK: explicit instantiation ``` Explicit instantiation has no effect if an [explicit specialization](template_specialization "cpp/language/template specialization") appeared before for the same set of template arguments. Only the declaration is required to be visible when explicitly instantiating a function template, a variable template, (since C++14) a member function or static data member of a class template, or a member function template. The complete definition must appear before the explicit instantiation of a class template, a member class of a class template, or a member class template, unless an explicit specialization with the same template arguments appeared before. If a function template, variable template, (since C++14) member function template, or member function or static data member of a class template is explicitly instantiated with an explicit instantiation definition, the template definition must be present in the same translation unit. When an explicit instantiation names a class template specialization, it serves as an explicit instantiation of the same kind (declaration or definition) of each of its non-inherited non-template members that has not been previously explicitly specialized in the translation unit. If this explicit instantiation is a definition, it is also an explicit instantiation definition only for the members that have been defined at this point. Explicit instantiation definitions ignore member access specifiers: parameter types and return types may be private. #### Implicit instantiation When code refers to a template in context that requires a completely defined type, or when the completeness of the type affects the code, and this particular type has not been explicitly instantiated, implicit instantiation occurs. For example, when an object of this type is constructed, but not when a pointer to this type is constructed. This applies to the members of the class template: unless the member is used in the program, it is not instantiated, and does not require a definition. ``` template<class T> struct Z // template definition { void f() {} void g(); // never defined }; template struct Z<double>; // explicit instantiation of Z<double> Z<int> a; // implicit instantiation of Z<int> Z<char>* p; // nothing is instantiated here p->f(); // implicit instantiation of Z<char> and Z<char>::f() occurs here. // Z<char>::g() is never needed and never instantiated: // it does not have to be defined ``` If a class template has been declared, but not defined, at the point of instantiation, the instantiation yields an incomplete class type: ``` template<class T> class X; // declaration, not definition X<char> ch; // error: incomplete type X<char> ``` | | | | --- | --- | | [Local classes](class#Local_classes "cpp/language/class") and any templates used in their members are instantiated as part of the instantiation of the entity within which the local class or enumeration is declared. | (since C++17) | ### See also * [template parameters and arguments](template_parameters "cpp/language/template parameters") allow templates to be parameterized * [function template declaration](function_template "cpp/language/function template") declares a function template * [template specialization](template_specialization "cpp/language/template specialization") defines an existing template for a specific type * [parameter packs](parameter_pack "cpp/language/parameter pack") allows the use of lists of types in templates (since C++11) cpp if statement if statement ============ Conditionally executes another statement. Used where code needs to be executed based on a run-time or compile-time (since C++17) condition, or whether the if statement is evaluated in a manifestly constant-evaluated context (since C++23). ### Syntax | | | | | --- | --- | --- | | attr(optional) `if` `constexpr`(optional) `(` init-statement(optional) condition `)` statement-true | (1) | | | attr(optional) `if` `constexpr`(optional) `(` init-statement(optional) condition `)` statement-true `else` statement-false | (2) | | | attr(optional) `if` `!`(optional) `consteval` compound-statement | (3) | (since C++23) | | attr(optional) `if` `!`(optional) `consteval` compound-statement `else` statement | (4) | (since C++23) | 1) *if statement* without an else branch 2) *if statement* with an else branch 3) *consteval if statement* without an else branch 4) *consteval if statement* with an else branch | | | | | --- | --- | --- | | attr | - | (since C++11) any number of [attributes](attributes "cpp/language/attributes") | | `constexpr` | - | (since C++17) if present, the statement becomes a *constexpr if statement* | | init-statement | - | (since C++17) either * an [expression statement](statements "cpp/language/statements") (which may be a *null statement* "`;`") * a [simple declaration](declarations "cpp/language/declarations"), typically a declaration of a variable with initializer, but it may declare arbitrary many variables or be a [structured binding](structured_binding "cpp/language/structured binding") declaration | | | | --- | --- | | * an [alias declaration](type_alias "cpp/language/type alias") | (since C++23) | Note that any init-statement must end with a semicolon `;`, which is why it is often described informally as an expression or a declaration followed by a semicolon. | | condition | - | one of * [expression](expressions "cpp/language/expressions") which is [contextually convertible](implicit_conversion#Contextual_conversions "cpp/language/implicit conversion") to `bool` * [declaration](declarations "cpp/language/declarations") of a single non-array variable with a brace-or-equals [initializer](initialization "cpp/language/initialization"). | | statement-true | - | any [statement](statements "cpp/language/statements") (often a compound statement), which is executed if condition evaluates to `true` | | statement-false | - | any [statement](statements "cpp/language/statements") (often a compound statement), which is executed if condition evaluates to `false` | | compound-statement | - | any [compound statement](statements#Compound_statements "cpp/language/statements"), which is executed if the if-statement * is evaluated in a [manifestly constant-evaluated context](constant_expression#Manifestly_constant-evaluated_expressions "cpp/language/constant expression"), if `!` is not preceding `consteval` * is not evaluated in a manifestly constant-evaluated context, if `!` is preceding `consteval` | | statement | - | any [statement](statements "cpp/language/statements") (must be a compound statement, see [below](if#Constexpr_if "cpp/language/if")), which is executed if the if-statement * is not evaluated in a [manifestly constant-evaluated context](constant_expression#Manifestly_constant-evaluated_expressions "cpp/language/constant expression"), if `!` is not preceding `consteval` * is evaluated in a manifestly constant-evaluated context, if `!` is preceding `consteval` | ### Explanation If the condition yields `true` after conversion to `bool`, statement-true is executed. If the else part of the if statement is present and condition yields `false` after conversion to `bool`, statement-false is executed. In the second form of if statement (the one including else), if statement-true is also an if statement then that inner if statement must contain an else part as well (in other words, in nested if-statements, the else is associated with the closest if that doesn't have an else). ``` #include <iostream> int main() { // simple if-statement with an else clause int i = 2; if (i > 2) std::cout << i << " is greater than 2\n"; else std::cout << i << " is not greater than 2\n"; // nested if-statement int j = 1; if (i > 1) if (j > 2) std::cout << i << " > 1 and " << j << " > 2\n"; else // this else is part of if (j > 2), not of if (i > 1) std::cout << i << " > 1 and " << j << " <= 2\n"; // declarations can be used as conditions with dynamic_cast struct Base { virtual ~Base() {} }; struct Derived : Base { void df() { std::cout << "df()\n"; } }; Base* bp1 = new Base; Base* bp2 = new Derived; if (Derived* p = dynamic_cast<Derived*>(bp1)) // cast fails, returns nullptr p->df(); // not executed if (auto p = dynamic_cast<Derived*>(bp2)) // cast succeeds p->df(); // executed } ``` Output: ``` 2 is not greater than 2 2 > 1 and 1 <= 2 df() ``` | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | If statements with initializer If init-statement is used, the if statement is equivalent to. | | | | | --- | --- | --- | | `{` init\_statement attr(optional) `if` `constexpr`(optional) `(` condition `)` statement-true `}` | | | or. | | | | | --- | --- | --- | | `{` init\_statement attr(optional) `if` `constexpr`(optional) `(` condition `)` statement-true `else` statement-false `}` | | | Except that names declared by the init-statement (if init-statement is a declaration) and names declared by condition (if condition is a declaration) are in the same scope, which is also the scope of both statements. ``` std::map<int, std::string> m; std::mutex mx; extern bool shared_flag; // guarded by mx int demo() { if (auto it = m.find(10); it != m.end()) { return it->second.size(); } if (char buf[10]; std::fgets(buf, 10, stdin)) { m[0] += buf; } if (std::lock_guard lock(mx); shared_flag) { unsafe_ping(); shared_flag = false; } if (int s; int count = ReadBytesWithSignal(&s)) { publish(count); raise(s); } if (const auto keywords = {"if", "for", "while"}; std::ranges::any_of(keywords, [&tok](const char* kw) { return tok == kw; })) { std::cerr << "Token must not be a keyword\n"; } } ``` | (since C++17) | | | | | --- | --- | | Constexpr if The statement that begins with `if constexpr` is known as the *constexpr if statement*. In a constexpr if statement, the value of condition must be a [contextually converted constant expression of type `bool`](constant_expression#Converted_constant_expression "cpp/language/constant expression") (until C++23)an expression [contextually converted to `bool`](implicit_conversion#Contextual_conversions "cpp/language/implicit conversion"), where the conversion is a [constant expression](constant_expression "cpp/language/constant expression") (since C++23). If the value is `true`, then statement-false is discarded (if present), otherwise, statement-true is discarded. The return statements in a discarded statement do not participate in function return type deduction: ``` template<typename T> auto get_value(T t) { if constexpr (std::is_pointer_v<T>) return *t; // deduces return type to int for T = int* else return t; // deduces return type to int for T = int } ``` The discarded statement can [odr-use](definition#One_Definition_Rule "cpp/language/definition") a variable that is not defined. ``` extern int x; // no definition of x required int f() { if constexpr (true) return 0; else if (x) return x; else return -x; } ``` Outside a template, a discarded statement is fully checked. `if constexpr` is not a substitute for the [`#if`](../preprocessor/conditional "cpp/preprocessor/conditional") preprocessing directive: ``` void f() { if constexpr(false) { int i = 0; int *p = i; // Error even though in discarded statement } } ``` If a constexpr if statement appears inside a [templated entity](templates#Templated_entity "cpp/language/templates"), and if condition is not [value-dependent](dependent_name#Value-dependent_expressions "cpp/language/dependent name") after instantiation, the discarded statement is not instantiated when the enclosing template is instantiated . ``` template<typename T, typename ... Rest> void g(T&& p, Rest&& ...rs) { // ... handle p if constexpr (sizeof...(rs) > 0) g(rs...); // never instantiated with an empty argument list. } ``` Note: an example where the condition remains value-dependent after instantiation is a nested template, e.g. ``` template<class T> void g() { auto lm = [](auto p) { if constexpr (sizeof(T) == 1 && sizeof p == 1) { // this condition remains value-dependent after instantiation of g<T> } }; } ``` Note: the discarded statement can't be ill-formed for every possible specialization: ``` template<typename T> void f() { if constexpr (std::is_arithmetic_v<T>) // ... else static_assert(false, "Must be arithmetic"); // ill-formed: invalid for every T } ``` The common workaround for such a catch-all statement is a type-dependent expression that is always false: ``` template<class> inline constexpr bool dependent_false_v = false; template<typename T> void f() { if constexpr (std::is_arithmetic_v<T>) // ... else static_assert(dependent_false_v<T>, "Must be arithmetic"); // ok } ``` Labels ([goto targets](goto "cpp/language/goto"), `case` labels, and `default:`) appearing in a substatement of a constexpr if can only be referenced (by [`switch`](switch "cpp/language/switch") or [`goto`](goto "cpp/language/goto")) in the same substatement. Note: a [typedef declaration](typedef "cpp/language/typedef") or [alias declaration](type_alias "cpp/language/type alias") (since C++23) can be used as the init-statement of a constexpr if statement to reduce the scope of the type alias. | (since C++17) | | | | | --- | --- | | Consteval if The statement that begins with `if consteval` is known as the *consteval if statement*. In a consteval if statement, both compound-statement and statement (if any) must be compound statements. If statement is not a compound statement, it will still be treated as a part of the consteval if statement (and thus results in a compilation error): ``` constexpr void f(bool b) { if (true) if consteval {} else ; // error: not a compound-statement // else not associated with outer if } ``` If a consteval if statement is evaluated in a [manifestly constant-evaluated context](constant_expression#Manifestly_constant-evaluated_expressions "cpp/language/constant expression"), compound-statement is executed. Otherwise, statement is executed if it is present. A `case` or `default` label appearing within a consteval if statement shall be associated with a [`switch`](switch "cpp/language/switch") statement within the same if statement. A [label](goto "cpp/language/goto") declared in a substatement of a consteval if statement shall only be referred to by a statement in the same substatement. If the statement begins with `if !consteval`, the compound-statement and statement (if any) must be both compound statements. Such statement is not considered as consteval if statement, but is equivalent to a consteval if statement:* `if !consteval {/*stmt*/}` is equivalent to `if consteval {} else {/*stmt*/}`. * `if !consteval {/*stmt-1*/} else {/*stmt-2*/}` is equivalent to `if consteval {/*stmt-2*/} else {/*stmt-1*/}`. compound-statement in a consteval if statement (or statement in the negative form) is in an [immediate function context](consteval "cpp/language/consteval"), in which a call to an immediate function needs not to be a constant expression. ``` #include <cmath> #include <cstdint> #include <cstring> #include <iostream> constexpr bool is_constant_evaluated() noexcept { if consteval { return true; } else { return false; } } constexpr bool is_runtime_evaluated() noexcept { if not consteval { return true; } else { return false; } } consteval std::uint64_t ipow_ct(std::uint64_t base, std::uint8_t exp) { if (!base) return base; std::uint64_t res{1}; while (exp) { if (exp & 1) res *= base; exp /= 2; base *= base; } return res; } constexpr std::uint64_t ipow(std::uint64_t base, std::uint8_t exp) { if consteval // use a compile-time friendly algorithm { return ipow_ct(base, exp); } else // use runtime evaluation { return std::pow(base, exp); } } int main(int, const char* argv[]) { static_assert(ipow(0,10) == 0 && ipow(2,10) == 1024); std::cout << ipow(std::strlen(argv[0]), 3) << '\n'; } ``` | (since C++23) | ### Notes If statement-true or statement-false is not a compound statement, it is treated as if it were: ``` if (x) int i; // i is no longer in scope ``` is the same as. ``` if (x) { int i; } // i is no longer in scope ``` The scope of the name introduced by condition, if it is a declaration, is the combined scope of both statements' bodies: ``` if (int x = f()) { int x; // error: redeclaration of x } else { int x; // error: redeclaration of x } ``` If statement-true is entered by [`goto`](goto "cpp/language/goto") or `longjmp`, condition is not evaluated and statement-false is not executed. | | | | --- | --- | | Built-in conversions are not allowed in the condition of a constexpr if statment, except for non-[narrowing](list_initialization#Narrowing_conversions "cpp/language/list initialization") [integral conversions](implicit_conversion#Integral_conversions "cpp/language/implicit conversion") to `bool`. | (since C++17)(until C++23) | | | | | --- | --- | | [`switch`](switch "cpp/language/switch") and [`goto`](goto "cpp/language/goto") are not allowed to jump into a branch of constexpr if statement or a consteval if statement (since C++23). | (since C++17) | ### Keywords [`if`](../keyword/if "cpp/keyword/if"), [`else`](../keyword/else "cpp/keyword/else"), [`constexpr`](../keyword/constexpr "cpp/keyword/constexpr"), [`consteval`](../keyword/consteval "cpp/keyword/consteval"). ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 631](https://cplusplus.github.io/CWG/issues/631.html) | C++98 | the control flow was unspecified if thefirst substatement is reached via a label | the condition is not evaluated and the secondsubstatement is not executed (same as in C) | ### See also | | | | --- | --- | | [is\_constant\_evaluated](../types/is_constant_evaluated "cpp/types/is constant evaluated") (C++20) | detects whether the call occurs within a constant-evaluated context (function) | | [C documentation](https://en.cppreference.com/w/c/language/if "c/language/if") for `if` statement |
programming_docs
cpp Address of an overloaded function Address of an overloaded function ================================= Besides [function-call expressions](operator_other "cpp/language/operator other"), where [overload resolution](overload_resolution "cpp/language/overload resolution") takes place, the name of an overloaded function may appear in the following 7 contexts: | # | Context | Target | | --- | --- | --- | | 1 | [initializer](initialization "cpp/language/initialization") in a [declaration](declarations "cpp/language/declarations") of an object or [reference](reference_initialization "cpp/language/reference initialization") | the object or reference being initialized | | 2 | on the right-hand-side of an assignment expression | the left-hand side of the assignment | | 3 | as a function call argument | the function parameter | | 4 | as a user-defined operator argument | the operator parameter | | 5 | the [`return`](return "cpp/language/return") statement | the return type of a function | | 6 | [explicit cast](explicit_cast "cpp/language/explicit cast") or [`static_cast`](static_cast "cpp/language/static cast") argument | the target type of a cast | | 7 | non-type [template argument](template_parameters "cpp/language/template parameters") | the type of the template parameter | In each context, the name of an overloaded function may be preceded by address-of operator `&` and may be enclosed in a redundant set of parentheses. In all these contexts, the function selected from the overload set is the function whose type matches the pointer to function, reference to function, or pointer to member function type that is expected by *target*. The parameter types and the return type of the function must match the target exactly, no implicit conversions are considered (e.g. a function returning a pointer to derived won't get selected when initializing a pointer to function returning a pointer to base). If the function name names a function template, then, first, [template argument deduction](template_argument_deduction "cpp/language/template argument deduction") is done, and if it succeeds, it produces a single template specialization which is added to the set of overloads to consider. All functions whose associated [constraints](constraints "cpp/language/constraints") are not satisfied are dropped from the set. (since C++20) If more than one function from the set matches the target, and at least one function is non-template, the template specializations are eliminated from consideration. For any pair of non-template functions where one is [more constrained](constraints "cpp/language/constraints") than another, the less constrained function is dropped from the set (since C++20). If all remaining candidates are template specializations, [less specialized](partial_specialization "cpp/language/partial specialization") ones are removed if more specialized are available. If more than one candidate remains after the removals, the program is ill-formed. ### Example ``` int f(int) { return 1; } int f(double) { return 2; } void g( int(&f1)(int), int(*f2)(double) ) {} template< int(*F)(int) > struct Templ {}; struct Foo { int mf(int) { return 3; } int mf(double) { return 4; } }; struct Emp { void operator<<(int (*)(double)) {} }; int main() { // 1. initialization int (*pf)(double) = f; // selects int f(double) int (&rf)(int) = f; // selects int f(int) int (Foo::*mpf)(int) = &Foo::mf; // selects int mf(int) // 2. assignment pf = nullptr; pf = &f; // selects int f(double) // 3. function argument g(f, f); // selects int f(int) for the 1st argument // and int f(double) for the second // 4. user-defined operator Emp{} << f; //selects int f(double) // 5. return value auto foo = []() -> int (*)(int) { return f; // selects int f(int) }; // 6. cast auto p = static_cast<int(*)(int)>(f); // selects int f(int) // 7. template argument Templ<f> t; // selects int f(int) } ``` ### References * C++20 standard (ISO/IEC 14882:2020): + 12.5 Address of overloaded function [over.over] * C++17 standard (ISO/IEC 14882:2017): + 16.4 Address of overloaded function [over.over] * C++14 standard (ISO/IEC 14882:2014): + 13.4 Address of overloaded function [over.over] * C++11 standard (ISO/IEC 14882:2011): + 13.4 Address of overloaded function [over.over] * C++98 standard (ISO/IEC 14882:1998): + 13.4 Address of overloaded function [over.over] cpp Copy elision Copy elision ============ Omits copy and move (since C++11) constructors, resulting in zero-copy pass-by-value semantics. ### Explanation | | | | --- | --- | | Mandatory elision of copy/move operations Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:* In a [return statement](return "cpp/language/return"), when the operand is a [prvalue](value_category "cpp/language/value category") of the same class type (ignoring [cv-qualification](cv "cpp/language/cv")) as the function return type: ``` T f() { return T(); } f(); // only one call to default constructor of T ``` The destructor of the type returned must be accessible at the point of the return statement and non-deleted, even though no T object is destroyed. * In the initialization of an object, when the initializer expression is a [prvalue](value_category "cpp/language/value category") of the same class type (ignoring [cv-qualification](cv "cpp/language/cv")) as the variable type: ``` T x = T(T(f())); // only one call to default constructor of T, to initialize x ``` This can only apply when the object being initialized is known not to be a potentially-overlapping subobject: ``` struct C { /* ... */ }; C f(); struct D; D g(); struct D : C { D() : C(f()) {} // no elision when initializing a base-class subobject D(int) : D(g()) {} // no elision because the D object being initialized might // be a base-class subobject of some other class }; ``` Note: the rule above does not specify an optimization: C++17 core language specification of [prvalues](value_category "cpp/language/value category") and [temporaries](implicit_conversion#Temporary_materialization "cpp/language/implicit conversion") is fundamentally different from that of the earlier C++ revisions: there is no longer a temporary to copy/move from. Another way to describe C++17 mechanics is "unmaterialized value passing": prvalues are returned and used without ever materializing a temporary. | (since C++17) | #### Non-mandatory elision of copy/move (since C++11) operations Under the following circumstances, the compilers are permitted, but not required to omit the copy and move (since C++11) construction of class objects even if the copy/move (since C++11) constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. This is an optimization: even when it takes place and the copy/move (since C++11) constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed: * In a [return statement](return "cpp/language/return"), when the operand is the name of a non-volatile object with automatic storage duration, which isn't a function parameter or a catch clause parameter, and which is of the same class type (ignoring [cv-qualification](cv "cpp/language/cv")) as the function return type. This variant of copy elision is known as NRVO, "named return value optimization". | | | | --- | --- | | * In the initialization of an object, when the source object is a nameless temporary and is of the same class type (ignoring [cv-qualification](cv "cpp/language/cv")) as the target object. When the nameless temporary is the operand of a return statement, this variant of copy elision is known as RVO, "return value optimization". | (until C++17) | | Return value optimization is mandatory and no longer considered as copy elision; see above. | (since C++17) | | | | | --- | --- | | * In a [throw-expression](throw "cpp/language/throw"), when the operand is the name of a non-volatile object with automatic storage duration, which isn't a function parameter or a catch clause parameter, and whose scope does not extend past the innermost try-block (if there is a try-block). * In a [catch clause](try_catch "cpp/language/try catch"), when the argument is of the same type (ignoring [cv-qualification](cv "cpp/language/cv")) as the exception object thrown, the copy of the exception object is omitted and the body of the catch clause accesses the exception object directly, as if caught by reference (there cannot be a move from the exception object because it is always an lvalue). This is disabled if such copy elision would change the observable behavior of the program for any reason other than skipping the copy constructor and the destructor of the catch clause argument (for example, if the catch clause argument is modified, and the exception object is rethrown with `throw`). | (since C++11) | | * In [coroutines](coroutines "cpp/language/coroutines"), copy/move of the parameter into coroutine state may be elided where this does not change the behavior of the program other than by omitting the calls to the parameter's constructor and destructor. This can take place if the parameter is never referenced after a suspension point or when the entire coroutine state was never heap-allocated in the first place. | (since C++20) | When copy elision occurs, the implementation treats the source and target of the omitted copy/move (since C++11) operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization (except that, if the parameter of the selected constructor is an rvalue reference to object type, the destruction occurs when the target would have been destroyed) (since C++11). Multiple copy elisions may be chained to eliminate multiple copies. | | | | --- | --- | | * In [constant expression](constant_expression "cpp/language/constant expression") and [constant initialization](constant_initialization "cpp/language/constant initialization"), return value optimization (RVO) is guaranteed, however, named return value optimization (NRVO) is forbidden: ``` struct A { void *p; constexpr A(): p(this) {} }; constexpr A g() { A a; return a; } constexpr A a; // a.p points to a // constexpr A b = g(); // error: b.p would be dangling and would point to a temporary // with automatic storage duration void h() { A c = g(); // c.p may point to c or to an ephemeral temporary } extern const A d; constexpr A f() { A e; if (&e == &d) return A(); else return e; // mandating NRVO in constant evaluation contexts would result in contradiction // that NRVO is performed if and only if it's not performed } // constexpr A d = f(); // error: d.p would be dangling ``` | (since C++11) | ### Notes Copy elision is the only allowed form of optimization (until C++14)one of the two allowed forms of optimization, alongside [allocation elision and extension](new#Allocation "cpp/language/new"), (since C++14) that can change the observable side-effects. Because some compilers do not perform copy elision in every situation where it is allowed (e.g., in debug mode), programs that rely on the side-effects of copy/move constructors and destructors are not portable. | | | | --- | --- | | In a return statement or a throw-expression, if the compiler cannot perform copy elision but the conditions for copy elision are met or would be met, except that the source is a function parameter, the compiler will attempt to use the move constructor even if the object is designated by an lvalue; see [return statement](return#Notes "cpp/language/return") for details. | (since C++11) | ### Example ``` #include <iostream> struct Noisy { Noisy() { std::cout << "constructed at " << this << '\n'; } Noisy(const Noisy&) { std::cout << "copy-constructed\n"; } Noisy(Noisy&&) { std::cout << "move-constructed\n"; } ~Noisy() { std::cout << "destructed at " << this << '\n'; } }; Noisy f() { Noisy v = Noisy(); // copy elision when initializing v // from a temporary (until C++17) / prvalue (since C++17) return v; // NRVO from v to the result object (not guaranteed, even in C++17) } // if optimization is disabled, the move constructor is called void g(Noisy arg) { std::cout << "&arg = " << &arg << '\n'; } int main() { Noisy v = f(); // copy elision in initialization of v // from the temporary returned by f() (until C++17) // from the prvalue f() (since C++17) std::cout << "&v = " << &v << '\n'; g(f()); // copy elision in initialization of the parameter of g() // from the temporary returned by f() (until C++17) // from the prvalue f() (since C++17) } ``` Possible output: ``` constructed at 0x7fffd635fd4e &v = 0x7fffd635fd4e constructed at 0x7fffd635fd4f &arg = 0x7fffd635fd4f destructed at 0x7fffd635fd4f destructed at 0x7fffd635fd4e ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1967](https://cplusplus.github.io/CWG/issues/1967.html) | C++11 | when copy elision is done using a move constructor, thelifetime of the moved-from object was still considered | not considered | | [CWG 2022](https://cplusplus.github.io/CWG/issues/2022.html) | C++11 | copy elision was optional in constant expressions | copy elision mandatory | | [CWG 2278](https://cplusplus.github.io/CWG/issues/2278.html) | C++11 | NRVO was mandatory in constant expressions | forbid NRVO in constant expressions | | [CWG 2426](https://cplusplus.github.io/CWG/issues/2426.html) | C++17 | destructor not required when returning a prvalue | destructor is potentially invoked | ### See also * [copy initialization](copy_initialization "cpp/language/copy initialization") * [copy constructor](copy_constructor "cpp/language/copy constructor") * [move constructor](move_constructor "cpp/language/move constructor") cpp delete expression delete expression ================= Destroys object(s) previously allocated by the [new expression](new "cpp/language/new") and releases obtained memory area. ### Syntax | | | | | --- | --- | --- | | `::`(optional) `delete` expression | (1) | | | `::`(optional) `delete []` expression | (2) | | 1) Destroys one non-array object created by a [new-expression](new "cpp/language/new") 2) Destroys an array created by a [new[]-expression](new "cpp/language/new") ### Explanation For the first (non-array) form, expression must be a pointer to an object type or a class type [contextually implicitly convertible](implicit_conversion "cpp/language/implicit conversion") to such pointer, and its value must be either *null* or pointer to a non-array object created by a [new-expression](new "cpp/language/new"), or a pointer to a base subobject of a non-array object created by a [new-expression](new "cpp/language/new"). The pointed-to type of expression must be [*similar*](reinterpret_cast#Type_aliasing "cpp/language/reinterpret cast") to the type of the object (or of a base subobject). If expression is anything else, including if it is a pointer obtained by the array form of [new-expression](new "cpp/language/new"), the behavior is [undefined](ub "cpp/language/ub"). For the second (array) form, expression must be a null pointer value or a pointer value previously obtained by an array form of [new-expression](new "cpp/language/new"). The pointed-to type of expression must be [*similar*](reinterpret_cast#Type_aliasing "cpp/language/reinterpret cast") to the element type of the array object. If expression is anything else, including if it's a pointer obtained by the non-array form of [new-expression](new "cpp/language/new"), the behavior is [undefined](ub "cpp/language/ub"). The result of the expression always has type `void`. If the object being deleted has incomplete class type at the point of deletion, and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined. If expression is not a null pointer and the [deallocation function](../memory/new/operator_delete "cpp/memory/new/operator delete") is not a destroying delete (since C++20), the `delete` expression invokes the [destructor](destructor "cpp/language/destructor") (if any) for the object that's being destroyed, or for every element of the array being destroyed (proceeding from the last element to the first element of the array). After that, whether or not an exception was thrown by any destructor, the delete expression invokes the [deallocation function](../memory/new/operator_delete "cpp/memory/new/operator delete"): either `[operator delete](http://en.cppreference.com/w/cpp/memory/new/operator_delete)` (for the first version of the expression) or `[operator delete](http://en.cppreference.com/w/cpp/memory/new/operator_delete)[]` (for the second version of the expression), unless the matching new-expression was combined with another new-expression (since C++14). The deallocation function's name is [looked up](lookup "cpp/language/lookup") in the scope of the dynamic type of the object pointed to by expression, which means class-specific deallocation functions, if present, are found before the global ones. If `::` is present in the `delete` expression, only the global namespace is examined by this lookup. In any case, any declarations other than of usual deallocation functions are discarded. If lookup finds more than one deallocation function, the function to be called is selected as follows (see [deallocation function](../memory/new/operator_delete "cpp/memory/new/operator delete") for a more detailed description of these functions and their effects): | | | | --- | --- | | * If at least one of the deallocation functions is a destroying delete, all non-destroying deletes are ignored. | (since C++20) | | * If the type's alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__`, alignment-aware deallocation functions (with a parameter of type `[std::align\_val\_t](../memory/new/align_val_t "cpp/memory/new/align val t")`) are preferred. For other types, the alignment-unaware deallocation functions (without a parameter of type `[std::align\_val\_t](../memory/new/align_val_t "cpp/memory/new/align val t")`) are preferred. + If more than one preferred functions are found, only preferred functions are considered in the next step. + If no preferred functions are found, the non-preferred ones are considered in the next step. * If only one function is left, that function is selected. | (since C++17) | * If the deallocation functions that were found are class-specific, size-unaware class-specific deallocation function (without a parameter of type `[std::size\_t](../types/size_t "cpp/types/size t")`) is preferred over size-aware class-specific deallocation function (with a parameter of type `[std::size\_t](../types/size_t "cpp/types/size t")`) | | | | --- | --- | | * Otherwise, lookup reached global scope, and: + If the type is complete and if, for the array form only, the operand is a pointer to a class type with a non-trivial destructor or a (possibly multi-dimensional) array thereof, the global size-aware global function (with a parameter of type `[std::size\_t](../types/size_t "cpp/types/size t")`) is selected + Otherwise, it is unspecified whether the global size-aware deallocation function (with a parameter of type `[std::size\_t](../types/size_t "cpp/types/size t")`) or the global size-unaware deallocation function (without a parameter of type `[std::size\_t](../types/size_t "cpp/types/size t")`) is selected. | (since C++14) | The pointer to the block of storage to be reclaimed is passed to the [deallocation function](../memory/new/operator_delete "cpp/memory/new/operator delete") that was selected by the process above as the first argument. The size of the block is passed as the optional `[std::size\_t](../types/size_t "cpp/types/size t")` argument. The alignment requirement is passed as the optional `[std::align\_val\_t](../memory/new/align_val_t "cpp/memory/new/align val t")` argument. (since C++17). If expression evaluates to a null pointer value, no destructors are called, and the deallocation function may or may not be called (it's unspecified), but the default deallocation functions are guaranteed to do nothing when passed a null pointer. If expression evaluates to a pointer to a base class subobject of the object that was allocated with [new](new "cpp/language/new"), the destructor of the base class must be [virtual](virtual "cpp/language/virtual"), otherwise the behavior is undefined. ### Notes A pointer to `void` cannot be deleted because it is not a pointer to a complete object type. | | | | --- | --- | | Because a pair of brackets following the keyword `delete` is always interpreted as the array form of delete, a [lambda-expression](lambda "cpp/language/lambda") with an empty capture list immediately after `delete` must be enclosed in parentheses. ``` // delete []{ return new int; }(); // parse error delete ([]{ return new int; })(); // OK ``` | (since C++11) | ### Keywords [`delete`](../keyword/delete "cpp/keyword/delete"). ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 288](https://cplusplus.github.io/CWG/issues/288.html) | C++98 | for the first form, the static type of theoperand was compared with its dynamic type | compare the static type of the objectto be deleted with its dynamic type | | [CWG 353](https://cplusplus.github.io/CWG/issues/353.html) | C++98 | whether the deallocation function will be invoked ifthe destructor throws an exception was unspecified | always invoked | | [CWG 599](https://cplusplus.github.io/CWG/issues/599.html) | C++98 | the first form could take a null pointer ofany type, including function pointers | except pointers to object types,all other pointer types are rejected | | [CWG 2474](https://cplusplus.github.io/CWG/issues/2474.html) | C++98 | deleting a pointer to an object of a similar butdifferent type resulted in undefined behavior | made well-defined | ### See also * [new](new "cpp/language/new")
programming_docs
cpp new expression new expression ============== Creates and initializes objects with dynamic [storage duration](storage_duration "cpp/language/storage duration"), that is, objects whose lifetime is not necessarily limited by the scope in which they were created. ### Syntax | | | | | --- | --- | --- | | `::`(optional) `new` `(` type `)` initializer(optional) | (1) | | | `::`(optional) `new` new-type initializer(optional) | (2) | | | `::`(optional) `new` `(`placement-params`)` `(` type `)` initializer(optional) | (3) | | | `::`(optional) `new` `(`placement-params`)` new-type initializer(optional) | (4) | | 1) Attempts to create an object of type, denoted by the [type-id](type#Type_naming "cpp/language/type") type, which may be array type, and may include a [placeholder type specifier](auto "cpp/language/auto") (since C++11), or include a class template name whose argument is to be deduced by [class template argument deduction](class_template_argument_deduction "cpp/language/class template argument deduction") (since C++17). 2) Same as (1), but new-type cannot include parentheses: ``` new int(*[10])(); // error: parsed as (new int) (*[10]) () new (int (*[10])()); // okay: allocates an array of 10 pointers to functions ``` In addition, new-type is greedy: it will include every token that can be a part of a declarator: ``` new int + 1; // okay: parsed as (new int) + 1, increments a pointer returned by new int new int * 1; // error: parsed as (new int*) (1) ``` 3) Same as (1), but provides additional arguments to the allocation function, see [placement new](new#Placement_new "cpp/language/new"). 4) Same as (2), but provides additional arguments to the allocation function. The initializer is not optional if. * type or new-type is an [array of unknown bound](array#Arrays_of_unknown_bound "cpp/language/array") | | | | --- | --- | | * a [placeholder](auto "cpp/language/auto") is used in type or new-type, that is, `auto` or `decltype(auto)` (since C++14), possibly combined with a [type constraint](constraints#Concepts "cpp/language/constraints") (since C++20) | (since C++11) | | * a class template is used in type or new-type whose arguments need to be [deduced](class_template_argument_deduction "cpp/language/class template argument deduction") | (since C++17) | ``` double* p = new double[]{1,2,3}; // creates an array of type double[3] auto p = new auto('c'); // creates a single object of type char. p is a char* auto q = new std::integral auto(1); // OK: q is a int* auto q = new std::floating_point auto(true) // ERROR: type constraint not satisfied auto r = new std::pair(1, true); // OK: r is a std::pair<int, bool>* auto r = new std::vector; // ERROR: element type can't be deduced ``` ### Explanation The `new` expression attempts to allocate storage and then attempts to construct and initialize either a single unnamed object, or an unnamed array of objects in the allocated storage. The new-expression returns a prvalue pointer to the constructed object or, if an array of objects was constructed, a pointer to the initial element of the array. If `type` is an array type, all dimensions other than the first must be specified as positive [integral constant expression](constant_expression "cpp/language/constant expression") (until C++14)[converted constant expression](constant_expression "cpp/language/constant expression") of type `[std::size\_t](../types/size_t "cpp/types/size t")` (since C++14), but (only when using un-parenthesized syntaxes (2) and (4)) the first dimension may be an expression of integral type, enumeration type, or class type with a single non-explicit conversion function to integral or enumeration type (until C++14)any expression convertible to `[std::size\_t](../types/size_t "cpp/types/size t")` (since C++14). This is the only way to directly create an array with size defined at runtime, such arrays are often referred to as *dynamic arrays*: ``` int n = 42; double a[n][5]; // error auto p1 = new double[n][5]; // OK auto p2 = new double[5][n]; // error: only the first dimension may be non-constant auto p3 = new (double[n][5]); // error: syntax (1) cannot be used for dynamic arrays ``` | | | | --- | --- | | The behavior is undefined if the value in the first dimension (converted to integral or enumeration type if needed) is negative. | (until C++11) | | In the following cases the expression specifying the first dimension is erroneous:* the expression is of non-class type and its value before conversion to `[std::size\_t](../types/size_t "cpp/types/size t")` is negative; * the expression is of class type and its value after user-defined conversion function and before the [second standard conversion](implicit_conversion "cpp/language/implicit conversion") is negative; * the value of the expression is larger than some implementation-defined limit; * the value is smaller than the number of array elements provided in [the brace-enclosed initializer](aggregate_initialization "cpp/language/aggregate initialization") (including the terminating `'\0'` on a [string literal](string_literal "cpp/language/string literal")). If the value in the first dimension is erroneous for any of these reasons,* if, after conversion to `[std::size\_t](../types/size_t "cpp/types/size t")`, the first dimension is a [core constant expression](constant_expression "cpp/language/constant expression"), the program is ill-formed (a compile-time error is issued); * Otherwise, if the allocation function that would have been called is non-throwing, the new-expression returns the null pointer of the required result type * Otherwise, the new-expression does not call the allocation function, and instead throws an exception of type `[std::bad\_array\_new\_length](../memory/new/bad_array_new_length "cpp/memory/new/bad array new length")` or derived from it | (since C++11) | The first dimension of zero is acceptable, and the allocation function is called. Note: `[std::vector](../container/vector "cpp/container/vector")` offers similar functionality for one-dimensional dynamic arrays. #### Allocation The new-expression allocates storage by calling the appropriate [allocation function](../memory/new/operator_new "cpp/memory/new/operator new"). If `type` is a non-array type, the name of the function is `operator new`. If `type` is an array type, the name of the function is `operator new[]`. As described in [allocation function](../memory/new/operator_new "cpp/memory/new/operator new"), the C++ program may provide global and class-specific replacements for these functions. If the new-expression begins with the optional `::` operator, as in `::new T` or `::new T[n]`, class-specific replacements will be ignored (the function is [looked up](lookup "cpp/language/lookup") in global [scope](scope "cpp/language/scope")). Otherwise, if `T` is a class type, lookup begins in the class scope of `T`. When calling the allocation function, the new-expression passes the number of bytes requested as the first argument, of type `[std::size\_t](http://en.cppreference.com/w/cpp/types/size_t)`, which is exactly `sizeof(T)` for non-array `T`. Array allocation may supply unspecified overhead, which may vary from one call to new to the next, unless the allocation function selected is the standard non-allocating form. The pointer returned by the new-expression will be offset by that value from the pointer returned by the allocation function. Many implementations use the array overhead to store the number of objects in the array which is used by the [`delete[]`](delete "cpp/language/delete") expression to call the correct number of destructors. In addition, if the new-expression is used to allocate an array of `char`, `unsigned char`, or [`std::byte`](../types/byte "cpp/types/byte") (since C++17), it may request additional memory from the allocation function if necessary to guarantee correct alignment of objects of all types no larger than the requested array size, if one is later placed into the allocated array. | | | | --- | --- | | New-expressions are allowed to elide or combine allocations made through replaceable allocation functions. In case of elision, the storage may be provided by the compiler without making the call to an allocation function (this also permits optimizing out unused new-expression). In case of combining, the allocation made by a new-expression E1 may be extended to provide additional storage for another new-expression E2 if all of the following is true: 1) The lifetime of the object allocated by E1 strictly contains the lifetime of the object allocated by E2, 2) E1 and E2 would invoke the same replaceable global allocation function 3) For a throwing allocation function, exceptions in E1 and E2 would be first caught in the same handler. Note that this optimization is only permitted when new-expressions are used, not any other methods to call a replaceable allocation function: `delete[] new int[10];` can be optimized out, but `[operator delete](http://en.cppreference.com/w/cpp/memory/new/operator_delete)([operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)(10));` cannot. | (since C++14) | | During an evaluation of a [constant expression](constant_expression "cpp/language/constant expression"), a call to an allocation function is always omitted. Only new-expressions that would otherwise result in a call to a replaceable global allocation function can be evaluated in constant expressions. | (since C++20) | ##### Placement new If `placement-params` are provided, they are passed to the allocation function as additional arguments. Such allocation functions are known as "placement new", after the standard allocation function `void\* [operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new)([std::size\_t](http://en.cppreference.com/w/cpp/types/size_t), void\*)`, which simply returns its second argument unchanged. This is used to construct objects in allocated storage: ``` // within any block scope... { // Statically allocate the storage with automatic storage duration // which is large enough for any object of type `T`. alignas(T) unsigned char buf[sizeof(T)]; T* tptr = new(buf) T; // Construct a `T` object, placing it directly into your // pre-allocated storage at memory address `buf`. tptr->~T(); // You must **manually** call the object's destructor // if its side effects is depended by the program. } // Leaving this block scope automatically deallocates `buf`. ``` Note: this functionality is encapsulated by the member functions of the [Allocator](../named_req/allocator "cpp/named req/Allocator") classes. | | | | --- | --- | | When allocating an object whose alignment requirement exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__` or an array of such objects, the new-expression passes the alignment requirement (wrapped in `[std::align\_val\_t](../memory/new/align_val_t "cpp/memory/new/align val t")`) as the second argument for the allocation function (for placement forms, `placement-params` appear after the alignment, as the third, fourth, etc arguments). If overload resolution fails (which happens when a class-specific allocation function is defined with a different signature, since it hides the globals), overload resolution is attempted a second time, without alignment in the argument list. This allows alignment-unaware class-specific allocation functions to take precedence over the global alignment-aware allocation functions. | (since C++17) | ``` new T; // calls operator new(sizeof(T)) // (C++17) or operator new(sizeof(T), std::align_val_t(alignof(T)))) new T[5]; // calls operator new[](sizeof(T)*5 + overhead) // (C++17) or operator new(sizeof(T)*5+overhead, std::align_val_t(alignof(T)))) new(2,f) T; // calls operator new(sizeof(T), 2, f) // (C++17) or operator new(sizeof(T), std::align_val_t(alignof(T)), 2, f) ``` If a non-throwing allocation function (e.g. the one selected by `new([std::nothrow](http://en.cppreference.com/w/cpp/memory/new/nothrow)) T`) returns a null pointer because of an allocation failure, then the new-expression returns immediately, it does not attempt to initialize an object or to call a deallocation function. If a null pointer is passed as the argument to a non-allocating placement new-expression, which makes the selected standard non-allocating placement allocation function return a null pointer, the behavior is undefined. #### Construction The object created by a new-expression is initialized according to the following rules: * For non-array `type`, the single object is constructed in the acquired memory area. + If initializer is absent, the object is [default-initialized](default_initialization "cpp/language/default initialization"). + If initializer is a parenthesized list of arguments, the object is [direct-initialized](direct_initialization "cpp/language/direct initialization"). | | | | --- | --- | | * If initializer is a brace-enclosed list of arguments, the object is [list-initialized](list_initialization "cpp/language/list initialization"). | (since C++11) | * If type or new-type is an array type, an array of objects is initialized. + If initializer is absent, each element is [default-initialized](default_initialization "cpp/language/default initialization") + If initializer is an empty pair of parentheses, each element is [value-initialized](value_initialization "cpp/language/value initialization"). | | | | --- | --- | | * If initializer is a brace-enclosed list of arguments, the array is [aggregate-initialized](aggregate_initialization "cpp/language/aggregate initialization"). | (since C++11) | | * If initializer is a parenthesized list of arguments, the array is [aggregate-initialized](aggregate_initialization "cpp/language/aggregate initialization"). | (since C++20) | If initialization terminates by throwing an exception (e.g. from the constructor), if new-expression allocated any storage, it calls the appropriate [deallocation function](../memory/new/operator_delete "cpp/memory/new/operator delete"): `[operator delete](http://en.cppreference.com/w/cpp/memory/new/operator_delete)` for non-array `type`, `[operator delete](http://en.cppreference.com/w/cpp/memory/new/operator_delete)[]` for array `type`. The deallocation function is looked up in global scope if the new-expression used the `::new` syntax, otherwise it is looked up in the scope of `T`, if `T` is a class type. If the failed allocation function was usual (non-placement), lookup for the deallocation function follows the rules described in [delete-expression](delete "cpp/language/delete"). For a failed placement new, all parameter types, except the first, of the matching deallocation function must be identical to the parameters of the placement new. The call to the deallocation function is made the value obtained earlier from the allocation function passed as the first argument, alignment passed as the optional alignment argument (since C++17), and `placement-params`, if any, passed as the additional placement arguments. If no deallocation function is found, memory is not deallocated. ### Memory leaks The objects created by new-expressions (objects with dynamic storage duration) persist until the pointer returned by the new-expression is used in a matching [delete-expression](delete "cpp/language/delete"). If the original value of pointer is lost, the object becomes unreachable and cannot be deallocated: a *memory leak* occurs. This may happen if the pointer is assigned to: ``` int* p = new int(7); // dynamically allocated int with value 7 p = nullptr; // memory leak ``` or if the pointer goes out of scope: ``` void f() { int* p = new int(7); } // memory leak ``` or due to exception: ``` void f() { int* p = new int(7); g(); // may throw delete p; // okay if no exception } // memory leak if g() throws ``` To simplify management of dynamically-allocated objects, the result of a new-expression is often stored in a *[smart pointer](../memory#Smart_pointers "cpp/memory")*: `[std::auto\_ptr](../memory/auto_ptr "cpp/memory/auto ptr")` (until C++17)`[std::unique\_ptr](../memory/unique_ptr "cpp/memory/unique ptr")`, or `[std::shared\_ptr](../memory/shared_ptr "cpp/memory/shared ptr")` (since C++11). These pointers guarantee that the delete expression is executed in the situations shown above. ### Keywords [`new`](../keyword/new "cpp/keyword/new"). ### Notes [Itanium C++ ABI](https://itanium-cxx-abi.github.io/cxx-abi/abi.html#array-cookies) requires that the array allocation overhead is zero if the element type of the created array is trivially destructible. So does MSVC. Some implementations (e.g. MSVC before VS 2019 v16.7) require non-zero array allocation overhead on non-allocating placement array new if the element type is not trivially destructible, which is no longer conforming since [CWG 2382](https://cplusplus.github.io/CWG/issues/2382.html). A non-allocating placement array new-expression that creates an array of `char`, `unsigned char`, or [`std::byte`](../types/byte "cpp/types/byte") (since C++17) can be used to implicitly create objects on given region of storage: it ends lifetime of objects overlapping with the array, and then implicitly creates objects of implicit-lifetime types in the array. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 74](https://cplusplus.github.io/CWG/issues/74.html) | C++98 | value in the first dimension must have integral type | enumeration types permitted | | [CWG 299](https://cplusplus.github.io/CWG/issues/299.html) | C++98 | value in the first dimension musthave integral or enumeration type | class types with a singleconversion function to integralor enumeration type permitted | | [CWG 624](https://cplusplus.github.io/CWG/issues/624.html) | C++98 | the behavior was unspecified when thesize of the allocated object would exceedthe implementation-defined limit | no storage is obtained and anexception is thrown in this case | | [CWG 1748](https://cplusplus.github.io/CWG/issues/1748.html) | C++98 | non-allocating placement new needto check if the argument is null | undefined behavior for null argument | | [CWG 1992](https://cplusplus.github.io/CWG/issues/1992.html) | C++11 | `new ([std::nothrow](http://en.cppreference.com/w/cpp/memory/new/nothrow)) int[N]`could throw `bad_array_new_length` | changed to return a null pointer | | [P1009R2](https://wg21.link/P1009R2) | C++11 | the array bound cannot bededuced in a new expression | deduction permitted | | [CWG 2382](https://cplusplus.github.io/CWG/issues/2382.html) | C++98 | non-allocating placement array newcould require allocation overhead | such allocation overhead disallowed | ### See also * [constructor](constructor "cpp/language/constructor") * [copy elision](copy_elision "cpp/language/copy elision") * [default constructor](default_constructor "cpp/language/default constructor") * [`delete`](delete "cpp/language/delete") * [destructor](destructor "cpp/language/destructor") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [default initialization](default_initialization "cpp/language/default initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [list initialization](list_initialization "cpp/language/list initialization") + [value initialization](value_initialization "cpp/language/value initialization")
programming_docs
cpp Type alias, alias template (since C++11) Type alias, alias template (since C++11) ======================================== Type alias is a name that refers to a previously defined type (similar to [typedef](typedef "cpp/language/typedef")). Alias template is a name that refers to a family of types. ### Syntax Alias declarations are [declarations](declarations "cpp/language/declarations") with the following syntax: | | | | | --- | --- | --- | | `using` identifier attr(optional) `=` type-id `;` | (1) | | | `template` `<` template-parameter-list `>` `using` identifier attr(optional) `=` type-id `;` | (2) | | | | | | | --- | --- | --- | | attr | - | optional sequence of any number of [attributes](attributes "cpp/language/attributes") | | identifier | - | the name that is introduced by this declaration, which becomes either a type name (1) or a template name (2) | | template-parameter-list | - | [template parameter list](template_parameters "cpp/language/template parameters"), as in [template declaration](templates "cpp/language/templates") | | type-id | - | abstract declarator or any other valid type-id (which may introduce a new type, as noted in [type-id](type#Type_naming "cpp/language/type")). The type-id cannot directly or indirectly refer to identifier. Note that the [point of declaration](scope#Point_of_declaration "cpp/language/scope") of the identifier is at the semicolon following type-id. | ### Explanation 1) A type alias declaration introduces a name which can be used as a synonym for the type denoted by type-id. It does not introduce a new type and it cannot change the meaning of an existing type name. There is no difference between a type alias declaration and [typedef](typedef "cpp/language/typedef") declaration. This declaration may appear in block scope, class scope, or namespace scope. 2) An alias template is a template which, when specialized, is equivalent to the result of substituting the template arguments of the alias template for the template parameters in the type-id ``` template<class T> struct Alloc { }; template<class T> using Vec = vector<T, Alloc<T>>; // type-id is vector<T, Alloc<T>> Vec<int> v; // Vec<int> is the same as vector<int, Alloc<int>> ``` When the result of specializing an alias template is a dependent [template-id](templates#template-id "cpp/language/templates"), subsequent substitutions apply to that template-id: ``` template<typename...> using void_t = void; template<typename T> void_t<typename T::foo> f(); f<int>(); // error, int does not have a nested type foo ``` The type produced when specializing an alias template is not allowed to directly or indirectly make use of its own type: ``` template<class T> struct A; template<class T> using B = typename A<T>::U; // type-id is A<T>::U template<class T> struct A { typedef B<T> U; }; B<short> b; // error: B<short> uses its own type via A<short>::U ``` Alias templates are never deduced by [template argument deduction](function_template#Template_argument_deduction "cpp/language/function template") when deducing a template template parameter. It is not possible to [partially](partial_specialization "cpp/language/partial specialization") or [explicitly specialize](template_specialization "cpp/language/template specialization") an alias template. Like any template declaration, an alias template can only be declared at class scope or namespace scope. | | | | --- | --- | | The type of a [lambda expression](lambda "cpp/language/lambda") appearing in an alias template declaration is different between instantiations of that template, even when the lambda expression is not dependent. ``` template <class T> using A = decltype([] { }); // A<int> and A<char> refer to different closure types ``` | (since C++20) | ### Example ``` #include <iostream> #include <string> #include <typeinfo> #include <type_traits> // type alias, identical to // typedef std::ios_base::fmtflags flags; using flags = std::ios_base::fmtflags; // the name 'flags' now denotes a type: flags fl = std::ios_base::dec; // type alias, identical to // typedef void (*func)(int, int); using func = void (*) (int, int); // the name 'func' now denotes a pointer to function: void example(int, int) {} func f = example; // alias template template<class T> using ptr = T*; // the name 'ptr<T>' is now an alias for pointer to T ptr<int> x; // type alias used to hide a template parameter template<class CharT> using mystring = std::basic_string<CharT, std::char_traits<CharT>>; mystring<char> str; // type alias can introduce a member typedef name template<typename T> struct Container { using value_type = T; }; // which can be used in generic programming template<typename ContainerT> void info(const ContainerT& c) { typename ContainerT::value_type T; std::cout << "ContainerT is `" << typeid(decltype(c)).name() << "`\n" "value_type is `" << typeid(T).name() << "`\n"; } // type alias used to simplify the syntax of std::enable_if template<typename T> using Invoke = typename T::type; template<typename Condition> using EnableIf = Invoke<std::enable_if<Condition::value>>; template<typename T, typename = EnableIf<std::is_polymorphic<T>>> int fpoly_only(T) { return 1; } struct S { virtual ~S() {} }; int main() { Container<int> c; info(c); // Container::value_type will be int in this function // fpoly_only(c); // error: enable_if prohibits this S s; fpoly_only(s); // okay: enable_if allows this } ``` Possible output: ``` ContainerT is `struct Container<int>` value_type is `int` ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1558](https://cplusplus.github.io/CWG/issues/1558.html) | C++11 | whether unused arguments in an alias specialization participate in substitition is not specified | substitution is performed | ### See also | | | | --- | --- | | [`typedef` declaration](typedef "cpp/language/typedef") | creates a synonym for a type | | [namespace alias](namespace_alias "cpp/language/namespace alias") | creates an alias of an existing namespace | cpp Using-declaration Using-declaration ================= Introduces a name that is defined elsewhere into the declarative region where this using-declaration appears. | | | | | --- | --- | --- | | `using` `typename`(optional) nested-name-specifier unqualified-id `;` | | (until C++17) | | `using` declarator-list `;` | | (since C++17) | | | | | | --- | --- | --- | | `typename` | - | the keyword `typename` may be used as necessary to resolve [dependent names](dependent_name "cpp/language/dependent name"), when the using-declaration introduces a member type from a base class into a class template | | nested-name-specifier | - | a sequence of names and scope resolution operators `::`, ending with a scope resolution operator. A single `::` refers to the global namespace. | | unqualified-id | - | an [id-expression](identifiers "cpp/language/identifiers") | | declarator-list | - | comma-separated list of one or more declarators of the `typename`(optional) nested-name-specifier unqualified-id. Some or all of the declarators may be followed by an ellipsis `...` to indicate [pack expansion](parameter_pack "cpp/language/parameter pack") | ### Explanation Using-declarations can be used to introduce namespace members into other namespaces and block scopes, or to introduce base class members into derived class definitions, or to introduce [enumerators](enum "cpp/language/enum") into namespaces, block, and class scopes (since C++20). | | | | --- | --- | | A using-declaration with more than one using-declarator is equivalent to a corresponding sequence of using-declarations with one using-declarator. | (since C++17) | #### In namespace and block scope Using-declaration introduces a member of another namespace into current namespace or block scope. ``` #include <iostream> #include <string> using std::string; int main() { string str = "Example"; using std::cout; cout << str; } ``` See [namespace](namespace "cpp/language/namespace") for details. #### In class definition Using-declaration introduces a member of a base class into the derived class definition, such as to expose a protected member of base as public member of derived. In this case, nested-name-specifier must name a base class of the one being defined. If the name is the name of an overloaded member function of the base class, all base class member functions with that name are introduced. If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class. ``` #include <iostream> struct B { virtual void f(int) { std::cout << "B::f\n"; } void g(char) { std::cout << "B::g\n"; } void h(int) { std::cout << "B::h\n"; } protected: int m; // B::m is protected typedef int value_type; }; struct D : B { using B::m; // D::m is public using B::value_type; // D::value_type is public using B::f; void f(int) { std::cout << "D::f\n"; } // D::f(int) overrides B::f(int) using B::g; void g(int) { std::cout << "D::g\n"; } // both g(int) and g(char) are visible using B::h; void h(int) { std::cout << "D::h\n"; } // D::h(int) hides B::h(int) }; int main() { D d; B& b = d; // b.m = 2; // Error: B::m is protected d.m = 1; // protected B::m is accessible as public D::m b.f(1); // calls derived f() d.f(1); // calls derived f() std::cout << "----------\n"; d.g(1); // calls derived g(int) d.g('a'); // calls base g(char), exposed via using B::g; std::cout << "----------\n"; b.h(1); // calls base h() d.h(1); // calls derived h() } ``` Output: ``` D::f D::f ---------- D::g B::g ---------- B::h D::h ``` | | | | --- | --- | | Inheriting constructors If the *using-declaration* refers to a constructor of a direct base of the class being defined (e.g. `using Base::Base;`), all constructors of that base (ignoring member access) are made visible to overload resolution when initializing the derived class. If overload resolution selects an inherited constructor, it is accessible if it would be accessible when used to construct an object of the corresponding base class: the accessibility of the using-declaration that introduced it is ignored. If overload resolution selects one of the inherited constructors when initializing an object of such derived class, then the `Base` subobject from which the constructor was inherited is initialized using the inherited constructor, and all other bases and members of `Derived` are initialized as if by the defaulted default constructor (default member initializers are used if provided, otherwise default initialization takes place). The entire initialization is treated as a single function call: initialization of the parameters of the inherited constructor is sequenced-before initialization of any base or member of the derived object. ``` struct B1 { B1(int, ...) {} }; struct B2 { B2(double) {} }; int get(); struct D1 : B1 { using B1::B1; // inherits B1(int, ...) int x; int y = get(); }; void test() { D1 d(2, 3, 4); // OK: B1 is initialized by calling B1(2, 3, 4), // then d.x is default-initialized (no initialization is performed), // then d.y is initialized by calling get() D1 e; // Error: D1 has no default constructor } struct D2 : B2 { using B2::B2; // inherits B2(double) B1 b; }; D2 f(1.0); // error: B1 has no default constructor ``` ``` struct W { W(int); }; struct X : virtual W { using W::W; // inherits W(int) X() = delete; }; struct Y : X { using X::X; }; struct Z : Y, virtual W { using Y::Y; }; Z z(0); // OK: initialization of Y does not invoke default constructor of X ``` If the constructor was inherited from multiple base class subobjects of type B, the program is ill-formed, similar to multiply-inherited non-static member functions: ``` struct A { A(int); }; struct B : A { using A::A; }; struct C1 : B { using B::B; }; struct C2 : B { using B::B; }; struct D1 : C1, C2 { using C1::C1; using C2::C2; }; D1 d1(0); // ill-formed: constructor inherited from different B base subobjects struct V1 : virtual B { using B::B; }; struct V2 : virtual B { using B::B; }; struct D2 : V1, V2 { using V1::V1; using V2::V2; }; D2 d2(0); // OK: there is only one B subobject. // This initializes the virtual B base class, // which initializes the A base class // then initializes the V1 and V2 base classes // as if by a defaulted default constructor ``` As with using-declarations for any other non-static member functions, if an inherited constructor matches the signature of one of the constructors of `Derived`, it is hidden from lookup by the version found in `Derived`. If one of the inherited constructors of `Base` happens to have the signature that matches a copy/move constructor of the `Derived`, it does not prevent implicit generation of `Derived` copy/move constructor (which then hides the inherited version, similar to `using operator=`). ``` struct B1 { B1(int); }; struct B2 { B2(int); }; struct D2 : B1, B2 { using B1::B1; using B2::B2; D2(int); // OK: D2::D2(int) hides both B1::B1(int) and B2::B2(int) }; D2 d2(0); // calls D2::D2(int) ``` Within a [templated class](templates "cpp/language/templates"), if a using-declaration refers to a [dependent name](dependent_name "cpp/language/dependent name"), it is considered to name a constructor if the nested-name-specifier has a terminal name that is the same as the unqualified-id. ``` template<class T> struct A : T { using T::T; // OK, inherits constructors of T }; template<class T, class U> struct B : T, A<U> { using A<U>::A; // OK, inherits constructors of A<U> using T::A; // does not inherit constructor of T // even though T may be a specialization of A<> }; ``` | (since C++11) | | | | | --- | --- | | Introducing scoped enumerators In addition to members of another namespace and members of base classes, using-declaration can also introduce enumerators of [enumerations](enum "cpp/language/enum") into namespace, block, and class scopes. A using-declaration can also be used with unscoped enumerators. ``` enum class button { up, down }; struct S { using button::up; button b = up; // OK }; using button::down; constexpr button non_up = down; // OK constexpr auto get_button(bool is_up) { using button::up, button::down; return is_up ? up : down; // OK } enum unscoped { val }; using unscoped::val; // OK, though needless ``` | (since C++20) | ### Notes Only the name explicitly mentioned in the using-declaration is transferred into the declarative scope: in particular, enumerators are not transferred when the enumeration type name is using-declared. A using-declaration cannot refer to a namespace, to a scoped enumerator (until C++20), to a destructor of a base class or to a specialization of a member template for a user-defined conversion function. A using-declaration cannot name a member template specialization ([template-id](templates#template-id "cpp/language/templates") is not permitted by the grammar): ``` struct B { template<class T> void f(); }; struct D : B { using B::f; // OK: names a template // using B::f<int>; // Error: names a template specialization void g() { f<int>(); } }; ``` A using-declaration also can't be used to introduce the name of a dependent member template as a *template-name* (the `template` disambiguator for [dependent names](dependent_name "cpp/language/dependent name") is not permitted). ``` template<class X> struct B { template<class T> void f(T); }; template<class Y> struct D : B<Y> { // using B<Y>::template f; // Error: disambiguator not allowed using B<Y>::f; // compiles, but f is not a template-name void g() { // f<int>(0); // Error: f is not known to be a template name, // so < does not start a template argument list f(0); // OK } }; ``` If a using-declaration brings the base class assignment operator into derived class, whose signature happens to match the derived class's copy-assignment or move-assignment operator, that operator is hidden by the implicitly-declared copy/move assignment operator of the derived class. Same applies to a using-declaration that inherits a base class constructor that happens to match the derived class copy/move constructor (since C++11). | | | | | | --- | --- | --- | --- | | The semantics of inheriting constructors were retroactively changed by a [defect report against C++11](#Defect_reports). Previously, an inheriting constructor declaration caused a set of synthesized constructor declarations to be injected into the derived class, which caused redundant argument copies/moves, had problematic interactions with some forms of SFINAE, and in some cases can be unimplementable on major ABIs. Older compilers may still implement the previous semantics. | Old inheriting constructor semantics | | --- | | If the *using-declaration* refers to a constructor of a direct base of the class being defined (e.g. `using Base::Base;`), constructors of that base class are inherited, according to the following rules: 1) A set of *candidate inheriting constructors* is composed of a) All non-template constructors of the base class (after omitting ellipsis parameters, if any) (since C++14) b) For each constructor with default arguments or the ellipsis parameter, all constructor signatures that are formed by dropping the ellipsis and omitting default arguments from the ends of argument lists one by one c) All constructor templates of the base class (after omitting ellipsis parameters, if any) (since C++14) d) For each constructor template with default arguments or the ellipsis, all constructor signatures that are formed by dropping the ellipsis and omitting default arguments from the ends of argument lists one by one 2) All candidate inherited constructors that aren't the default constructor or the copy/move constructor and whose signatures do not match user-defined constructors in the derived class, are implicitly declared in the derived class. The default parameters are not inherited: ``` struct B1 { B1(int); }; struct D1 : B1 { using B1::B1; // The set of candidate inherited constructors is // 1. B1(const B1&) // 2. B1(B1&&) // 3. B1(int) // D1 has the following constructors: // 1. D1() = delete // 2. D1(const D1&) // 3. D1(D1&&) // 4. D1(int) <- inherited }; struct B2 { B2(int = 13, int = 42); }; struct D2 : B2 { using B2::B2; // The set of candidate inherited constructors is // 1. B2(const B2&) // 2. B2(B2&&) // 3. B2(int = 13, int = 42) // 4. B2(int = 13) // 5. B2() // D2 has the following constructors: // 1. D2() // 2. D2(const D2&) // 3. D2(D2&&) // 4. D2(int, int) <- inherited // 5. D2(int) <- inherited }; ``` The inherited constructors are equivalent to user-defined constructors with an empty body and with a [member initializer list](initializer_list "cpp/language/initializer list") consisting of a single nested-name-specifier, which forwards all of its arguments to the base class constructor. It has the same [access](access "cpp/language/access") as the corresponding base constructor. It is `constexpr` if the user-defined constructor would have satisfied `constexpr` constructor requirements. It is deleted if the corresponding base constructor is deleted or if a defaulted default constructor would be deleted (except that the construction of the base whose constructor is being inherited doesn't count). An inheriting constructor cannot be explicitly instantiated or explicitly specialized. If two using-declarations inherit the constructor with the same signature (from two direct base classes), the program is ill-formed. An inheriting constructor template should not be [explicitly instantiated](function_template#Explicit_instantiation "cpp/language/function template") or [explicitly specialized](template_specialization "cpp/language/template specialization"). | | (since C++11) | | | | | --- | --- | | [Pack expansions](parameter_pack "cpp/language/parameter pack") in using-declarations make it possible to form a class that exposes overloaded members of variadic bases without recursion: ``` template<typename... Ts> struct Overloader : Ts... { using Ts::operator()...; // exposes operator() from every base }; template<typename... T> Overloader(T...) -> Overloader<T...>; // C++17 deduction guide, not needed in C++20 int main() { auto o = Overloader{ [] (auto const& a) {std::cout << a;}, [] (float f) {std::cout << std::setprecision(3) << f;} }; } ``` | (since C++17) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 258](https://cplusplus.github.io/CWG/issues/258.html) | C++98 | a non-const member function of a derived class canoverride and/or hide a const member function of its base | overriding and hiding also requirecv-qualifications to be the same | | [CWG 1738](https://cplusplus.github.io/CWG/issues/1738.html) | C++11 | it was not clear whether it is permitted to explicitly instantiate orexplicitly specialize specializations of inheriting constructor templates | prohibited | | [P0136R1](https://wg21.link/P0136R1) | C++11 | inheriting constructor declaration injectsadditional constructors in the derived class | causes base class constructorsto be found by name lookup |
programming_docs
cpp Function declaration Function declaration ==================== A function declaration introduces the function name and its type. A function definition associates the function name/type with the function body. ### Function declaration Function declarations may appear in any scope. A function declaration at class scope introduces a class member function (unless the friend specifier is used), see [member functions](member_functions "cpp/language/member functions") and [friend functions](friend "cpp/language/friend") for details. The type of the function being declared is composed from the *return type* (provided by the decl-specifier-seq of the [declaration syntax](declarations "cpp/language/declarations")) and the function declarator. | | | | | --- | --- | --- | | noptr-declarator `(` parameter-list `)` cv(optional) ref(optional) except(optional) attr(optional) | (1) | | | noptr-declarator `(` parameter-list `)` cv(optional) ref(optional) except(optional) attr(optional) `->` trailing | (2) | (since C++11) | (see [Declarations](declarations "cpp/language/declarations") for the other forms of the declarator syntax). 1) Regular function declarator syntax 2) Trailing return type declaration: trailing return type is only allowed on the outermost function declarator. The decl-specifier-seq in this case must contain the keyword `auto` | | | | | --- | --- | --- | | noptr-declarator | - | any valid declarator, but if it begins with \*, &, or &&, it has to be surrounded by parentheses. | | parameter-list | - | possibly empty, comma-separated list of the function parameters (see below for details) | | attr | - | (since C++11) optional list of [attributes](attributes "cpp/language/attributes"). These attributes are applied to the type of the function, not the function itself. The attributes for the function appear after the identifier within the declarator and are combined with the attributes that appear in the beginning of the declaration, if any. | | cv | - | const/volatile qualification, only allowed in non-static member function declarations | | ref | - | (since C++11) ref-qualification, only allowed in non-static member function declarations | | except | - | | | | | --- | --- | | [dynamic exception specification](except_spec "cpp/language/except spec"). | (until C++11) | | either [dynamic exception specification](except_spec "cpp/language/except spec")or [noexcept specification](noexcept_spec "cpp/language/noexcept spec"). | (since C++11)(until C++17) | | [noexcept specification](noexcept_spec "cpp/language/noexcept spec"). | (since C++17) | | | | | --- | --- | | Note that the exception specification is not part of the function type. | (until C++17) | | | trailing | - | Trailing return type, useful if the return type depends on argument names, such as `template<class T, class U> auto add(T t, U u) -> decltype(t + u);` or is complicated, such as in `auto fpif(int)->int(*)(int)` | | | | | --- | --- | | As mentioned in [Declarations](declarations#Declarators "cpp/language/declarations"), the declarator can be followed by a *requires* clause, which declares the associated [constraints](constraints "cpp/language/constraints") for the function, which must be satisfied in order for the function to be selected by [overload resolution](overload_resolution "cpp/language/overload resolution"). (example: `void f1(int a) requires true;`) Note that the associated constraint is part of function signature, but not part of function type. | (since C++20) | Function declarators can be mixed with other declarators, where decl-specifier-seq allows: ``` // declares an int, an int*, a function, and a pointer to a function int a = 1, *p = NULL, f(), (*pf)(double); // decl-specifier-seq is int // declarator f() declares (but doesn't define) // a function taking no arguments and returning int struct S { virtual int f(char) const, g(int) &&; // declares two non-static member functions virtual int f(char), x; // compile-time error: virtual (in decl-specifier-seq) // is only allowed in declarations of non-static // member functions }; ``` | | | | --- | --- | | Using a volatile-qualified object type as parameter type or return type is deprecated. | (since C++20) | The return type of a function cannot be a function type or an array type (but can be a pointer or reference to those). | | | | --- | --- | | As with any declaration, attributes that appear before the declaration and the attributes that appear immediately after the identifier within the declarator both apply to the entity being declared or defined (in this case, to the function): ``` [[noreturn]] void f [[noreturn]] (); // okay: both attributes apply to the function f ``` However, the attributes that appear after the declarator (in the syntax above), apply to the type of the function, not to the function itself: ``` void f() [[noreturn]]; // error: this attribute has no effect on the function itself ``` | (since C++11) | As with any declaration, the type of the function `func` declared as `ret func(params)` is `ret(params)` (except for parameter type rewriting described below): see [type naming](type#Type_naming "cpp/language/type"). | | | | --- | --- | | Return type deduction If the *decl-specifier-seq* of the function declaration contains the keyword `auto`, trailing return type may be omitted, and will be deduced by the compiler from the type of the expression used in the [return](return "cpp/language/return") statement. If the return type does not use `decltype(auto)`, the deduction follows the rules of [template argument deduction](template_argument_deduction#Other_contexts "cpp/language/template argument deduction"): ``` int x = 1; auto f() { return x; } // return type is int const auto& f() { return x; } // return type is const int& ``` If the return type is `decltype(auto)`, the return type is as what would be obtained if the expression used in the return statement were wrapped in [decltype](decltype "cpp/language/decltype"): ``` int x = 1; decltype(auto) f() { return x; } // return type is int, same as decltype(x) decltype(auto) f() { return(x); } // return type is int&, same as decltype((x)) ``` (note: "`const decltype(auto)&`" is an error, `decltype(auto)` must be used on its own). If there are multiple return statements, they must all deduce to the same type: ``` auto f(bool val) { if (val) return 123; // deduces return type int else return 3.14f; // error: deduces return type float } ``` If there is no return statement or if the argument of the return statement is a void expression, the declared return type must be either `decltype(auto)`, in which case the deduced return type is `void`, or (possibly cv-qualified) `auto`, in which case the deduced return type is then (identically cv-qualified) `void`: ``` auto f() {} // returns void auto g() { return f(); } // returns void auto* x() {} // error: cannot deduce auto* from void ``` Once a return statement has been seen in a function, the return type deduced from that statement can be used in the rest of the function, including in other return statements: ``` auto sum(int i) { if (i == 1) return i; // sum’s return type is int else return sum(i - 1) + i; // okay: sum’s return type is already known } ``` If the return statement uses a brace-init-list, deduction is not allowed: ``` auto func () { return {1, 2, 3}; } // error ``` [Virtual functions](virtual "cpp/language/virtual") and [coroutines](coroutines "cpp/language/coroutines") (since C++20)cannot use return type deduction: ``` struct F { virtual auto f() { return 2; } // error }; ``` [Function templates](function_template "cpp/language/function template") other than [user-defined conversion functions](cast_operator "cpp/language/cast operator") can use return type deduction. The deduction takes place at instantiation even if the expression in the return statement is not [dependent](dependent_name "cpp/language/dependent name"). This instantiation is not in an immediate context for the purposes of [SFINAE](sfinae "cpp/language/sfinae"). ``` template<class T> auto f(T t) { return t; } typedef decltype(f(1)) fint_t; // instantiates f<int> to deduce return type template<class T> auto f(T* t) { return *t; } void g() { int (*p)(int*) = &f; } // instantiates both fs to determine return types, // chooses second template overload ``` Redeclarations or specializations of functions or function templates that use return type deduction must use the same return type placeholders: ``` auto f(int num) { return num; } // int f(int num); // error: no placeholder return type // decltype(auto) f(int num); // error: different placeholder template<typename T> auto g(T t) { return t; } template auto g(int); // okay: return type is int // template char g(char); // error: not a specialization of the primary template g ``` Similarly, redeclarations or specializations of functions or function templates that do not use return type deduction must not use a placeholder: ``` int f(int num); // auto f(int num) { return num; } // error: not a redeclaration of f template<typename T> T g(T t) { return t; } template int g(int); // okay: specialize T as int // template auto g(char); // error: not a specialization of the primary template g ``` [Explicit instantiation declarations](function_template#Explicit_instantiation "cpp/language/function template") do not themselves instantiate function templates that use return type deduction: ``` template<typename T> auto f(T t) { return t; } extern template auto f(int); // does not instantiate f<int> int (*p)(int) = f; // instantiates f<int> to determine its return type, // but an explicit instantiation definition // is still required somewhere in the program ``` | (since C++14) | ### Parameter list Parameter list determines the arguments that can be specified when the function is called. It is a comma-separated list of *parameter declarations*, each of which has the following syntax: | | | | | --- | --- | --- | | attr(optional) decl-specifier-seq declarator | (1) | | | attr(optional) decl-specifier-seq declarator `=` initializer | (2) | | | attr(optional) decl-specifier-seq abstract-declarator(optional) | (3) | | | attr(optional) decl-specifier-seq abstract-declarator(optional) `=` initializer | (4) | | | `void` | (5) | | 1) Declares a named (formal) parameter. For the meanings of decl-specifier-seq and declarator, see [declarations](declarations "cpp/language/declarations"). ``` int f(int a, int* p, int (*(*x)(double))[3]); ``` 2) Declares a named (formal) parameter with a [default value](default_arguments "cpp/language/default arguments"). ``` int f(int a = 7, int* p = nullptr, int (*(*x)(double))[3] = nullptr); ``` 3) Declares an unnamed parameter. ``` int f(int, int*, int (*(*)(double))[3]); ``` 4) Declares an unnamed parameter with a [default value](default_arguments "cpp/language/default arguments"). ``` int f(int = 7, int* = nullptr, int (*(*)(double))[3] = nullptr); ``` 5) Indicates that the function takes no parameters, it is the exact synonym for an empty parameter list: `int f(void);` and `int f();` declare the same function. Note that the type `void` (possibly cv-qualified) cannot be used in a parameter list otherwise: `int f(void, int);` and `int f(const void);` are errors (although derived types, such as `void*` can be used). In a template, only non-dependent void type can be used (a function taking a single parameter of type `T` does not become a no-parameter function if instantiated with `T = void`). An ellipsis `...` may appear at the end of the parameter list; this declares a [variadic function](variadic_arguments "cpp/language/variadic arguments"): ``` int printf(const char* fmt ...); ``` For compatibility with C89, an optional comma may appear before the ellipsis if the parameter list contains at least one parameter: ``` int printf(const char* fmt, ...); // OK, same as above ``` | | | | --- | --- | | Although decl-specifier-seq implies there can exist [specifiers](declarations#Specifiers "cpp/language/declarations") other than type specifiers, the only other specifier allowed is `register` as well as `auto` (until C++11), and it has no effect. | (until C++17) | | | | | --- | --- | | If any of the function parameters uses a *placeholder* (either `auto` or a [concept type](../concepts "cpp/concepts")), the function declaration is instead an [abbreviated function template](function_template#Abbreviated_function_template "cpp/language/function template") declaration: ``` void f1(auto); // same as template<class T> void f(T) void f2(C1 auto); // same as template<C1 T> void f7(T), if C1 is a concept ``` | (since C++20) | Parameter names declared in function declarations are usually for only self-documenting purposes. They are used (but remain optional) in function definitions. The type of each function parameter in the parameter list is determined according to the following rules: 1) First, decl-specifier-seq and the declarator are combined as in any [declaration](declarations "cpp/language/declarations") to determine the type. 2) If the type is "array of T" or "array of unknown bound of T", it is replaced by the type "pointer to T" 3) If the type is a function type F, it is replaced by the type "pointer to F" 4) Top-level cv-qualifiers are dropped from the parameter type (This adjustment only affects the function type, but doesn't modify the property of the parameter: `int f(const int p, decltype(p)*);` and `int f(int, const int*);` declare the same function) Because of these rules, the following function declarations declare exactly the same function: ``` int f(char s[3]); int f(char[]); int f(char* s); int f(char* const); int f(char* volatile s); ``` The following declarations also declare exactly the same function: ``` int f(int()); int f(int (*g)()); ``` An ambiguity arises in a parameter list when a type name is nested in parentheses (including [lambda expressions](lambda "cpp/language/lambda")) (since C++11). In this case, the choice is between the declaration of a parameter of type pointer to function and the declaration of a parameter with redundant parentheses around the identifier of the declarator. The resolution is to consider the type name as a [simple type specifier](declarations#Specifiers "cpp/language/declarations") (which is the pointer to function type): ``` class C {}; void f(int(C)) {} // void f(int(*fp)(C param)) {} // NOT void f(int C) {} void g(int *(C[10])); // void g(int *(*fp)(C param[10])); // NOT void g(int *C[10]); ``` Parameter type cannot be a type that includes a reference or a pointer to array of unknown bound, including a multi-level pointers/arrays of such types, or a pointer to functions whose parameters are such types. | | | | --- | --- | | The ellipsis that indicates [variadic arguments](variadic_arguments "cpp/language/variadic arguments") need not be preceded by a comma, even if it follows the ellipsis that indicates a [parameter pack](parameter_pack "cpp/language/parameter pack") expansion, so the following function templates are exactly the same: ``` template<typename... Args> void f(Args..., ...); template<typename... Args> void f(Args... ...); template<typename... Args> void f(Args......); ``` An example of when such declaration might be used is the [possible implementation](../types/is_function#Possible_implementation "cpp/types/is function") of `[std::is\_function](../types/is_function "cpp/types/is function")`. ``` #include <cstdio> template<typename... Variadic, typename... Args> constexpr void invoke(auto (*fun)(Variadic......), Args... args) { fun(args...); } int main() { invoke(std::printf, "%dm•%dm•%dm = %d%s%c", 2,3,7, 2*3*7, "m³", '\n'); } ``` Output: ``` 2m•3m•7m = 42m³ ``` | (since C++11) | ### Function definition A non-member function definition may appear at namespace scope only (there are no nested functions). A [member function](member_functions "cpp/language/member functions") definition may also appear in the body of a [class definition](class "cpp/language/class"). They have the following syntax: | | | | | --- | --- | --- | | attr(optional) decl-specifier-seq(optional) declarator virt-specifier-seq(optional) function-body | | | where function-body is one of the following. | | | | | --- | --- | --- | | ctor-initializer(optional) compound-statement | (1) | | | function-try-block | (2) | | | `=` `delete` `;` | (3) | (since C++11) | | `=` `default` `;` | (4) | (since C++11) | 1) regular function body 2) [function-try-block](function-try-block "cpp/language/function-try-block") (which is a regular function body wrapped in a try/catch block) 3) explicitly deleted function definition 4) explicitly defaulted function definition, only allowed for [special member functions](member_functions#Special_member_functions "cpp/language/member functions") and [comparison operator functions](default_comparisons "cpp/language/default comparisons") (since C++20) | | | | | --- | --- | --- | | attr | - | (since C++11) optional list of [attributes](attributes "cpp/language/attributes"). These attributes are combined with the attributes after the identifier in the declarator (see top of this page), if any. | | decl-specifier-seq | - | the return type with specifiers, as in the [declaration grammar](declarations "cpp/language/declarations") | | declarator | - | function declarator, same as in the function declaration grammar above (can be parenthesized). as with function declaration, it may be followed by a requires-clause (since C++20) | | virt-specifier-seq | - | (since C++11) [`override`](override "cpp/language/override"), [`final`](final "cpp/language/final"), or their combination in any order (only allowed for non-static member functions) | | ctor-initializer | - | [member initializer list](initializer_list "cpp/language/initializer list"), only allowed in constructors | | compound-statement | - | the brace-enclosed [sequence of statements](statements#Compound_statements "cpp/language/statements") that constitutes the body of a function | ``` int max(int a, int b, int c) { int m = (a > b) ? a : b; return (m > c) ? m : c; } // decl-specifier-seq is "int" // declarator is "max(int a, int b, int c)" // body is { ... } ``` The function body is a [compound statement](statements#Compound_statements "cpp/language/statements") (sequence of zero or more statements surrounded by a pair of curly braces), which is executed when the function call is made. The parameter types, as well as the return type of a function definition cannot be (possibly cv-qualified) [incomplete](incomplete_type "cpp/language/incomplete type") [class types](class "cpp/language/class") unless the function is defined as deleted (since C++11). The completeness check is only made in the function body, which allows [member functions](member_functions "cpp/language/member functions") to return the class in which they are defined (or its enclosing class), even if it is incomplete at the point of definition (it is complete in the function body). The parameters declared in the declarator of a function definition are [in scope](scope "cpp/language/scope") within the body. If a parameter is not used in the function body, it does not need to be named (it's sufficient to use an abstract declarator): ``` void print(int a, int) // second parameter is not used { std::printf("a = %d\n", a); } ``` Even though top-level [cv-qualifiers](cv "cpp/language/cv") on the parameters are discarded in function declarations, they modify the type of the parameter as visible in the body of a function: ``` void f(const int n) // declares function of type void(int) { // but in the body, the type of n is const int } ``` | | | | --- | --- | | Deleted functions If, instead of a function body, the special syntax `= delete ;` is used, the function is defined as *deleted*. Any use of a deleted function is ill-formed (the program will not compile). This includes calls, both explicit (with a function call operator) and implicit (a call to deleted overloaded operator, special member function, allocation function etc), constructing a pointer or pointer-to-member to a deleted function, and even the use of a deleted function in an unevaluated expression. However, implicit [ODR-use](definition#ODR-use "cpp/language/definition") of a non-pure virtual member function that happens to be deleted is allowed. If the function is overloaded, [overload resolution](overload_resolution "cpp/language/overload resolution") takes place first, and the program is only ill-formed if the deleted function was selected: ``` struct sometype { void* operator new(std::size_t) = delete; void* operator new[](std::size_t) = delete; }; sometype* p = new sometype; // error: attempts to call deleted sometype::operator new ``` The deleted definition of a function must be the first declaration in a translation unit: a previously-declared function cannot be redeclared as deleted: ``` struct sometype { sometype(); }; sometype::sometype() = delete; // error: must be deleted on the first declaration ``` User-provided functions A function is *user-provided* if it is user-declared and not explicitly defaulted or deleted on its first declaration. A user-provided explicitly-defaulted function (i.e., explicitly defaulted after its first declaration) is defined at the point where it is explicitly defaulted; if such a function is implicitly defined as deleted, the program is ill-formed. Declaring a function as defaulted after its first declaration can provide efficient execution and concise definition while enabling a stable binary interface to an evolving code base. ``` // All special member functions of `trivial` are // defaulted on their first declarations respectively, // they are not user-provided struct trivial { trivial() = default; trivial(const trivial&) = default; trivial(trivial&&) = default; trivial& operator=(const trivial&) = default; trivial& operator=(trivial&&) = default; ~trivial() = default; }; struct nontrivial { nontrivial(); // first declaration }; // not defaulted on the first declaration, // it is user-provided and is defined here nontrivial::nontrivial() = default; ``` \_\_func\_\_ Within the function body, the function-local predefined variable `__func__` is defined as if by. ``` static const char __func__[] = "function-name"; ``` This variable has block scope and static storage duration: ``` struct S { S(): s(__func__) {} // okay: initializer-list is part of function body const char* s; }; void f(const char* s = __func__); // error: parameter-list is part of declarator ``` ``` #include <iostream> void Foo() { std::cout << __func__ << ' '; } struct Bar { Bar() { std::cout << __func__ << ' '; } ~Bar() { std::cout << __func__ << ' '; } struct Pub { Pub() { std::cout << __func__ << ' '; } }; }; int main() { Foo(); Bar bar; Bar::Pub pub; } ``` Possible output: ``` Foo Bar Pub ~Bar ``` | (since C++11) | ### Notes In case of ambiguity between a variable declaration using the direct-initialization syntax and a function declaration, the compiler always chooses function declaration; see [direct-initialization](direct_initialization#Notes "cpp/language/direct initialization"). ### Example ``` #include <iostream> #include <string> // simple function with a default argument, returning nothing void f0(const std::string& arg = "world!") { std::cout << "Hello, " << arg << '\n'; } // the declaration is in namespace (file) scope // (the definition is provided later) int f1(); // function returning a pointer to f0, pre-C++11 style void (*fp03())(const std::string&) { return f0; } // function returning a pointer to f0, with C++11 trailing return type auto fp11() -> void(*)(const std::string&) { return f0; } int main() { f0(); fp03()("test!"); fp11()("again!"); int f2(std::string) noexcept; // declaration in function scope std::cout << "f2(\"bad\"): " << f2("bad") << '\n'; std::cout << "f2(\"42\"): " << f2("42") << '\n'; } // simple non-member function returning int int f1() { return 007; } // function with an exception specification and a function try block int f2(std::string str) noexcept try { return std::stoi(str); } catch (const std::exception& e) { std::cerr << "stoi() failed!\n"; return 0; } ``` Possible output: ``` stoi() failed! Hello, world! Hello, test! Hello, again! f2("bad"): 0 f2("42"): 42 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 135](https://cplusplus.github.io/CWG/issues/135.html) | C++98 | member functions defined in classcould not have a parameter of or returnits own class because it is incomplete | allowed | | [CWG 332](https://cplusplus.github.io/CWG/issues/332.html) | C++98 | a parameter could have cv-qualified `void` type | prohibited | | [CWG 393](https://cplusplus.github.io/CWG/issues/393.html) | C++98 | types that include pointers/references toarray of unknown bound could not be parameters | such types are allowed | | [CWG 452](https://cplusplus.github.io/CWG/issues/452.html) | C++98 | member initializer list was not a part of function body | made it a part of functionbody by modifying the syntaxof function definition | | [CWG 577](https://cplusplus.github.io/CWG/issues/577.html) | C++98 | dependent type `void` could be used todeclare a function taking no parameters | only non-dependent`void` is allowed | | [CWG 1327](https://cplusplus.github.io/CWG/issues/1327.html) | C++11 | defaulted or deleted functions could notbe specified with `override` or `final` | allowed | | [CWG 1355](https://cplusplus.github.io/CWG/issues/1355.html) | C++11 | only special member functions could be user-provided | extended to all functions | | [CWG 1394](https://cplusplus.github.io/CWG/issues/1394.html) | C++11 | deleted functions could not have any parameter ofan incomplete type or return an incomplete type | incomplete type allowed | | [CWG 1824](https://cplusplus.github.io/CWG/issues/1824.html) | C++98 | the completeness check on parameter type andreturn type of a function definition could be madeoutside the context of the function definition | only make the completenesscheck in the context ofthe function definition | | [CWG 1877](https://cplusplus.github.io/CWG/issues/1877.html) | C++14 | return type deduction treated `return;` as `return void();` | simply deduce the returntype as `void` in this case | | [CWG 2015](https://cplusplus.github.io/CWG/issues/2015.html) | C++11 | the implicit odr-use of a deletedvirtual function was ill-formed | such odr-uses are exemptfrom the use prohibition | | [CWG 2044](https://cplusplus.github.io/CWG/issues/2044.html) | C++14 | return type deduction on functions returning `void`would fail if the declared return type is `decltype(auto)` | updated the deductionrule to handle this case | | [CWG 2081](https://cplusplus.github.io/CWG/issues/2081.html) | C++14 | function redeclarations could use return typededuction even if the initial declaration does not | not allowed | | [CWG 2145](https://cplusplus.github.io/CWG/issues/2145.html) | C++98 | the declarator in function definition could not be parenthesized | allowed | | [CWG 2259](https://cplusplus.github.io/CWG/issues/2259.html) | C++11 | the ambiguity resolution rule regarding parenthesizedtype names did not cover lambda expressions | covered | | [CWG 2430](https://cplusplus.github.io/CWG/issues/2430.html) | C++98 | in the definition of a member function in a class definition,the type of that class could not be the return type orparameter type due to the resolution of [CWG issue 1824](https://cplusplus.github.io/CWG/issues/1824.html) | only make the completenesscheck in the function body | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/function_declaration "c/language/function declaration") for Declaring functions |
programming_docs
cpp Implicit conversions Implicit conversions ==================== Implicit conversions are performed whenever an expression of some type `T1` is used in context that does not accept that type, but accepts some other type `T2`; in particular: * when the expression is used as the argument when calling a function that is declared with `T2` as parameter; * when the expression is used as an operand with an operator that expects `T2`; * when initializing a new object of type `T2`, including `return` statement in a function returning `T2`; * when the expression is used in a `switch` statement (`T2` is integral type); * when the expression is used in an `if` statement or a loop (`T2` is `bool`). The program is well-formed (compiles) only if there exists one unambiguous *implicit conversion sequence* from `T1` to `T2`. If there are multiple overloads of the function or operator being called, after the implicit conversion sequence is built from `T1` to each available `T2`, [overload resolution](overload_resolution "cpp/language/overload resolution") rules decide which overload is compiled. Note: in arithmetic expressions, the destination type for the implicit conversions on the operands to binary operators is determined by a separate set of rules, [*usual arithmetic conversions*](operator_arithmetic#Conversions "cpp/language/operator arithmetic"). ### Order of the conversions Implicit conversion sequence consists of the following, in this order: 1) zero or one *standard conversion sequence*; 2) zero or one *user-defined conversion*; 3) zero or one *standard conversion sequence* (only if a user-defined conversion is used). When considering the argument to a constructor or to a user-defined conversion function, only a standard conversion sequence is allowed (otherwise user-defined conversions could be effectively chained). When converting from one non-class type to another non-class type, only a standard conversion sequence is allowed. A standard conversion sequence consists of the following, in this order: 1) zero or one conversion from the following set: *lvalue-to-rvalue conversion*, *array-to-pointer conversion*, and *function-to-pointer conversion*; 2) zero or one *numeric promotion* or *numeric conversion*; | | | | --- | --- | | 3) zero or one *function pointer conversion*; | (since C++17) | 4) zero or one *qualification conversion*. A user-defined conversion consists of zero or one non-explicit single-argument [converting constructor](converting_constructor "cpp/language/converting constructor") or non-explicit [conversion function](cast_operator "cpp/language/cast operator") call. An expression `e` is said to be *implicitly convertible to `T2`* if and only if `T2` can be [copy-initialized](copy_initialization "cpp/language/copy initialization") from `e`, that is the declaration `T2 t = e;` is well-formed (can be compiled), for some invented temporary `t`. Note that this is different from [direct initialization](direct_initialization "cpp/language/direct initialization") (`T2 t(e)`), where explicit constructors and conversion functions would additionally be considered. #### Contextual conversions | | | | | | --- | --- | --- | --- | | In the following contexts, the type `bool` is expected and the implicit conversion is performed if the declaration `bool t(e);` is well-formed (that is, an explicit conversion function such as `explicit T::operator bool() const;` is considered). Such expression `e` is said to be *contextually converted to bool*.* the controlling expression of `if`, `while`, `for`; * the operands of the built-in logical operators `!`, `&&` and `||`; * the first operand of the conditional operator `?:`; * the predicate in a [`static_assert`](static_assert "cpp/language/static assert") declaration; * the expression in a [`noexcept`](noexcept_spec "cpp/language/noexcept spec") specifier; | | | | --- | --- | | * the expression in an [`explicit`](explicit "cpp/language/explicit") specifier; | (since C++20) | | (since C++11) | In the following contexts, a context-specific type `T` is expected, and the expression `e` of class type `E` is only allowed if. | | | | --- | --- | | * `E` has a single non-explicit (since C++11) [user-defined conversion function](cast_operator "cpp/language/cast operator") to an allowable type. | (until C++14) | | * there is exactly one type `T` among the allowable types such that `E` has non-explicit conversion functions whose return types are (possibly cv-qualified) `T` or reference to (possibly cv-qualified) `T`, and * `e` is implicitly convertible to `T`. | (since C++14) | Such expression `e` is said to be *contextually implicitly converted* to the specified type `T`. Note that explicit conversion functions are not considered, even though they are considered in contextual conversions to bool. (since C++11). * the argument of the [delete-expression](delete "cpp/language/delete") (`T` is any object pointer type); * [integral constant expression](constant_expression#Integral_constant_expression "cpp/language/constant expression"), where a literal class is used (`T` is any integral or unscoped (since C++11) enumeration type, the selected user-defined conversion function must be [constexpr](constexpr "cpp/language/constexpr")); * the controlling expression of the [`switch`](switch "cpp/language/switch") statement (`T` is any integral or enumeration type). ``` #include <cassert> template<typename T> class zero_init { T val; public: zero_init() : val(static_cast<T>(0)) {} zero_init(T val) : val(val) {} operator T&() { return val; } operator T() const { return val; } }; int main() { zero_init<int> i; assert(i == 0); i = 7; assert(i == 7); switch (i) {} // error until C++14 (more than one conversion function) // OK since C++14 (both functions convert to the same type int) switch (i + 0) {} // always okay (implicit conversion) } ``` ### Value transformations Value transformations are conversions that change the [value category](value_category "cpp/language/value category") of an expression. They take place whenever an expression appears as an operand of an operator that expects an expression of a different value category. #### Lvalue to rvalue conversion A [glvalue](value_category#glvalue "cpp/language/value category") of any non-function, non-array type `T` can be implicitly converted to a [prvalue](value_category#prvalue "cpp/language/value category") of the same type. If `T` is a non-class type, this conversion also removes cv-qualifiers. The object denoted by the glvalue is not accessed if: * the conversion occurs in an [unevaluated context](expressions#Unevaluated_expressions "cpp/language/expressions"), such as an operand of `sizeof`, `noexcept`, `decltype`, (since C++11) or the static form of `typeid` | | | | --- | --- | | * the glvalue has the type `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")`: in this case the resulting prvalue is the null pointer constant `nullptr`. | (since C++11) | * the value stored in the object is a compile-time constant and certain other conditions are satisfied (see [ODR-use](definition#ODR-use "cpp/language/definition")) If `T` is a non-class type, the value contained in the object is produced as the prvalue result. For a class type, this conversion. | | | | --- | --- | | effectively copy-constructs a temporary object of type `T` using the original glvalue as the constructor argument, and that temporary object is returned as a prvalue. | (until C++17) | | converts the glvalue to a prvalue whose result object is copy-initialized by the glvalue. | (since C++17) | This conversion models the act of reading a value from a memory location into a CPU register. If the object to which the glvalue refers contains an indeterminate value (such as obtained by [default initializing](default_initialization "cpp/language/default initialization") a non-class automatic variable), the behavior is [undefined](ub "cpp/language/ub") except if the indeterminate value is of possibly cv-qualified `unsigned char` or [`std::byte`](../types/byte "cpp/types/byte") (since C++17) type. The behavior is also implementation-defined (rather than undefined) if the glvalue contains a pointer value that was invalidated. #### Array to pointer conversion An [lvalue](value_category#lvalue "cpp/language/value category") or [rvalue](value_category#rvalue "cpp/language/value category") of type "array of `N` `T`" or "array of unknown bound of `T`" can be implicitly converted to a [prvalue](value_category#prvalue "cpp/language/value category") of type "pointer to `T`". If the array is a prvalue, [temporary materialization](#Temporary_materialization) occurs. (since C++17) The resulting pointer refers to the first element of the array (see [array to pointer decay](array#Array-to-pointer_decay "cpp/language/array") for details). | | | | --- | --- | | Temporary materialization A [prvalue](value_category#prvalue "cpp/language/value category") of any complete type `T` can be converted to an xvalue of the same type `T`. This conversion initializes a temporary object of type T from the prvalue by evaluating the prvalue with the temporary object as its result object, and produces an xvalue denoting the temporary object. If `T` is a class or array of class type, it must have an accessible and non-deleted destructor. ``` struct S { int m; }; int i = S().m; // member access expects glvalue as of C++17; // S() prvalue is converted to xvalue ``` Temporary materialization occurs in the following situations:* when [binding a reference](reference_initialization "cpp/language/reference initialization") to a prvalue; * when performing a [member access](operator_member_access "cpp/language/operator member access") on a class prvalue; * when performing an array-to-pointer conversion (see above) or [subscripting](operator_member_access#Built-in_subscript_operator "cpp/language/operator member access") on an array prvalue; * when initializing an object of type `std::initializer_list<T>` from a [braced-init-list](list_initialization "cpp/language/list initialization"); * when [`typeid`](typeid "cpp/language/typeid") is applied to a prvalue (this is part of an unevaluated expression); * when [`sizeof`](sizeof "cpp/language/sizeof") is applied to a prvalue (this is part of an unevaluated expression); * when a prvalue appears as a [discarded-value expression](expressions#Discarded-value_expressions "cpp/language/expressions"). Note that temporary materialization does *not* occur when initializing an object from a prvalue of the same type (by [direct-initialization](direct_initialization "cpp/language/direct initialization") or [copy-initialization](copy_initialization "cpp/language/copy initialization")): such object is initialized directly from the initializer. This ensures "guaranteed copy elision". | (since C++17) | #### Function to pointer An [lvalue](value_category#lvalue "cpp/language/value category") of function type `T` can be implicitly converted to a [prvalue](value_category#prvalue "cpp/language/value category") [pointer to that function](pointer#Pointers_to_functions "cpp/language/pointer"). This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist. ### Numeric promotions #### Integral promotion [prvalues](value_category#prvalue "cpp/language/value category") of small integral types (such as `char`) may be converted to prvalues of larger integral types (such as `int`). In particular, [arithmetic operators](operator_arithmetic "cpp/language/operator arithmetic") do not accept types smaller than `int` as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable. This conversion always preserves the value. The following implicit conversions are classified as integral promotions: * `signed char` or `signed short` can be converted to `int`; * `unsigned char` or `unsigned short` can be converted to `int` if it can hold its entire value range, and `unsigned int` otherwise; * `char` can be converted to `int` or `unsigned int` depending on the underlying type: `signed char` or `unsigned char` (see above); * `wchar_t`, `char8_t` (since C++20), `char16_t`, and `char32_t` (since C++11) can be converted to the first type from the following list able to hold their entire value range: `int`, `unsigned int`, `long`, `unsigned long`, `long long`, `unsigned long long` (since C++11); * an unscoped (since C++11) [enumeration](enum "cpp/language/enum") type whose underlying type is not fixed can be converted to the first type from the following list able to hold their entire value range: `int`, `unsigned int`, `long`, `unsigned long`, `long long`, or `unsigned long long`, extended integer types with higher conversion rank (in rank order, signed given preference over unsigned) (since C++11). If the value range is greater, no integral promotions apply; * an unscoped (since C++11) enumeration type whose underlying type is fixed can be converted to its underlying type, and, if the underlying type is also subject to integral promotion, to the promoted underlying type. Conversion to the unpromoted underlying type is better for the purposes of [overload resolution](overload_resolution "cpp/language/overload resolution"); * a [bit-field](bit_field "cpp/language/bit field") type can be converted to `int` if it can represent entire value range of the bit-field, otherwise to `unsigned int` if it can represent entire value range of the bit-field, otherwise no integral promotions apply; * the type `bool` can be converted to `int` with the value `false` becoming `​0​` and `true` becoming `1`. Note that all other conversions are not promotions; for example, [overload resolution](overload_resolution "cpp/language/overload resolution") chooses `char` -> `int` (promotion) over `char` -> `short` (conversion). #### Floating-point promotion A [prvalue](value_category#prvalue "cpp/language/value category") of type `float` can be converted to a prvalue of type `double`. The value does not change. ### Numeric conversions Unlike the promotions, numeric conversions may change the values, with potential loss of precision. #### Integral conversions A [prvalue](value_category#prvalue "cpp/language/value category") of an integer type or of an unscoped (since C++11) enumeration type can be converted to any other integer type. If the conversion is listed under integral promotions, it is a promotion and not a conversion. * If the destination type is unsigned, the resulting value is the smallest unsigned value equal to the source value [modulo](https://en.wikipedia.org/wiki/Modular_arithmetic "enwiki:Modular arithmetic") 2n where n is the number of bits used to represent the destination type. That is, depending on whether the destination type is wider or narrower, signed integers are sign-extended[[footnote 1]](#cite_note-1) or truncated and unsigned integers are zero-extended or truncated respectively. * If the destination type is signed, the value does not change if the source integer can be represented in the destination type. Otherwise the result is implementation-defined (until C++20)the unique value of the destination type equal to the source value modulo 2n where n is the number of bits used to represent the destination type. (since C++20). (Note that this is different from [signed integer arithmetic overflow](operator_arithmetic#Overflows "cpp/language/operator arithmetic"), which is undefined). * If the source type is `bool`, the value `false` is converted to zero and the value `true` is converted to the value one of the destination type (note that if the destination type is `int`, this is an integer promotion, not an integer conversion). * If the destination type is `bool`, this is a [boolean conversion](#Boolean_conversions) (see below). #### Floating-point conversions A [prvalue](value_category#prvalue "cpp/language/value category") of a floating-point type can be converted to a prvalue of any other floating-point type. If the conversion is listed under floating-point promotions, it is a promotion and not a conversion. * If the source value can be represented exactly in the destination type, it does not change. * If the source value is between two representable values of the destination type, the result is one of those two values (it is implementation-defined which one, although if IEEE arithmetic is supported, rounding defaults [to nearest](../numeric/fenv/fe_round "cpp/numeric/fenv/FE round")). * Otherwise, the behavior is undefined. #### Floating–integral conversions * A [prvalue](value_category#prvalue "cpp/language/value category") of floating-point type can be converted to a prvalue of any integer type. The fractional part is truncated, that is, the fractional part is discarded. If the value cannot fit into the destination type, the behavior is undefined (even when the destination type is unsigned, modulo arithmetic does not apply). If the destination type is `bool`, this is a boolean conversion (see below). * A prvalue of integer or unscoped (since C++11) enumeration type can be converted to a prvalue of any floating-point type. The result is exact if possible. If the value can fit into the destination type but cannot be represented exactly, it is implementation defined whether the closest higher or the closest lower representable value will be selected, although if IEEE arithmetic is supported, rounding defaults [to nearest](../numeric/fenv/fe_round "cpp/numeric/fenv/FE round"). If the value cannot fit into the destination type, the behavior is undefined. If the source type is `bool`, the value `false` is converted to zero, and the value `true` is converted to one. #### Pointer conversions * A *null pointer constant* (see `[NULL](../types/null "cpp/types/NULL")`), can be converted to any pointer type, and the result is the null pointer value of that type. Such conversion (known as *null pointer conversion*) is allowed to convert to a cv-qualified type as a single conversion, that is, it's not considered a combination of numeric and qualifying conversions. * A [prvalue](value_category#prvalue "cpp/language/value category") pointer to any (optionally cv-qualified) object type `T` can be converted to a prvalue pointer to (identically cv-qualified) `void`. The resulting pointer represents the same location in memory as the original pointer value. If the original pointer is a null pointer value, the result is a null pointer value of the destination type. * A prvalue pointer to a (optionally cv-qualified) derived complete class type can be converted to a prvalue pointer to its (identically cv-qualified) base class. If the base class is inaccessible or ambiguous, the conversion is ill-formed (won't compile). The result of the conversion is a pointer to the base class subobject within the pointed-to object. The null pointer value is converted to the null pointer value of the destination type. #### Pointer-to-member conversions * A *null pointer constant* (see `[NULL](../types/null "cpp/types/NULL")`) can be converted to any pointer-to-member type, and the result is the null member pointer value of that type. Such conversion (known as *null member pointer conversion*) is allowed to convert to a cv-qualified type as a single conversion, that is, it's not considered a combination of numeric and qualifying conversions. * A [prvalue](value_category#prvalue "cpp/language/value category") pointer to member of some type `T` in a base class `B` can be converted to a [prvalue](value_category#prvalue "cpp/language/value category") pointer to member of the same type `T` in its derived complete class `D`. If `B` is inaccessible, ambiguous, or virtual base of `D` or is a base of some intermediate virtual base of `D`, the conversion is ill-formed (won't compile). The resulting pointer can be dereferenced with a `D` object, and it will access the member within the `B` base subobject of that `D` object. The null pointer value is converted to the null pointer value of the destination type. #### Boolean conversions A [prvalue](value_category#prvalue "cpp/language/value category") of integral, floating-point, unscoped (since C++11) enumeration, pointer, and pointer-to-member types can be converted to a prvalue of type `bool`. The value zero (for integral, floating-point, and unscoped (since C++11) enumeration) and the null pointer and the null pointer-to-member values become `false`. All other values become `true`. | | | | --- | --- | | In the context of a [direct-initialization](direct_initialization "cpp/language/direct initialization"), a `bool` object may be initialized from a prvalue of type `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")`, including `nullptr`. The resulting value is `false`. However, this is not considered to be an implicit conversion. | (since C++11) | ### Qualification conversions * A [prvalue](value_category#prvalue "cpp/language/value category") of type pointer to [cv-qualified](cv "cpp/language/cv") type `T` can be converted to a prvalue pointer to a more cv-qualified same type `T` (in other words, constness and volatility can be added). * A prvalue of type pointer to member of cv-qualified type `T` in class `X` can be converted to a prvalue pointer to member of more cv-qualified type `T` in class `X`. "More" cv-qualified means that. * a pointer to *unqualified* type can be converted to a pointer to `const`; * a pointer to *unqualified* type can be converted to a pointer to `volatile`; * a pointer to *unqualified* type can be converted to a pointer to `const volatile`; * a pointer to `const` type can be converted to a pointer to `const volatile`; * a pointer to `volatile` type can be converted to a pointer to `const volatile`. For multi-level pointers, the following restrictions apply: a multilevel pointer `P1` which is cv1 0-qualified pointer to cv1 1-qualified pointer to ... cv1 n-1-qualified pointer to cv1 n-qualified `T` is convertible to a multilevel pointer `P2` which is cv2 0-qualified pointer to cv2 1-qualified pointer to ... cv2 n-1-qualified pointer to cv2 n-qualified `T` only if. * the number of levels `n` is the same for both pointers; | | | | --- | --- | | * at every level that array type is involved in, at least one array type has unknown bound, or both array types have same size; | (since C++20) | * if there is a `const` in the cv1 k qualification at some level (other than level zero) of `P1`, there is a `const` in the same level cv2 k of `P2`; * if there is a `volatile` in the cv1 k qualification at some level (other than level zero) of `P1`, there is a `volatile` in the same cv2 klevel of `P2`; | | | | --- | --- | | * if there is an array type of unknown bound at some level (other than level zero) of `P1`, there is an array type of unknown bound in the same level of `P2`; | (since C++20) | * if at some level `k` the `P2` is *more* cv-qualified than `P1` or there is an array type of known bound in `P1` and an array type of unknown bound in `P2` (since C++20), then there must be a `const` at every single level (other than level zero) of `P2` up until k: cv2 1, cv2 2 ... cv2 k. * same rules apply to multi-level pointers to members and multi-level mixed pointers to objects and pointers to members; * same rules apply to multi-level pointers that include pointers to array of known or unknown bound at any level (arrays of cv-qualified elements are considered to be identically cv-qualified themselves); * level zero is addressed by the rules for non-multilevel qualification conversions. ``` char** p = 0; const char** p1 = p; // error: level 2 more cv-qualified but level 1 is not const const char* const * p2 = p; // OK: level 2 more cv-qualified and const added at level 1 volatile char * const * p3 = p; // OK: level 2 more cv-qual and const added at level 1 volatile const char* const* p4 = p2; // OK: 2 more cv-qual and const was already at 1 double *a[2][3]; double const * const (*ap)[3] = a; // OK double * const (*ap1)[] = a; // OK since C++20 ``` Note that in the C programming language, const/volatile can be added to the first level only: ``` char** p = 0; char * const* p1 = p; // OK in C and C++ const char* const * p2 = p; // error in C, OK in C++ ``` | | | | --- | --- | | Function pointer conversions* A [prvalue](value_category#prvalue "cpp/language/value category") of type pointer to non-throwing function can be converted to a prvalue pointer to potentially-throwing function. * A prvalue of type pointer to non-throwing member function can be converted to a prvalue pointer to potentially-throwing member function. ``` void (*p)(); void (**pp)() noexcept = &p; // error: cannot convert to pointer to noexcept function struct S { typedef void (*p)(); operator p(); }; void (*q)() noexcept = S(); // error: cannot convert to pointer to noexcept function ``` | (since C++17) | ### The safe bool problem Until the introduction of explicit conversion functions in C++11, designing a class that should be usable in boolean contexts (e.g. `if(obj) { ... }`) presented a problem: given a user-defined conversion function, such as `T::operator bool() const;`, the implicit conversion sequence allowed one additional standard conversion sequence after that function call, which means the resultant `bool` could be converted to `int`, allowing such code as `obj << 1;` or `int i = obj;`. One early solution for this can be seen in `[std::basic\_ios](../io/basic_ios "cpp/io/basic ios")`, which defines `operator!` and `operator void*`(until C++11), so that the code such as `if([std::cin](http://en.cppreference.com/w/cpp/io/cin)) {...}` compiles because `void*` is convertible to `bool`, but `int n = [std::cout](http://en.cppreference.com/w/cpp/io/cout);` does not compile because `void*` is not convertible to `int`. This still allows nonsense code such as `delete [std::cout](http://en.cppreference.com/w/cpp/io/cout);` to compile, and many pre-C++11 third party libraries were designed with a more elaborate solution, known as the [Safe Bool idiom](http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Safe_bool). | | | | --- | --- | | The [explicit bool conversion](explicit "cpp/language/explicit") can also be used to resolve the safe bool problem. ``` explicit operator bool() const { ... } ``` | (since C++11) | ### Footnotes 1. This only applies if the arithmetic is two's complement which is only required for the [exact-width integer types](../types/integer "cpp/types/integer"). Note, however, that at the moment all platforms with a C++ compiler use two's complement arithmetic ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 172](https://cplusplus.github.io/CWG/issues/172.html) | C++98 | enumeration type is promoted based on its underlying type | based on its value range instead | | [CWG 330](https://cplusplus.github.io/CWG/issues/330.html) | C++98 | conversion from `double * const (*p)[3]` to`double const * const (*p)[3]` invalid | conversion valid | | [CWG 519](https://cplusplus.github.io/CWG/issues/519.html) | C++98 | null pointer values were not guaranteed to bepreserved when converting to another pointer type | always preserved | | [CWG 616](https://cplusplus.github.io/CWG/issues/616.html) | C++98 | the behavior of lvalue to rvalue conversion ofany uninitialized object and pointer objectsof invalid values was always undefined | indeterminate `unsigned char`is allowed; use of invalid pointersis implementation-defined | | [CWG 685](https://cplusplus.github.io/CWG/issues/685.html) | C++98 | the underlying type of an enumeration type wasnot prioritized in integral promotion if it is fixed | prioritized | | [CWG 707](https://cplusplus.github.io/CWG/issues/707.html) | C++98 | integer to floating point conversionhad defined behavior in all cases | the behavior is undefined ifthe value being converted isout of the destination range | | [CWG 1423](https://cplusplus.github.io/CWG/issues/1423.html) | C++11 | `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` is convertible to boolin both direct- and copy-initialization | direct-initialization only | | [CWG 1781](https://cplusplus.github.io/CWG/issues/1781.html) | C++11 | `[std::nullptr\_t](../types/nullptr_t "cpp/types/nullptr t")` to bool is considered a implicit conversioneven though it is only valid for direct-initialization | no longer consideredan implicit conversion | | [CWG 1787](https://cplusplus.github.io/CWG/issues/1787.html) | C++98 | the behavior of reading from an indeterminate`unsigned char` cached in a register was undefined | made well-defined | | [CWG 1981](https://cplusplus.github.io/CWG/issues/1981.html) | C++11 | contextual conversions considered explicit conversion functions | not considered | | [CWG 2310](https://cplusplus.github.io/CWG/issues/2310.html) | C++98 | for derived-to-base pointer conversions andbase-to-derived pointer-to-member conversions,the derived class type could be incomplete | must be complete | | [CWG 2484](https://cplusplus.github.io/CWG/issues/2484.html) | C++20 | `char8_t` and `char16_t` have different integralpromotion strategies, but they can fit both of them | `char8_t` should be promotedin the same way as `char16_t` | ### See also * [`const_cast`](const_cast "cpp/language/const cast") * [`static_cast`](static_cast "cpp/language/static cast") * [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") * [`reinterpret_cast`](reinterpret_cast "cpp/language/reinterpret cast") * [explicit cast](explicit_cast "cpp/language/explicit cast") * [user-defined conversion](cast_operator "cpp/language/cast operator") | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/conversion "c/language/conversion") for Implicit conversions |
programming_docs
cpp Constant initialization Constant initialization ======================= Sets the initial values of the [static](storage_duration "cpp/language/storage duration") variables to a compile-time constant. ### Explanation If a static or thread-local (since C++11) variable is constant-initialized (see below), constant initialization is performed instead of zero initialization before all other initializations. A variable or temporary object `obj` is *constant-initialized* if. * either it has an [initializer](initialization "cpp/language/initialization") or its [default-initialization](default_initialization "cpp/language/default initialization") results in some initialization being performed, and * its initialization [full-expression](expressions#Full-expressions "cpp/language/expressions") is a [constant expression](constant_expression "cpp/language/constant expression"), except that if `obj` is an object, that full-expression may also invoke [constexpr](constexpr "cpp/language/constexpr") constructors for `obj` and its [subobjects](object#Subobjects "cpp/language/object") even if those objects are of non-[literal](../named_req/literaltype "cpp/named req/LiteralType") class types (since C++11). The effects of constant initialization are the same as the effects of the corresponding initialization, except that it's guaranteed that it is complete before any other initialization of a static or thread-local (since C++11) object begins, and it may be performed at compile time. ### Notes The compiler is permitted to initialize other static and thread-local (since C++11) objects using constant initialization, if it can guarantee that the value would be the same as if the standard order of initialization was followed. In practice, constant initialization is performed at compile time, and pre-calculated object representations are stored as part of the program image (e.g. in the `.data` section). If a variable is both `const` and constant initialized, its object representation may be stored in a read-only section of the program image (e.g. the `.rodata` section). ### Example ``` #include <iostream> #include <array> struct S { static const int c; }; const int d = 10 * S::c; // not a constant expression: S::c has no preceding // initializer, this initialization happens after const const int S::c = 5; // constant initialization, guaranteed to happen first int main() { std::cout << "d = " << d << '\n'; std::array<int, S::c> a1; // OK: S::c is a constant expression // std::array<int, d> a2; // error: d is not a constant expression } ``` Output: ``` d = 50 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 441](https://cplusplus.github.io/CWG/issues/441.html) | C++98 | references could not be constant initialized | made constant initializable | | [CWG 1489](https://cplusplus.github.io/CWG/issues/1489.html) | C++98 | it was unclear whether value-initializingan object can be a constant initialization | it can | | [CWG 1747](https://cplusplus.github.io/CWG/issues/1747.html) | C++98 | binding a reference to a function could not be constant initialization | it can | | [CWG 1834](https://cplusplus.github.io/CWG/issues/1834.html) | C++11 | binding a reference to an xvalue could not be constant initialization | it can | | [CWG 2026](https://cplusplus.github.io/CWG/issues/2026.html) | C++98 | zero-initialization was specified to alwaysoccur first, even before constant initialization | no zero-initialization ifconstant initialization applies | | [CWG 2366](https://cplusplus.github.io/CWG/issues/2366.html) | C++98 | default-initialization could not be constantinitialization (constant initializers were required) | it can | ### See also * [`constexpr`](constexpr "cpp/language/constexpr") * [constructor](constructor "cpp/language/constructor") * [converting constructor](converting_constructor "cpp/language/converting constructor") * [copy constructor](copy_constructor "cpp/language/copy constructor") * [default constructor](default_constructor "cpp/language/default constructor") * [`explicit`](explicit "cpp/language/explicit") * [initialization](initialization "cpp/language/initialization") + [aggregate initialization](aggregate_initialization "cpp/language/aggregate initialization") + [copy initialization](copy_initialization "cpp/language/copy initialization") + [default initialization](default_initialization "cpp/language/default initialization") + [direct initialization](direct_initialization "cpp/language/direct initialization") + [list initialization](list_initialization "cpp/language/list initialization") + [reference initialization](reference_initialization "cpp/language/reference initialization") + [value initialization](value_initialization "cpp/language/value initialization") + [zero initialization](zero_initialization "cpp/language/zero initialization") * [move constructor](move_constructor "cpp/language/move constructor") cpp switch statement switch statement ================ Transfers control to one of the several statements, depending on the value of a condition. ### Syntax | | | | | --- | --- | --- | | attr(optional) `switch` `(` init-statement(optional) condition `)` statement | | | | | | | | --- | --- | --- | | attr | - | (since C++11) any number of [attributes](attributes "cpp/language/attributes") | | init-statement | - | (since C++17) either * an [expression statement](statements#Expression_statements "cpp/language/statements") (which may be a *null statement* "`;`") * a [simple declaration](declarations#Simple_declaration "cpp/language/declarations"), typically a declaration of a variable with initializer, but it may declare arbitrarily many variables or [structured bindings](structured_binding "cpp/language/structured binding") (since C++17) | | | | --- | --- | | * an [alias declaration](type_alias "cpp/language/type alias") | (since C++23) | Note that any init-statement must end with a semicolon `;`, which is why it is often described informally as an expression or a declaration followed by a semicolon. | | condition | - | any [expression](expressions "cpp/language/expressions") of integral or enumeration type, or of a class type [contextually implicitly convertible](implicit_conversion#Contextual_conversions "cpp/language/implicit conversion") to an integral or enumeration type, or a [declaration](declarations "cpp/language/declarations") of a single non-array variable of such type with a brace-or-equals [initializer](initialization "cpp/language/initialization"). If the (possibly converted) type is subject to [integral promotions](implicit_conversion#Integral_promotion "cpp/language/implicit conversion"), condition is converted to the promoted type. | | statement | - | any [statement](statements "cpp/language/statements") (typically a compound statement). `case:` and `default:` labels are permitted in statement and `break;` statement has special meaning. | | | | | | --- | --- | --- | | attr(optional) `case` constant-expression `:` statement | (1) | | | attr(optional) `default` `:` statement | (2) | | | | | | | --- | --- | --- | | constant-expression | - | a constant expression of the same type as the type of condition after conversions and [integral promotions](implicit_conversion#Integral_promotion "cpp/language/implicit conversion") | ### Explanation The body of a switch statement may have an arbitrary number of `case:` labels, as long as the values of all constant-expressions are unique (after conversions/promotions). At most one `default:` label may be present (although nested switch statements may use their own `default:` labels or have `case:` labels whose constants are identical to the ones used in the enclosing switch). If condition evaluates to the value that is equal to the value of one of constant-expressions, then control is transferred to the statement that is labeled with that constant-expression. If condition evaluates to the value that doesn't match any of the `case:` labels, and the `default:` label is present, control is transferred to the statement labeled with the `default:` label. If condition evaluates to the value that doesn't match any of the `case:` labels, and the `default:` label is not present, then none of the statements in switch body is executed. The [break](break "cpp/language/break") statement, when encountered in statement exits the switch statement: ``` switch (1) { case 1: cout << '1'; // prints "1", case 2: cout << '2'; // then prints "2" } ``` ``` switch (1) { case 1: cout << '1'; // prints "1" break; // and exits the switch case 2: cout << '2'; break; } ``` | | | | | | | --- | --- | --- | --- | --- | | Compilers may issue warnings on fallthrough (reaching the next case label without a break) unless the [attribute](attributes "cpp/language/attributes") `[[[fallthrough](attributes/fallthrough "cpp/language/attributes/fallthrough")]]` appears immediately before the case label to indicate that the fallthrough is intentional. If init-statement is used, the switch statement is equivalent to. | | | | | --- | --- | --- | | `{` init-statement `switch` `(` condition `)` statement } | | | Except that names declared by the init-statement (if init-statement is a declaration) and names declared by condition (if condition is a declaration) are in the same scope, which is also the scope of statement. | (since C++17) | Because transfer of control is [not permitted to enter the scope](goto "cpp/language/goto") of a variable, if a declaration statement is encountered inside the statement, it has to be scoped in its own compound statement: ``` switch (1) { case 1: int x = 0; // initialization std::cout << x << '\n'; break; default: // compilation error: jump to default: // would enter the scope of 'x' without initializing it std::cout << "default\n"; break; } ``` ``` switch (1) { case 1: { int x = 0; std::cout << x << '\n'; break; } // scope of 'x' ends here default: std::cout << "default\n"; // no error break; } ``` ### Keywords [`switch`](../keyword/switch "cpp/keyword/switch"), [`case`](../keyword/case "cpp/keyword/case"), [`default`](../keyword/default "cpp/keyword/default"). ### Example The following code shows several usage cases of the *switch* statement. ``` #include <iostream> int main() { const int i = 2; switch (i) { case 1: std::cout << "1"; case 2: // execution starts at this case label std::cout << "2"; case 3: std::cout << "3"; [[fallthrough]]; // C++17 attribute to silent the warning on fall through case 5: std::cout << "45"; break; // execution of subsequent statements is terminated case 6: std::cout << "6"; } std::cout << '\n'; switch (i) { case 4: std::cout << "a"; default: std::cout << "d"; // there are no applicable constant expressions // therefore default is executed } std::cout << '\n'; switch (i) { case 4: std::cout << "a"; // nothing is executed } // when enumerations are used in a switch statement, many compilers // issue warnings if one of the enumerators is not handled enum color { RED, GREEN, BLUE }; switch (RED) { case RED: std::cout << "red\n"; break; case GREEN: std::cout << "green\n"; break; case BLUE: std::cout << "blue\n"; break; } // the C++17 init-statement syntax can be helpful when there is // no implicit conversion to integral or enumeration type struct Device { enum State { SLEEP, READY, BAD }; auto state() const { return m_state; } /*...*/ private: State m_state{}; }; switch (auto dev = Device{}; dev.state()) { case Device::SLEEP: /*...*/ break; case Device::READY: /*...*/ break; case Device::BAD: /*...*/ break; } // pathological examples // the statement doesn't have to be a compound statement switch (0) std::cout << "this does nothing\n"; // labels don't require a compound statement either switch (int n = 1) { case 0: case 1: std::cout << n << '\n'; } } ``` Output: ``` 2345 d red 1 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 1767](https://cplusplus.github.io/CWG/issues/1767.html) | C++98 | conditions of types that are not subject tointegral promotion could not be promoted | do not promoteconditions of these types | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/switch "c/language/switch") for `switch` | ### External links * [Loop unrolling using Duff's Device](https://en.wikipedia.org/wiki/Duff%27s_device "enwiki:Duff's device") * [Duff's device can be used to implement coroutines in C/C++](https://en.wikipedia.org/wiki/Coroutine#C "enwiki:Coroutine") cpp The as-if rule The as-if rule ============== Allows any and all code transformations that do not change the observable behavior of the program. ### Explanation The C++ compiler is permitted to perform any changes to the program as long as the following remains true: | | | | --- | --- | | 1) At every [sequence point](eval_order "cpp/language/eval order"), the values of all [volatile](cv "cpp/language/cv") objects are stable (previous evaluations are complete, new evaluations not started) | (until C++11) | | 1) Accesses (reads and writes) to [volatile](cv "cpp/language/cv") objects occur strictly according to the semantics of the expressions in which they occur. In particular, they are [not reordered](../atomic/memory_order "cpp/atomic/memory order") with respect to other volatile accesses on the same thread. | (since C++11) | 2) At program termination, data written to files is exactly as if the program was executed as written. 3) Prompting text which is sent to interactive devices will be shown before the program waits for input. 4) If the ISO C pragma [`#pragma STDC FENV_ACCESS`](../preprocessor/impl "cpp/preprocessor/impl") is supported and is set to `ON`, the changes to the [floating-point environment](../numeric/fenv "cpp/numeric/fenv") (floating-point exceptions and rounding modes) are guaranteed to be observed by the floating-point arithmetic operators and function calls as if executed as written, except that * the result of any floating-point expression other than cast and assignment may have range and precision of a floating-point type different from the type of the expression (see `[FLT\_EVAL\_METHOD](../types/climits/flt_eval_method "cpp/types/climits/FLT EVAL METHOD")`) * notwithstanding the above, intermediate results of any floating-point expression may be calculated as if to infinite range and precision (unless [`#pragma STDC FP_CONTRACT`](../preprocessor/impl "cpp/preprocessor/impl") is `OFF`) ### Notes Because the compiler is (usually) unable to analyze the code of an external library to determine whether it does or does not perform I/O or volatile access, third-party library calls also aren't affected by optimization. However, standard library calls may be replaced by other calls, eliminated, or added to the program during optimization. Statically-linked third-party library code may be subject to link-time optimization. Programs with [undefined behavior](ub "cpp/language/ub"), e.g. due to access to an array out of bounds, modification of a const object, [evaluation order](eval_order "cpp/language/eval order") violations, etc, are free from the as-if rule: they often change observable behavior when recompiled with different optimization settings. For example, if a test for signed integer overflow relies on the result of that overflow, e.g. `if(n+1 < n) abort();`, [it is removed entirely by some compilers](http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html) because [signed overflow is undefined behavior](operator_arithmetic#Overflows "cpp/language/operator arithmetic") and the optimizer is free to assume it never happens and the test is redundant. [Copy elision](copy_elision "cpp/language/copy elision") is an exception from the as-if rule: the compiler may remove calls to move- and copy-constructors and the matching calls to the destructors of temporary objects even if those calls have observable side effects. | | | | --- | --- | | [New-expression](new#Allocation "cpp/language/new") has another exception from the as-if rule: the compiler may remove calls to the [replaceable allocation functions](../memory/new/operator_new "cpp/memory/new/operator new") even if a user-defined replacement is provided and has observable side-effects. | (since C++14) | The count and order of floating-point exceptions can be changed by optimization as long as the state as observed by the next floating-point operation is as if no optimization took place: ``` #pragma STDC FENV_ACCESS ON for (i = 0; i < n; i++) x + 1; // x+1 is dead code, but may raise FP exceptions // (unless the optimizer can prove otherwise). However, executing it n times will // raise the same exception over and over. So this can be optimized to: if (0 < n) x + 1; ``` ### Example ``` int& preinc(int& n) { return ++n; } int add(int n, int m) { return n+m; } // volatile input to prevent constant folding volatile int input = 7; // volatile output to make the result a visible side-effect volatile int result; int main() { int n = input; // using built-in operators would invoke undefined behavior // int m = ++n + ++n; // but using functions makes sure the code executes as-if // the functions were not overlapped int m = add(preinc(n), preinc(n)); result = m; } ``` Output: ``` # full code of the main() function as produced by the GCC compiler # x86 (Intel) platform: movl input(%rip), %eax # eax = input leal 3(%rax,%rax), %eax # eax = 3 + eax + eax movl %eax, result(%rip) # result = eax xorl %eax, %eax # eax = 0 (the return value of main()) ret # PowerPC (IBM) platform: lwz 9,LC..1(2) li 3,0 # r3 = 0 (the return value of main()) lwz 11,0(9) # r11 = input; slwi 11,11,1 # r11 = r11 << 1; addi 0,11,3 # r0 = r11 + 3; stw 0,4(9) # result = r0; blr # Sparc (Sun) platform: sethi %hi(result), %g2 sethi %hi(input), %g1 mov 0, %o0 # o0 = 0 (the return value of main) ld [%g1+%lo(input)], %g1 # g1 = input add %g1, %g1, %g1 # g1 = g1 + g1 add %g1, 3, %g1 # g1 = 3 + g1 st %g1, [%g2+%lo(result)] # result = g1 jmp %o7+8 nop # in all cases, the side effects of preinc() were eliminated, and the # entire main() function was reduced to the equivalent of result = 2*input + 3; ``` ### See also * [copy elision](copy_elision "cpp/language/copy elision") | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/as_if "c/language/as if") for as-if rule |
programming_docs
cpp Requires expression (since C++20) Requires expression (since C++20) ================================= Yields a prvalue expression of type `bool` that describes the constraints. ### Syntax | | | | | --- | --- | --- | | `requires` `{` requirement-seq `}` | | | | `requires` `(` parameter-list(optional) `)` `{` requirement-seq `}` | | | | | | | | --- | --- | --- | | parameter-list | - | a comma-separated list of parameters like in a function declaration, except that default arguments are not allowed and it cannot end with an ellipsis (other than one signifying a pack expansion). These parameters have no storage, linkage or lifetime, and are only used to assist in specifying requirements. These parameters are in scope until the closing `}` of the requirement-seq. | | requirement-seq | - | sequence of *requirements*, each requirement is one of the following: * simple requirement * type requirements * compound requirements * nested requirements | ### Explanation Requirements may refer to the template parameters that are in scope, to the local parameters introduced in the parameter-list, and to any other declarations that are visible from the enclosing context. The substitution of template arguments into a requires-expression used in a declaration of a [templated entity](templates#Templated_entity "cpp/language/templates") may result in the formation of invalid types or expressions in its requirements, or the violation of semantic constraints of those requirements. In such cases, the requires-expression evaluates to `false` and does not cause the program to be ill-formed. The substitution and semantic constraint checking proceeds in lexical order and stops when a condition that determines the result of the requires-expression is encountered. If substitution (if any) and semantic constraint checking succeed, the requires-expression evaluates to `true`. If a substitution failure would occur in a requires-expression for every possible template argument, the program is ill-formed, no diagnostic required: ``` template<class T> concept C = requires { new int[-(int)sizeof(T)]; // invalid for every T: ill-formed, no diagnostic required }; ``` If a requires-expression contains invalid types or expressions in its requirements, and it does not appear within the declaration of a [templated entity](templates#Templated_entity "cpp/language/templates"), then the program is ill-formed. ### Simple requirements A simple requirement is an arbitrary expression statement that does not start with the keyword `requires`. It asserts that the expression is valid. The expression is an unevaluated operand; only language correctness is checked. ``` template<typename T> concept Addable = requires (T a, T b) { a + b; // "the expression a+b is a valid expression that will compile" }; template<class T, class U = T> concept Swappable = requires(T&& t, U&& u) { swap(std::forward<T>(t), std::forward<U>(u)); swap(std::forward<U>(u), std::forward<T>(t)); }; ``` A requirement that starts with the keyword `requires` is always interpreted as a nested requirement. Thus a simple requirement cannot start with an unparenthesized requires-expression. ### Type requirements A type requirement is the keyword `typename` followed by a type name, optionally qualified. The requirement is that the named type is valid: this can be used to verify that a certain named nested type exists, or that a class template specialization names a type, or that an alias template specialization names a type. A type requirement naming a class template specialization does not require the type to be complete. ``` template<typename T> using Ref = T&; template<typename T> concept C = requires { typename T::inner; // required nested member name typename S<T>; // required class template specialization typename Ref<T>; // required alias template substitution }; template<class T, class U> using CommonType = std::common_type_t<T, U>; template<class T, class U> concept Common = requires (T&& t, U&& u) { typename CommonType<T, U>; // CommonType<T, U> is valid and names a type { CommonType<T, U>{std::forward<T>(t)} }; { CommonType<T, U>{std::forward<U>(u)} }; }; ``` ### Compound Requirements A compound requirement has the form. | | | | | --- | --- | --- | | `{` expression `}` `noexcept`(optional) return-type-requirement(optional) `;` | | | | | | | | --- | --- | --- | | return-type-requirement | - | `->` type-constraint | and asserts properties of the named expression. Substitution and semantic constraint checking proceeds in the following order: 1) Template arguments (if any) are substituted into expression; 2) If `noexcept` is used, expression must not be [potentially throwing](noexcept "cpp/language/noexcept"); 3) If return-type-requirement is present, then: a) Template arguments are substituted into the return-type-requirement; b) `decltype((expression))` must satisfy the constraint imposed by the type-constraint. Otherwise, the enclosing requires-expression is `false`. ``` template<typename T> concept C2 = requires(T x) { // the expression *x must be valid // AND the type T::inner must be valid // AND the result of *x must be convertible to T::inner {*x} -> std::convertible_to<typename T::inner>; // the expression x + 1 must be valid // AND std::same_as<decltype((x + 1)), int> must be satisfied // i.e., (x + 1) must be a prvalue of type int {x + 1} -> std::same_as<int>; // the expression x * 1 must be valid // AND its result must be convertible to T {x * 1} -> std::convertible_to<T>; }; ``` ### Nested requirements A nested requirement has the form. | | | | | --- | --- | --- | | `requires` constraint-expression `;` | | | It can be used to specify additional constraints in terms of local parameters. The constraint-expression must be satisfied by the substituted template arguments, if any. Substitution of template arguments into a nested requirement causes substitution into the constraint-expression only to the extent needed to determine whether the constraint-expression is satisfied. ``` template<class T> concept Semiregular = DefaultConstructible<T> && CopyConstructible<T> && Destructible<T> && CopyAssignable<T> && requires(T a, size_t n) { requires Same<T*, decltype(&a)>; // nested: "Same<...> evaluates to true" { a.~T() } noexcept; // compound: "a.~T()" is a valid expression that doesn't throw requires Same<T*, decltype(new T)>; // nested: "Same<...> evaluates to true" requires Same<T*, decltype(new T[n])>; // nested { delete new T }; // compound { delete new T[n] }; // compound }; ``` ### Note The keyword `requires` is also used to introduce [requires clauses](constraints#Requires_clauses "cpp/language/constraints"). ``` template<typename T> concept Addable = requires (T x) { x + x; }; // requires-expression template<typename T> requires Addable<T> // requires-clause, not requires-expression T add(T a, T b) { return a + b; } template<typename T> requires requires (T x) { x + x; } // ad-hoc constraint, note keyword used twice T add(T a, T b) { return a + b; } ``` ### Keywords [`requires`](../keyword/requires "cpp/keyword/requires"). ### See also | | | | --- | --- | | [Constraints and concepts](constraints "cpp/language/constraints")(C++20) | specifies the requirements on template arguments | cpp Language linkage Language linkage ================ Provides for linkage between modules written in different programming languages. | | | | | --- | --- | --- | | `extern` string-literal `{` declaration-seq(optional) `}` | (1) | | | `extern` string-literal declaration | (2) | | 1) Applies the language specification string-literal to all function types, function names with external linkage and variables with external linkage declared in declaration-seq. 2) Applies the language specification string-literal to a single declaration or definition. | | | | | --- | --- | --- | | string-literal | - | the name of the required language linkage | | declaration-seq | - | a sequence of declarations, which may include nested linkage specifications | | declaration | - | a declaration | ### Explanation Every function type, every function name with [external linkage](storage_duration "cpp/language/storage duration"), and every variable name with [external linkage](storage_duration "cpp/language/storage duration"), has a property called *language linkage*. Language linkage encapsulates the set of requirements necessary to link with a module written in another programming language: [calling convention](https://en.wikipedia.org/wiki/Calling_convention "enwiki:Calling convention"), [name mangling](https://en.wikipedia.org/wiki/Name_mangling "enwiki:Name mangling") algorithm, etc. Only two language linkages are guaranteed to be supported: 1. `"C++"`, the default language linkage. 2. `"C"`, which makes it possible to link with functions written in the C programming language, and to define, in a C++ program, functions that can be called from the modules written in C. ``` extern "C" { int open(const char *pathname, int flags); // C function declaration } int main() { int fd = open("test.txt", 0); // calls a C function from a C++ program } // This C++ function can be called from C code extern "C" void handler(int) { std::cout << "Callback invoked\n"; // It can use C++ } ``` Since language linkage is part of every function type, pointers to functions maintain language linkage as well. Language linkage of function types (which represents calling convention) and language linkage of function names (which represents name mangling) are independent of each other: ``` extern "C" void f1(void(*pf)()); // declares a function f1 with C linkage, // which returns void and takes a pointer to a C function // which returns void and takes no parameters extern "C" typedef void FUNC(); // declares FUNC as a C function type that returns void // and takes no parameters FUNC f2; // the name f2 has C++ linkage, but its type is C function extern "C" FUNC f3; // the name f3 has C linkage and its type is C function void() void (*pf2)(FUNC*); // the name pf2 has C++ linkage, and its type is // "pointer to a C++ function which returns void and takes one // argument of type 'pointer to the C function which returns void // and takes no parameters'" extern "C" { static void f4(); // the name of the function f4 has internal linkage (no language) // but the function's type has C language linkage } ``` Two functions with the same name and the same parameter list in the same namespace cannot have two different language linkages (note, however, that linkage of a parameter may permit such overloading, as in the case of `[std::qsort](../algorithm/qsort "cpp/algorithm/qsort")` and `[std::bsearch](../algorithm/bsearch "cpp/algorithm/bsearch")`). Likewise, two variables in the same namespace cannot have two different language linkages. #### Special rules for "C" linkage When class members, friend functions with a trailing [requires-clause](constraints#Requires_clauses "cpp/language/constraints"), (since C++20) or member functions appear in a `"C"` language block, the linkage of their types remains `"C++"` (but parameter types, if any, remain `"C"`): ``` extern "C" { class X { void mf(); // the function mf and its type have C++ language linkage void mf2(void(*)()); // the function mf2 has C++ language linkage; // the parameter has type “pointer to C function” }; } ``` When a function or a variable is declared (in any namespace) with `"C"` language linkage, all declarations of functions (in any namespace) and all declarations of variables in global scope with the same unqualified name must refer to the same function or variable. ``` int x; namespace A { extern "C" int x(); // error: same name as global-namespace variable x } ``` ``` namespace A { extern "C" int f(); } namespace B { extern "C" int f(); // A​::​f and B​::​f refer to the same function f with C linkage } int A::f() { return 98; } // definition for that function ``` ``` namespace A { extern "C" int g() { return 1; } } namespace B { extern "C" int g() { return 1; } // error: redefinition of the same function } ``` ``` namespace A { extern "C" int h(); } extern "C" int h() { return 97; } // definition for the C linkage function h // A​::​h and ​::​h refer to the same function ``` | | | | --- | --- | | Note: the special rule that excludes friend with trailing requires clauses makes it possible to declare a friend function with the same name as a global scope `"C"` function using a dummy clause: ``` template<typename T> struct A { struct B; }; extern "C" { template<typename T> struct A<T>::B { friend void f(B*) requires true {} // C language linkage ignored }; } namespace Q { extern "C" void f(); // not ill-formed } ``` | (since C++23) | ### Notes Language specifications can only appear in [namespace scope](scope#Namespace_scope "cpp/language/scope"). The braces of the language specification do not establish a scope. When language specifications nest, the innermost specification is the one that is in effect. A function can be re-declared without a linkage specification after it was declared with a language specification, the second declaration will reuse the first language linkage. The opposite is not true: if the first declaration has no language linkage, it is assumed `"C++"`, and redeclaring with another language is an error. A declaration directly contained in a language linkage specification is treated as if it contains the [`extern` specifier](storage_duration "cpp/language/storage duration") for the purpose of determining the [linkage](storage_duration#Linkage "cpp/language/storage duration") of the declared name and whether it is a [definition](definition "cpp/language/definition"). ``` extern "C" int x; // a declaration and not a definition // The above line is equivalent to extern "C" { extern int x; } extern "C" { int x; } // a declaration and definition extern "C" double f(); static double f(); // error: linkage confliction extern "C" static void g(); // error: linkage confliction ``` `extern "C"` makes it possible to include header files containing declarations of C library functions in a C++ program, but if the same header file is shared with a C program, `extern "C"` (which is not allowed in C) must be hidden with an appropriate [`#ifdef`](../preprocessor/conditional "cpp/preprocessor/conditional"), typically [`__cplusplus`](../preprocessor/replace#Predefined_macros "cpp/preprocessor/replace"): ``` #ifdef __cplusplus extern "C" int foo(int, int); // C++ compiler sees this #else int foo(int, int); // C compiler sees this #endif ``` The only modern compiler that differentiates function types with `"C"` and `"C++"` language linkages is Oracle Studio, others do not permit overloads that are only different in language linkage, including the overload sets required by the C++ standard (`[std::qsort](../algorithm/qsort "cpp/algorithm/qsort")`, `[std::bsearch](../algorithm/bsearch "cpp/algorithm/bsearch")`, `[std::signal](../utility/program/signal "cpp/utility/program/signal")`, `[std::atexit](../utility/program/atexit "cpp/utility/program/atexit")`, and `[std::at\_quick\_exit](../utility/program/at_quick_exit "cpp/utility/program/at quick exit")`): [GCC bug 2316](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=2316), [Clang bug 6277](https://bugs.llvm.org/show_bug.cgi?id=6277), [CWG issue 1555](https://cplusplus.github.io/CWG/issues/1555.html). ``` extern "C" using c_predfun = int(const void*, const void*); extern "C++" using cpp_predfun = int(const void*, const void*); // ill-formed, but accepted by most compilers static_assert(std::is_same<c_predfun, cpp_predfun>::value, "C and C++ language linkages shall not differentiate function types."); // following declarations do not declare overloads in most compilers // because c_predfun and cpp_predfun are considered to be the same type void qsort(void* base, std::size_t nmemb, std::size_t size, c_predfun* compar); void qsort(void* base, std::size_t nmemb, std::size_t size, cpp_predfun* compar); ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 4](https://cplusplus.github.io/CWG/issues/4.html) | C++98 | names with internal linkage can have language linkages | limited to names with external linkage | | [CWG 341](https://cplusplus.github.io/CWG/issues/341.html) | C++98 | a function with "C" language linkage canhave the same name as a global variable | the program is ill-formed in this case(no diagnostic required if theyappear in different translation units) | | [CWG 564](https://cplusplus.github.io/CWG/issues/564.html) | C++98 | the program was ill-formed if two declarationsonly differ in language linkage specifications(i.e. different string literals following 'extern') | the actual language linkages given bythe declarations are compared instead | | [CWG 2460](https://cplusplus.github.io/CWG/issues/2460.html) | C++20 | friend functions with a trailing requires-clauseand "C" language linkage had conflict behaviors | "C" language linkage is ignored in this case | ### References * C++20 standard (ISO/IEC 14882:2020): + 9.11 Linkage specifications [dcl.link] * C++17 standard (ISO/IEC 14882:2017): + 10.5 Linkage specifications [dcl.link] * C++14 standard (ISO/IEC 14882:2014): + 7.5 Linkage specifications [dcl.link] * C++11 standard (ISO/IEC 14882:2011): + 7.5 Linkage specifications [dcl.link] * C++03 standard (ISO/IEC 14882:2003): + 7.5 Linkage specifications [dcl.link] cpp do-while loop do-while loop ============= Executes a statement repeatedly, until the value of expression becomes false. The test takes place after each iteration. ### Syntax | | | | | --- | --- | --- | | attr(optional) `do` statement `while (` expression `)` `;` | | | | | | | | --- | --- | --- | | attr | - | (since C++11) any number of [attributes](attributes "cpp/language/attributes") | | expression | - | any [expression](expressions "cpp/language/expressions") which is [contextually convertible](implicit_cast "cpp/language/implicit cast") to bool. This expression is evaluated after each iteration, and if it yields `false`, the loop is exited. | | statement | - | any [statement](statements "cpp/language/statements"), typically a compound statement, which is the body of the loop | ### Explanation statement is always executed at least once, even if expression always yields false. If it should not execute in this case, a [while](while "cpp/language/while") or [for](for "cpp/language/for") loop may be used. If the execution of the loop needs to be terminated at some point, a [break statement](break "cpp/language/break") can be used as terminating statement. If the execution of the loop needs to be continued at the end of the loop body, a [continue statement](continue "cpp/language/continue") can be used as shortcut. ### Notes As part of the C++ [forward progress guarantee](memory_model#Forward_progress "cpp/language/memory model"), the behavior is [undefined](ub "cpp/language/ub") if a loop that has no [observable behavior](as_if "cpp/language/as if") (does not make calls to I/O functions, access volatile objects, or perform atomic or synchronization operations) does not terminate. Compilers are permitted to remove such loops. ### Keywords [`do`](../keyword/do "cpp/keyword/do"), [`while`](../keyword/while "cpp/keyword/while"). ### Example ``` #include <iostream> #include <algorithm> #include <string> int main() { int j = 2; do { // compound statement is the loop body j += 2; std::cout << j << " "; } while (j < 9); std::cout << '\n'; // common situation where do-while loop is used std::string s = "aba"; std::sort(s.begin(), s.end()); do std::cout << s << '\n'; // expression statement is the loop body while(std::next_permutation(s.begin(), s.end())); } ``` Output: ``` 4 6 8 10 aab aba baa ``` ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/do "c/language/do") for `do-while` |
programming_docs
cpp for loop for loop ======== Executes init-statement once, then executes statement and iteration-expression repeatedly, until the value of condition becomes false. The test takes place before each iteration. ### Syntax | | | | | --- | --- | --- | | *formal syntax:* | | | | attr(optional) `for (` init-statement condition(optional) `;` iteration-expression(optional) `)` statement | | | | *informal syntax:* | | | | attr(optional) `for (` declaration-or-expression(optional) `;` declaration-or-expression(optional) `;` expression(optional) `)` statement | | | | | | | | --- | --- | --- | | attr | - | (since C++11) any number of [attributes](attributes "cpp/language/attributes") | | init-statement | - | one of * an [expression statement](statements "cpp/language/statements") (which may be a *null statement* "`;`") * a [simple declaration](declarations "cpp/language/declarations"), typically a declaration of a loop counter variable with initializer, but it may declare arbitrary many variables or [structured bindings](structured_binding "cpp/language/structured binding") (since C++17) | | | | --- | --- | | * an [alias declaration](type_alias "cpp/language/type alias") | (since C++23) | Note that any init-statement must end with a semicolon `;`, which is why it is often described informally as an expression or a declaration followed by a semicolon. | | condition | - | either * an [expression](expressions "cpp/language/expressions") which is [contextually convertible](implicit_cast "cpp/language/implicit cast") to bool. This expression is evaluated before each iteration, and if it yields `false`, the loop is exited. * a [declaration](declarations "cpp/language/declarations") of a single variable with a brace-or-equals [initializer](initialization "cpp/language/initialization"). the initializer is evaluated before each iteration, and if the value of the declared variable converts to `false`, the loop is exited. | | iteration-expression | - | any [expression](expressions "cpp/language/expressions"), which is executed after every iteration of the loop and before re-evaluating condition. Typically, this is the expression that increments the loop counter | | statement | - | any [statement](statements "cpp/language/statements"), typically a compound statement, which is the body of the loop | ### Explanation The above syntax produces code equivalent to: | | | | | --- | --- | --- | | `{` init-statement `while (` condition `) {` statement iteration-expression `;` `}` `}` | | | Except that. 1) Names declared by the init-statement (if init-statement is a declaration) and names declared by condition (if condition is a declaration) are in the same scope (which is also the scope of statement). 2) [continue](continue "cpp/language/continue") in the statement will execute iteration-expression 3) Empty condition is equivalent to `while(true)` If the execution of the loop needs to be terminated at some point, [break statement](break "cpp/language/break") can be used as terminating statement. If the execution of the loop needs to be continued at the end of the loop body, [continue statement](continue "cpp/language/continue") can be used as shortcut. As is the case with [while](while "cpp/language/while") loop, if statement is a single statement (not a compound statement), the scope of variables declared in it is limited to the loop body as if it was a compound statement. ``` for (;;) int n; // n goes out of scope ``` ### Keywords [`for`](../keyword/for "cpp/keyword/for"). ### Notes As part of the C++ [forward progress guarantee](memory_model#Forward_progress "cpp/language/memory model"), the behavior is [undefined](ub "cpp/language/ub") if a loop that has no [observable behavior](as_if "cpp/language/as if") (does not make calls to I/O functions, access volatile objects, or perform atomic or synchronization operations) does not terminate. Compilers are permitted to remove such loops. While in C++, the scope of the init-statement and the scope of statement are one and the same, in C the scope of statement is nested within the scope of init-statement: ``` for (int i = 0; ; ) { long i = 1; // valid C, invalid C++ // ... } ``` ### Example ``` #include <iostream> #include <vector> int main() { std::cout << "1) typical loop with a single statement as the body:\n"; for (int i = 0; i < 10; ++i) std::cout << i << ' '; std::cout << "\n\n" "2) init-statement can declare multiple names, as " "long as they can use the same decl-specifier-seq:\n"; for (int i = 0, *p = &i; i < 9; i += 2) { std::cout << i << ':' << *p << ' '; } std::cout << "\n\n" "3) condition may be a declaration:\n"; char cstr[] = "Hello"; for (int n = 0; char c = cstr[n]; ++n) std::cout << c; std::cout << "\n\n" "4) init-statement can use the auto type specifier:\n"; std::vector<int> v = {3, 1, 4, 1, 5, 9}; for (auto iter = v.begin(); iter != v.end(); ++iter) { std::cout << *iter << ' '; } std::cout << "\n\n" "5) init-statement can be an expression:\n"; int n = 0; for (std::cout << "Loop start\n"; std::cout << "Loop test\n"; std::cout << "Iteration " << ++n << '\n') if(n > 1) break; std::cout << "\n" "6) constructors and destructors of objects created " "in the loop's body are called per each iteraton:\n"; struct S { S(int x, int y) { std::cout << "S::S(" << x << ", " << y << "); "; } ~S() { std::cout << "S::~S()\n"; } }; for (int i{0}, j{5}; i < j; ++i, --j) S s{i, j}; } ``` Output: ``` 1) typical loop with a single statement as the body: 0 1 2 3 4 5 6 7 8 9 2) init-statement can declare multiple names, as long as they can use the same decl-specifier-seq: 0:0 2:2 4:4 6:6 8:8 3) condition may be a declaration: Hello 4) init-statement can use the auto type specifier: 3 1 4 1 5 9 5) init-statement can be an expression: Loop start Loop test Iteration 1 Loop test Iteration 2 Loop test 6) constructors and destructors of objects created in the loops's body are called per each iteraton: S::S(0, 5); S::~S() S::S(1, 4); S::~S() S::S(2, 3); S::~S() ``` ### See also | | | | --- | --- | | [range-`for` loop](range-for "cpp/language/range-for")(C++11) | executes loop over range | | [C documentation](https://en.cppreference.com/w/c/language/for "c/language/for") for `for` | cpp Namespace aliases Namespace aliases ================= Namespace aliases allow the programmer to define an alternate name for a namespace. They are commonly used as a convenient shortcut for long or deeply-nested namespaces. ### Syntax | | | | | --- | --- | --- | | `namespace` alias\_name = ns\_name`;` | (1) | | | `namespace` alias\_name = `::`ns\_name`;` | (2) | | | `namespace` alias\_name = nested\_name`::`ns\_name`;` | (3) | | ### Explanation The new alias alias\_name provides an alternate method of accessing ns\_name. alias\_name must be a name not previously used. alias\_name is valid for the duration of the scope in which it is introduced. ### Example ``` #include <iostream> namespace foo { namespace bar { namespace baz { int qux = 42; } } } namespace fbz = foo::bar::baz; int main() { std::cout << fbz::qux << '\n'; } ``` Output: ``` 42 ``` ### See also | | | | --- | --- | | [namespace declaration](namespace "cpp/language/namespace") | identifies a namespace | | [type alias declaration](type_alias "cpp/language/type alias") (C++11) | creates a synonym for a type | cpp Dynamic exception specification (until C++17) Dynamic exception specification (until C++17) ============================================= Lists the exceptions that a function might directly or indirectly throw. ### Syntax | | | | | --- | --- | --- | | `throw(`type-id-list(optional)`)` | (1) | (deprecated in C++11)(removed in C++17) | 1) Explicit dynamic exception specification | | | | | --- | --- | --- | | type-id-list | - | comma-separated list of [type-ids](type#Type_naming "cpp/language/type"), a type-id representing a [pack expansion](parameter_pack#Pack_expansion "cpp/language/parameter pack") is followed by an ellipsis (...) (since C++11) | An explicit dynamic exception specification shall appear only on a function declarator for a function type, pointer to function type, reference to function type, or pointer to member function type that is the top-level type of a declaration or definition, or on such a type appearing as a parameter or return type in a function declarator. ``` void f() throw(int); // OK: function declaration void (*pf)() throw (int); // OK: pointer to function declaration void g(void pfa() throw(int)); // OK: pointer to function parameter declaration typedef int (*pf)() throw(int); // Error: typedef declaration ``` ### Explanation If a function is declared with type `T` listed in its dynamic exception specification, the function may throw exceptions of that type or a type derived from it. [Incomplete types](incomplete_type "cpp/language/incomplete type"), pointers or references to incomplete types other than cv `void*`, and rvalue reference types (since C++11) are not allowed in the exception specification. Array and function types, if used, are adjusted to corresponding pointer types, top level cv-qualifications are also dropped. [parameter packs](parameter_pack "cpp/language/parameter pack") are allowed (since C++11). A dynamic exception specification whose set of adjusted types is empty (after any packs are expanded) (since C++11) is non-throwing. A function with a non-throwing dynamic exception specification does not allow any exceptions. A dynamic exception specification is not considered part of a function’s type. If the function throws an exception of the type not listed in its exception specification, the function `[std::unexpected](../error/unexpected "cpp/error/unexpected")` is called. The default function calls `[std::terminate](../error/terminate "cpp/error/terminate")`, but it may be replaced by a user-provided function (via `[std::set\_unexpected](../error/set_unexpected "cpp/error/set unexpected")`) which may call `[std::terminate](../error/terminate "cpp/error/terminate")` or throw an exception. If the exception thrown from `[std::unexpected](../error/unexpected "cpp/error/unexpected")` is accepted by the exception specification, stack unwinding continues as usual. If it isn't, but `[std::bad\_exception](../error/bad_exception "cpp/error/bad exception")` is allowed by the exception specification, `[std::bad\_exception](../error/bad_exception "cpp/error/bad exception")` is thrown. Otherwise, `[std::terminate](../error/terminate "cpp/error/terminate")` is called. ### Potential exceptions Each function `f`, pointer to function `pf`, and pointer to member function `pmf` has a *set of potential exceptions*, which consists of types that might be thrown. Set of all types indicates that any exception may be thrown. This set is defined as follows: 1) If the declaration of `f`, `pf`, or `pmf` uses a dynamic exception specification that does not allow all exceptions (until C++11), the set consists of the types listed in that specification. | | | | --- | --- | | 2) Otherwise, if the declaration of `f`, `pf`, or `pmf` uses [`noexcept(true)`](noexcept "cpp/language/noexcept"), the set is empty. | (since C++11) | 3) Otherwise, the set is the set of all types. Note: for implicitly-declared special member functions (constructors, assignment operators, and destructors) and for the inheriting constructors (since C++11), the set of potential exceptions is a combination of the sets of the potential exceptions of everything they would call: constructors/assignment operators/destructors of non-variant non-static data members, direct bases, and, where appropriate, virtual bases (including default argument expressions, as always). Each expression `e` has a *set of potential exceptions*. The set is empty if `e` is a [core constant expression](constant_expression "cpp/language/constant expression"), otherwise, it is the union of the sets of potential exceptions of all immediate subexpressions of `e` (including [default argument expressions](default_arguments "cpp/language/default arguments")), combined with another set that depends on the form of `e`, as follows: 1) If `e` is a function call expression, let `g` denote the function, function pointer, or pointer to member function that is that is called, then * if the declaration of `g` uses a dynamic exception specification, the set of potential exceptions of `g` is added to the set; | | | | --- | --- | | * if the declaration of `g` uses [`noexcept(true)`](noexcept "cpp/language/noexcept"), the set is empty; | (since C++11) | * otherwise, the set is the set of all types. 2) If `e` calls a function implicitly (it's an operator expression and the operator is overloaded, it is a [new-expression](new "cpp/language/new") and the allocation function is overloaded, or it is a full expression and the destructor of a temporary is called), then the set is the set of that function. 3) If `e` is a [throw-expression](throw "cpp/language/throw"), the set is the exception that would be initialized by its operand, or the set of all types for the re-throwing throw-expression (with no operand). 4) If `e` is a [`dynamic_cast`](dynamic_cast "cpp/language/dynamic cast") to a reference to a polymorphic type, the set consists of `[std::bad\_cast](../types/bad_cast "cpp/types/bad cast")`. 5) If `e` is a [`typeid`](typeid "cpp/language/typeid") applied to a dereferenced pointer to a polymorphic type, the set consists of `[std::bad\_typeid](../types/bad_typeid "cpp/types/bad typeid")`. | | | | --- | --- | | 6) If `e` is a [new-expression](new "cpp/language/new") with a non-constant array size, and the selected allocation function has a non-empty set of potential exceptions, the set consists of `[std::bad\_array\_new\_length](../memory/new/bad_array_new_length "cpp/memory/new/bad array new length")`. | (since C++11) | ``` void f() throw(int); // f()'s set is "int" void g(); // g()'s set is the set of all types struct A { A(); }; // "new A"'s set is the set of all types struct B { B() noexcept; }; // "B()"'s set is empty struct D() { D() throw (double); }; // new D's set is the set of all types ``` All implicitly-declared member functions and inheriting constructors (since C++11)have exception specifications, selected as follows: * If the set of potential exceptions is the set of all types, the implicit exception specification allows all exceptions (the exception specification is considered present, even though it is inexpressible in code and behaves as if there is no exception specification) (until C++11)is `noexcept(false)` (since C++11). * Otherwise, If the set of potential exceptions is not empty, the implicit exception specification lists every type from the set. * Otherwise, the implicit exception specification is `throw()` (until C++11)`noexcept(true)` (since C++11). ``` struct A { A(int = (A(5), 0)) noexcept; A(const A&) throw(); A(A&&) throw(); ~A() throw(X); }; struct B { B() throw(); B(const B&) = default; // exception specification is "noexcept(true)" B(B&&, int = (throw Y(), 0)) noexcept; ~B() throw(Y); }; int n = 7; struct D : public A, public B { int * p = new (std::nothrow) int[n]; // D has the following implicitly-declared members: // D::D() throw(X, std::bad_array_new_length); // D::D(const D&) noexcept(true); // D::D(D&&) throw(Y); // D::~D() throw(X, Y); }; ``` ### Example ``` #include <iostream> #include <exception> #include <cstdlib> static_assert(__cplusplus < 201700, "ISO C++17 does not allow dynamic exception specifications."); class X {}; class Y {}; class Z : public X {}; class W {}; void f() throw(X, Y) { int n = 0; if (n) throw X(); // OK if (n) throw Z(); // also OK throw W(); // will call std::unexpected() } int main() { std::set_unexpected([] { std::cout << "That was unexpected!" << std::endl; // flush needed std::abort(); }); f(); } ``` Output: ``` That was unexpected! ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 25](https://cplusplus.github.io/CWG/issues/25.html) | C++98 | the behavior of assignment and initializationbetween pointers to members with differentexception specifications was unspecified | apply the restrictionfor function pointersand references | | [CWG 973](https://cplusplus.github.io/CWG/issues/973.html) | C++98 | exception specification may contain functions types, but thecorresponding function pointer conversion was not specified | specified | | [CWG 1267](https://cplusplus.github.io/CWG/issues/1267.html) | C++11 | rvalue reference types were allowed in exception specifications | not allowed | | [CWG 1351](https://cplusplus.github.io/CWG/issues/1351.html) | C++98C++11 | default argument (C++98) and default member initializer(C++11) were ignored in implicit exception specification | made considered | | [CWG 1777](https://cplusplus.github.io/CWG/issues/1777.html) | C++11 | `throw(T...)` was not a non-throwingspecification even if `T` is an empty pack | it is non-throwingif the pack is empty | | [CWG 2191](https://cplusplus.github.io/CWG/issues/2191.html) | C++98 | the set of potential exceptions of a `typeid` expressionmight contain `bad_typeid` even if it cannot be thrown | contains `bad_typeid`only if it can be thrown | ### See also | | | | --- | --- | | [`noexcept` specifier](noexcept_spec "cpp/language/noexcept spec")(C++11) | specifies whether a function could throw exceptions | cpp C++ attribute: likely, unlikely (since C++20) C++ attribute: likely, unlikely (since C++20) ============================================= Allow the compiler to optimize for the case where paths of execution including that statement are more or less likely than any alternative path of execution that does not include such a statement. ### Syntax | | | | | --- | --- | --- | | `[[likely]]` | (1) | | | `[[unlikely]]` | (2) | | ### Explanation These attributes may be applied to labels and statements (other than declaration-statements). They may not be simultaneously applied to the same label or statement. 1) Applies to a statement to allow the compiler to optimize for the case where paths of execution including that statement are more likely than any alternative path of execution that does not include such a statement. 2) Applies to a statement to allow the compiler to optimize for the case where paths of execution including that statement are less likely than any alternative path of execution that does not include such a statement. A path of execution is deemed to include a label if and only if it contains a jump to that label: ``` int f(int i) { switch(i) { case 1: [[fallthrough]]; [[likely]] case 2: return 1; } return 2; } ``` `i == 2` is considered more likely than any other value of `i`, but the `[[**likely**]]` has no effect on the `i == 1` case even though it falls through the `case 2:` label. ### Example ``` #include <chrono> #include <cmath> #include <iomanip> #include <iostream> #include <random> namespace with_attributes { constexpr double pow(double x, long long n) noexcept { if (n > 0) [[likely]] return x * pow(x, n - 1); else [[unlikely]] return 1; } constexpr long long fact(long long n) noexcept { if (n > 1) [[likely]] return n * fact(n - 1); else [[unlikely]] return 1; } constexpr double cos(double x) noexcept { constexpr long long precision{16LL}; double y{}; for (auto n{0LL}; n < precision; n += 2LL) [[likely]] y += pow(x, n) / (n & 2LL ? -fact(n) : fact(n)); return y; } } // namespace with_attributes namespace no_attributes { constexpr double pow(double x, long long n) noexcept { if (n > 0) return x * pow(x, n - 1); else return 1; } constexpr long long fact(long long n) noexcept { if (n > 1) return n * fact(n - 1); else return 1; } constexpr double cos(double x) noexcept { constexpr long long precision{16LL}; double y{}; for (auto n{0LL}; n < precision; n += 2LL) y += pow(x, n) / (n & 2LL ? -fact(n) : fact(n)); return y; } } // namespace no_attributes double gen_random() noexcept { static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_real_distribution<double> dis(-1.0, 1.0); return dis(gen); } volatile double sink{}; // ensures a side effect int main() { for (const auto x : {0.125, 0.25, 0.5, 1. / (1 << 26)}) { std::cout << std::setprecision(53) << "x = " << x << '\n' << std::cos(x) << '\n' << with_attributes::cos(x) << '\n' << (std::cos(x) == with_attributes::cos(x) ? "equal" : "differ") << '\n'; } auto benchmark = [](auto fun, auto rem) { const auto start = std::chrono::high_resolution_clock::now(); for (auto size{1ULL}; size != 10'000'000ULL; ++size) { sink = fun(gen_random()); } const std::chrono::duration<double> diff = std::chrono::high_resolution_clock::now() - start; std::cout << "Time: " << std::fixed << std::setprecision(6) << diff.count() << " sec " << rem << std::endl; }; benchmark(with_attributes::cos, "(with attributes)"); benchmark(no_attributes::cos, "(without attributes)"); benchmark([](double t) { return std::cos(t); }, "(std::cos)"); } ``` Possible output: ``` x = 0.125 0.99219766722932900560039115589461289346218109130859375 0.99219766722932900560039115589461289346218109130859375 equal x = 0.25 0.96891242171064473343022882545483298599720001220703125 0.96891242171064473343022882545483298599720001220703125 equal x = 0.5 0.8775825618903727587394314468838274478912353515625 0.8775825618903727587394314468838274478912353515625 equal x = 1.490116119384765625e-08 0.99999999999999988897769753748434595763683319091796875 0.99999999999999988897769753748434595763683319091796875 equal Time: 0.579122 sec (with attributes) Time: 0.722553 sec (without attributes) Time: 0.425963 sec (std::cos) ```
programming_docs
cpp C++ attribute: fallthrough (since C++17) C++ attribute: fallthrough (since C++17) ======================================== Indicates that the fall through from the previous case label is intentional and should not be diagnosed by a compiler that warns on fallthrough. ### Syntax | | | | | --- | --- | --- | | `[[fallthrough]]` | | | ### Explanation May only be applied to a [null statement](../statements#Expression_statements "cpp/language/statements") to create a *fallthrough statement* (`[[fallthrough]];`). A fallthrough statement may only be used in a [switch](../switch "cpp/language/switch") statement, where the next statement to be executed is a statement with a case or default label for that switch statement. If the fallthrough statement is inside a loop, the next (labeled) statement must be part of the same iteration of that loop. ### Example ``` void f(int n) { void g(), h(), i(); switch (n) { case 1: case 2: g(); [[fallthrough]]; case 3: // no warning on fallthrough h(); case 4: // compiler may warn on fallthrough if (n < 3) { i(); [[fallthrough]]; // OK } else { return; } case 5: while (false) { [[fallthrough]]; // ill-formed: next statement is not // part of the same iteration } case 6: [[fallthrough]]; // ill-formed, no subsequent case or default label } } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 2406](https://cplusplus.github.io/CWG/issues/2406.html) | C++17 | `[[fallthrough]]` could appear in a loopnested inside the target switch statement | prohibited | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/attributes/fallthrough "c/language/attributes/fallthrough") for `fallthrough` | cpp C++ attribute: nodiscard (since C++17) C++ attribute: nodiscard (since C++17) ====================================== If a function declared `nodiscard` or a function returning an enumeration or class declared `nodiscard` by value is called from a [discarded-value expression](../expressions#Discarded-value_expressions "cpp/language/expressions") other than a cast to `void`, the compiler is encouraged to issue a warning. ### Syntax | | | | | --- | --- | --- | | `[[nodiscard]]` | (1) | | | `[[nodiscard(` string-literal `)]]` | (2) | (since C++20) | | | | | | --- | --- | --- | | string-literal | - | text that could be used to explain the rationale for why the result should not be discarded | ### Explanation Appears in a function declaration, enumeration declaration, or class declaration. If, from a [discarded-value expression](../expressions#Discarded-value_expressions "cpp/language/expressions") other than a cast to `void`, * a function declared `nodiscard` is called, or * a function returning an enumeration or class declared `nodiscard` by value is called, or * a constructor declared `nodiscard` is called by [explicit type conversion](../explicit_cast "cpp/language/explicit cast") or [`static_cast`](../static_cast "cpp/language/static cast"), or * an object of an enumeration or class type declared `nodiscard` is initialized by [explicit type conversion](../explicit_cast "cpp/language/explicit cast") or [`static_cast`](../static_cast "cpp/language/static cast"), the compiler is encouraged to issue a warning. | | | | --- | --- | | The string-literal, if specified, is usually included in the warnings. | (since C++20) | ### Example ``` struct [[nodiscard]] error_info { /*...*/ }; error_info enable_missile_safety_mode() { /*...*/ return {}; } void launch_missiles() { /*...*/ } void test_missiles() { enable_missile_safety_mode(); // compiler may warn on discarding a nodiscard value launch_missiles(); } error_info& foo() { static error_info e; /*...*/ return e; } void f1() { foo(); // nodiscard type is not returned by value, no warning } // nodiscard( string-literal ) (since C++20): [[nodiscard("PURE FUN")]] int strategic_value(int x, int y) { return x^y; } int main() { strategic_value(4,2); // compiler may warn on discarding a nodiscard value auto z = strategic_value(0,0); // ok: return value is not discarded return z; } ``` Possible output: ``` game.cpp:5:4: warning: ignoring return value of function declared with 'nodiscard' attribute game.cpp:17:5: warning: ignoring return value of function declared with 'nodiscard' attribute: PURE FUN ``` ### Standard library The following standard functions are declared with `nodiscard` attribute: | | | --- | | Allocation functions | | [operator newoperator new[]](../../memory/new/operator_new "cpp/memory/new/operator new") | allocation functions (function) | | [allocate](../../memory/allocator/allocate "cpp/memory/allocator/allocate") | allocates uninitialized storage (public member function of `std::allocator<T>`) | | [allocate](../../memory/allocator_traits/allocate "cpp/memory/allocator traits/allocate") [static] | allocates uninitialized storage using the allocator (public static member function of `std::allocator_traits<Alloc>`) | | [allocate](../../memory/memory_resource/allocate "cpp/memory/memory resource/allocate") | allocates memory (public member function of `std::pmr::memory_resource`) | | [allocate](../../memory/polymorphic_allocator/allocate "cpp/memory/polymorphic allocator/allocate") | Allocate memory (public member function of `std::pmr::polymorphic_allocator<T>`) | | [allocate](../../memory/scoped_allocator_adaptor/allocate "cpp/memory/scoped allocator adaptor/allocate") | allocates uninitialized storage using the outer allocator (public member function of `std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...>`) | | Indirect access | | [launder](../../utility/launder "cpp/utility/launder") (C++17) | pointer optimization barrier (function template) | | [assume\_aligned](../../memory/assume_aligned "cpp/memory/assume aligned") (C++20) | informs the compiler that a pointer is aligned (function template) | | Emptiness-checking functions | | [empty](../../iterator/empty "cpp/iterator/empty") (C++17) | checks whether the container is empty (function template) | | [empty](../../container/node_handle#empty "cpp/container/node handle") | checks whether the node handle is empty(public member function of `*node handle*`) | | [empty](../../container/array/empty "cpp/container/array/empty") (C++11) | checks whether the container is empty (public member function of `std::array<T,N>`) | | [empty](../../string/basic_string/empty "cpp/string/basic string/empty") | checks whether the string is empty (public member function of `std::basic_string<CharT,Traits,Allocator>`) | | [empty](../../string/basic_string_view/empty "cpp/string/basic string view/empty") (C++17) | checks whether the view is empty (public member function of `std::basic_string_view<CharT,Traits>`) | | [empty](../../container/deque/empty "cpp/container/deque/empty") | checks whether the container is empty (public member function of `std::deque<T,Allocator>`) | | [empty](../../container/forward_list/empty "cpp/container/forward list/empty") (C++11) | checks whether the container is empty (public member function of `std::forward_list<T,Allocator>`) | | [empty](../../container/list/empty "cpp/container/list/empty") | checks whether the container is empty (public member function of `std::list<T,Allocator>`) | | [empty](../../container/map/empty "cpp/container/map/empty") | checks whether the container is empty (public member function of `std::map<Key,T,Compare,Allocator>`) | | [empty](../../regex/match_results/empty "cpp/regex/match results/empty") | checks whether the match was successful (public member function of `std::match_results<BidirIt,Alloc>`) | | [empty](../../container/multimap/empty "cpp/container/multimap/empty") | checks whether the container is empty (public member function of `std::multimap<Key,T,Compare,Allocator>`) | | [empty](../../container/multiset/empty "cpp/container/multiset/empty") | checks whether the container is empty (public member function of `std::multiset<Key,Compare,Allocator>`) | | [empty](../../container/priority_queue/empty "cpp/container/priority queue/empty") | checks whether the underlying container is empty (public member function of `std::priority_queue<T,Container,Compare>`) | | [empty](../../container/queue/empty "cpp/container/queue/empty") | checks whether the underlying container is empty (public member function of `std::queue<T,Container>`) | | [empty](../../container/set/empty "cpp/container/set/empty") | checks whether the container is empty (public member function of `std::set<Key,Compare,Allocator>`) | | [empty](../../container/span/empty "cpp/container/span/empty") | checks if the sequence is empty (public member function of `std::span<T,Extent>`) | | [empty](../../container/stack/empty "cpp/container/stack/empty") | checks whether the underlying container is empty (public member function of `std::stack<T,Container>`) | | [empty](../../container/unordered_map/empty "cpp/container/unordered map/empty") (C++11) | checks whether the container is empty (public member function of `std::unordered_map<Key,T,Hash,KeyEqual,Allocator>`) | | [empty](../../container/unordered_multimap/empty "cpp/container/unordered multimap/empty") (C++11) | checks whether the container is empty (public member function of `std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>`) | | [empty](../../container/unordered_multiset/empty "cpp/container/unordered multiset/empty") (C++11) | checks whether the container is empty (public member function of `std::unordered_multiset<Key,Hash,KeyEqual,Allocator>`) | | [empty](../../container/unordered_set/empty "cpp/container/unordered set/empty") (C++11) | checks whether the container is empty (public member function of `std::unordered_set<Key,Hash,KeyEqual,Allocator>`) | | [empty](../../container/vector/empty "cpp/container/vector/empty") | checks whether the container is empty (public member function of `std::vector<T,Allocator>`) | | [empty](../../filesystem/path/empty "cpp/filesystem/path/empty") | checks if the path is empty (public member function of `std::filesystem::path`) | | Miscellaneous | | [async](../../thread/async "cpp/thread/async") (C++11) | runs a function asynchronously (potentially in a new thread) and returns a `[std::future](../../thread/future "cpp/thread/future")` that will hold the result (function template) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [P1771R1](https://wg21.link/P1771R1) | C++17 | `[[nodiscard]]` on constructors has no effect | can cause a warning if the constructed object is discarded | ### See also | | | | --- | --- | | [ignore](../../utility/tuple/ignore "cpp/utility/tuple/ignore") (C++11) | placeholder to skip an element when unpacking a `tuple` using [`tie`](../../utility/tuple/tie "cpp/utility/tuple/tie") (constant) | | [C documentation](https://en.cppreference.com/w/c/language/attributes/nodiscard "c/language/attributes/nodiscard") for `nodiscard` | cpp C++ attribute: carries_dependency (since C++11) C++ attribute: carries\_dependency (since C++11) ================================================ Indicates that dependency chain in release-consume `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")` propagates in and out of the function, which allows the compiler to skip unnecessary memory fence instructions. ### Syntax | | | | | --- | --- | --- | | `[[carries_dependency]]` | | | ### Explanation Indicates that dependency chain in release-consume `[std::memory\_order](../../atomic/memory_order "cpp/atomic/memory order")` propagates in and out of the function, which allows the compiler to skip unnecessary memory fence instructions. This attribute may appear in two situations: 1) it may apply to the parameter declarations of a function or lambda-expressions, in which case it indicates that initialization of the parameter carries dependency into lvalue-to-rvalue conversion of that object. 2) It may apply to the function declaration as a whole, in which case it indicates that the return value carries dependency to the evaluation of the function call expression. This attribute must appear on the first declaration of a function or one of its parameters in any translation unit. If it is not used on the first declaration of a function or one of its parameters in another translation unit, the program is ill-formed; no diagnostic required. See `[std::kill\_dependency](../../atomic/kill_dependency "cpp/atomic/kill dependency")` for example usage. cpp C++ attribute: optimize_for_synchronized (TM TS) C++ attribute: optimize\_for\_synchronized (TM TS) ================================================== Indicates that the function definition should be optimized for invocation from a [synchronized statement](../transactional_memory "cpp/language/transactional memory"). ### Syntax | | | | | --- | --- | --- | | `[[optimize_for_synchronized]]` | | | ### Explanation Applies to the name being declared in a function declaration, which must be the first declaration of the function. Indicates that the function definition should be optimized for invocation from a [synchronized statement](../transactional_memory "cpp/language/transactional memory"). In particular, it avoids serializing synchronized blocks that make a call to a function that is transaction-safe for the majority of calls, but not for all calls. ### Example cpp C++ attribute: noreturn (since C++11) C++ attribute: noreturn (since C++11) ===================================== Indicates that the function does not return. ### Syntax | | | | | --- | --- | --- | | `[[noreturn]]` | | | ### Explanation Indicates that the function does not return. This attribute applies to the name of the function being declared in function declarations only. The behavior is undefined if the function with this attribute actually returns. The first declaration of the function must specify this attribute if any declaration specifies it. If a function is declared with `[[**noreturn**]]` in one translation unit, and the same function is declared without `[[**noreturn**]]` in another translation unit, the program is ill-formed; no diagnostic required. ### Example ``` [[ noreturn ]] void f() { throw "error"; // OK } void q [[ noreturn ]] (int i) { // behavior is undefined if called with an argument <= 0 if (i > 0) { throw "positive"; } } // void h() [[noreturn]]; // error: attribute applied to function type of h, not h itself int main() { try { f(); } catch(...) {} try { q(42); } catch(...) {} } ``` ### Standard library The following standard functions are declared with `noreturn` attribute: | | | --- | | Terminating functions | | [\_Exit](../../utility/program/_exit "cpp/utility/program/ Exit") (C++11) | causes normal program termination without cleaning up (function) | | [abort](../../utility/program/abort "cpp/utility/program/abort") | causes abnormal program termination (without cleaning up) (function) | | [exit](../../utility/program/exit "cpp/utility/program/exit") | causes normal program termination with cleaning up (function) | | [quick\_exit](../../utility/program/quick_exit "cpp/utility/program/quick exit") (C++11) | causes quick program termination without completely cleaning up (function) | | [terminate](../../error/terminate "cpp/error/terminate") | function called when exception handling fails (function) | | [unexpected](../../error/unexpected "cpp/error/unexpected") (removed in C++17) | function called when dynamic exception specification is violated (function) | | Compiler hints | | [unreachable](../../utility/unreachable "cpp/utility/unreachable") (C++23) | marks unreachable point of execution (function) | | Always-throwing functions | | [rethrow\_exception](../../error/rethrow_exception "cpp/error/rethrow exception") (C++11) | throws the exception from an `[std::exception\_ptr](../../error/exception_ptr "cpp/error/exception ptr")` (function) | | [rethrow\_nested](../../error/nested_exception/rethrow_nested "cpp/error/nested exception/rethrow nested") | throws the stored exception (public member function of `std::nested_exception`) | | [throw\_with\_nested](../../error/throw_with_nested "cpp/error/throw with nested") (C++11) | throws its argument with `[std::nested\_exception](../../error/nested_exception "cpp/error/nested exception")` mixed in (function template) | | Non-local jumps (since C++17) | | [longjmp](../../utility/program/longjmp "cpp/utility/program/longjmp") | jumps to specified location (function) | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/_Noreturn "c/language/ Noreturn") for `_Noreturn` | | [C documentation](https://en.cppreference.com/w/c/language/attributes/noreturn "c/language/attributes/noreturn") for `[[noreturn]]` | cpp C++ attribute: maybe_unused (since C++17) C++ attribute: maybe\_unused (since C++17) ========================================== Suppresses warnings on unused entities. ### Syntax | | | | | --- | --- | --- | | `[[maybe_unused]]` | | | ### Explanation This attribute can appear in the declaration of the following entities: * [class/struct/union](../classes "cpp/language/classes"): `struct [[maybe_unused]] S;`, * [typedef](../typedef "cpp/language/typedef"), including those declared by [alias declaration](../type_alias "cpp/language/type alias"): `[[maybe_unused]] typedef S* PS;`, `using PS [[maybe_unused]] = S*;`, * variable, including [static data member](../static "cpp/language/static"): `[[maybe_unused]] int x;`, * [non-static data member](../data_members "cpp/language/data members"): `union U { [[maybe_unused]] int n; };`, * [function](../function "cpp/language/function"): `[[maybe_unused]] void f();`, * [enumeration](../enum "cpp/language/enum"): `enum [[maybe_unused]] E {};`, * enumerator: `enum { A [[maybe_unused]], B [[maybe_unused]] = 42 };`, * [structured binding](../structured_binding "cpp/language/structured binding"): `[[maybe_unused]] auto [a, b] = [std::make\_pair](http://en.cppreference.com/w/cpp/utility/pair/make_pair)(42, 0.23);`. For entites declared `[[maybe_unused]]`, if the entities or their structured bindings are unused, the warning on unused entities issued by the compiler is suppressed. ### Example ``` #include <cassert> [[maybe_unused]] void f([[maybe_unused]] bool thing1, [[maybe_unused]] bool thing2) { [[maybe_unused]] bool b = thing1 && thing2; assert(b); // in release mode, assert is compiled out, and b is unused // no warning because it is declared [[maybe_unused]] } // parameters thing1 and thing2 are not used, no warning int main() {} ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [CWG 2360](https://cplusplus.github.io/CWG/issues/2360.html) | C++17 | could not apply `[[maybe_unused]]` to structured bindings | allowed | ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/attributes/maybe_unused "c/language/attributes/maybe unused") for `maybe_unused` |
programming_docs
cpp C++ attribute: deprecated (since C++14) C++ attribute: deprecated (since C++14) ======================================= Indicates that the name or entity declared with this attribute is [deprecated](https://en.wikipedia.org/wiki/Deprecation "enwiki:Deprecation"), that is, the use is allowed, but discouraged for some reason. ### Syntax | | | | | --- | --- | --- | | `[[deprecated``]]` | (1) | | | `[[deprecated(` string-literal `)]]` | (2) | | | | | | | --- | --- | --- | | string-literal | - | text that could be used to explain the rationale for deprecation and/or to suggest a replacing entity | ### Explanation Indicates that the use of the name or entity declared with this attribute is allowed, but discouraged for some reason. Compilers typically issue warnings on such uses. The string-literal, if specified, is usually included in the warnings. This attribute is allowed in declarations of the following names or entities: * [class/struct/union](../classes "cpp/language/classes"): `struct [[deprecated]] S;`, * [typedef-name](../typedef "cpp/language/typedef"), including those declared by [alias declaration](../type_alias "cpp/language/type alias"): `[[deprecated]] typedef S* PS;`, `using PS [[deprecated]] = S*;`, * variable, including [static data member](../static "cpp/language/static"): `[[deprecated]] int x;`, * [non-static data member](../data_members "cpp/language/data members"): `union U { [[deprecated]] int n; };`, * [function](../function "cpp/language/function"): `[[deprecated]] void f();`, * [namespace](../namespace "cpp/language/namespace"): `namespace [[deprecated]] NS { int x; }` * [enumeration](../enum "cpp/language/enum"): `enum [[deprecated]] E {};`, * enumerator: `enum { A [[deprecated]], B [[deprecated]] = 42 };`. (since C++17) * [template specialization](../template_specialization "cpp/language/template specialization"): `template<> struct [[deprecated]] X<int> {};` A name declared non-deprecated may be redeclared deprecated. A name declared deprecated cannot be un-deprecated by redeclaring it without this attribute. ### Example ``` #include <iostream> [[deprecated]] void TriassicPeriod() { std::clog << "Triassic Period: [251.9 - 208.5] million years ago.\n"; } [[deprecated("Use NeogenePeriod() instead.")]] void JurassicPeriod() { std::clog << "Jurassic Period: [201.3 - 152.1] million years ago.\n"; } [[deprecated("Use calcSomethingDifferently(int).")]] int calcSomething(int x) { return x * 2; } int main() { TriassicPeriod(); JurassicPeriod(); } ``` Possible output: ``` Triassic Period: [251.9 - 208.5] million years ago. Jurassic Period: [201.3 - 152.1] million years ago. main.cpp:20:5: warning: 'TriassicPeriod' is deprecated [-Wdeprecated-declarations] TriassicPeriod(); ^ main.cpp:3:3: note: 'TriassicPeriod' has been explicitly marked deprecated here [[deprecated]] ^ main.cpp:21:5: warning: 'JurassicPeriod' is deprecated: Use NeogenePeriod() instead [-Wdeprecated-declarations] JurassicPeriod(); ^ main.cpp:8:3: note: 'JurassicPeriod' has been explicitly marked deprecated here [[deprecated("Use NeogenePeriod() instead")]] ^ 2 warnings generated. ``` ### See also | | | --- | | [C documentation](https://en.cppreference.com/w/c/language/attributes/deprecated "c/language/attributes/deprecated") for `deprecated` | cpp C++ attribute: no_unique_address (since C++20) C++ attribute: no\_unique\_address (since C++20) ================================================ Allows this data member to be overlapped with other non-static data members or base class subobjects of its class. ### Syntax | | | | | --- | --- | --- | | `[[no_unique_address]]` | | | ### Explanation Applies to the name being declared in the declaration of a non-static data member that's not a bit field. Makes this member subobject [potentially-overlapping](../object#Subobjects "cpp/language/object"), i.e., allows this member to be overlapped with other non-static data members or base class subobjects of its class. This means that if the member has an empty class type (e.g. stateless allocator), the compiler may optimise it to occupy no space, just like if it were an [empty base](../ebo "cpp/language/ebo"). If the member is not empty, any tail padding in it may be also reused to store other data members. ### Example ``` #include <iostream> struct Empty {}; // empty class struct X { int i; Empty e; }; struct Y { int i; [[no_unique_address]] Empty e; }; struct Z { char c; [[no_unique_address]] Empty e1, e2; }; struct W { char c[2]; [[no_unique_address]] Empty e1, e2; }; int main() { // the size of any object of empty class type is at least 1 static_assert(sizeof(Empty) >= 1); // at least one more byte is needed to give e a unique address static_assert(sizeof(X) >= sizeof(int) + 1); // empty member optimized out std::cout << "sizeof(Y) == sizeof(int) is " << std::boolalpha << (sizeof(Y) == sizeof(int)) << '\n'; // e1 and e2 cannot share the same address because they have the // same type, even though they are marked with [[no_unique_address]]. // However, either may share address with c. static_assert(sizeof(Z) >= 2); // e1 and e2 cannot have the same address, but one of them can share with // c[0] and the other with c[1] std::cout << "sizeof(W) == 2 is " << (sizeof(W) == 2) << '\n'; } ``` Possible output: ``` sizeof(Y) == sizeof(int) is true sizeof(W) == 2 is true ``` cpp std::filesystem::hard_link_count std::filesystem::hard\_link\_count ================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` std::uintmax_t hard_link_count( const std::filesystem::path& p ); std::uintmax_t hard_link_count( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (1) | (since C++17) | Returns the number of hard links for the filesystem object identified by path `p`. The non-throwing overload returns `static_cast<uintmax_t>(-1)` on errors. ### Parameters | | | | | --- | --- | --- | | p | - | path to examine | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value The number of hard links for `p`. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { // On a POSIX-style filesystem, each directory has at least 2 hard links: // itself and the special member pathname "." fs::path p = fs::current_path(); std::cout << "Number of hard links for current path is " << fs::hard_link_count(p) << '\n'; // each ".." is a hard link to the parent directory, so the total number // of hard links for any directory is 2 plus number of direct subdirectories p = fs::current_path() / ".."; // each dot-dot is a hard link to parent std::cout << "Number of hard links for .. is " << fs::hard_link_count(p) << '\n'; } ``` Possible output: ``` Number of hard links for current path is 2 Number of hard links for .. is 3 ``` ### See also | | | | --- | --- | | [create\_hard\_link](create_hard_link "cpp/filesystem/create hard link") (C++17) | creates a hard link (function) | | [hard\_link\_count](directory_entry/hard_link_count "cpp/filesystem/directory entry/hard link count") | returns the number of hard links referring to the file to which the directory entry refers (public member function of `std::filesystem::directory_entry`) | cpp std::filesystem::is_character_file std::filesystem::is\_character\_file ==================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool is_character_file( std::filesystem::file_status s ) noexcept; ``` | (1) | (since C++17) | | ``` bool is_character_file( const std::filesystem::path& p ); bool is_character_file( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (2) | (since C++17) | Checks if the given file status or path corresponds to a character special file, as if determined by POSIX [`S_ISCHR`](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html). Examples of character special files are character devices such as `/dev/null`, `/dev/tty`, `/dev/audio`, or `/dev/nvram` on Linux. 1) Equivalent to `s.type() == file_type::character`. 2) Equivalent to `is_character_file(status(p))` or `is_character_file(status(p, ec))` respectively ### Parameters | | | | | --- | --- | --- | | s | - | file status to check | | p | - | path to examine | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the file indicated by `p` or if the type indicated `s` refers to a character device, `false` otherwise. The non-throwing overload returns `false` if an error occurs. ### Exceptions 2) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <filesystem> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> namespace fs = std::filesystem; void demo_status(const fs::path& p, fs::file_status s) { std::cout << p; // alternative: switch(s.type()) { case fs::file_type::regular: ...} if(fs::is_regular_file(s)) std::cout << " is a regular file\n"; if(fs::is_directory(s)) std::cout << " is a directory\n"; if(fs::is_block_file(s)) std::cout << " is a block device\n"; if(fs::is_character_file(s)) std::cout << " is a character device\n"; if(fs::is_fifo(s)) std::cout << " is a named IPC pipe\n"; if(fs::is_socket(s)) std::cout << " is a named IPC socket\n"; if(fs::is_symlink(s)) std::cout << " is a symlink\n"; if(!fs::exists(s)) std::cout << " does not exist\n"; } int main() { // create files of different kinds fs::create_directory("sandbox"); std::ofstream("sandbox/file"); // create regular file fs::create_directory("sandbox/dir"); mkfifo("sandbox/pipe", 0644); sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, "sandbox/sock"); int fd = socket(PF_UNIX, SOCK_STREAM, 0); bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof addr); fs::create_symlink("file", "sandbox/symlink"); // demo different status accessors for(auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it) demo_status(*it, it->symlink_status()); // use cached status from directory entry demo_status("/dev/null", fs::status("/dev/null")); // direct calls to status demo_status("/dev/sda", fs::status("/dev/sda")); demo_status("sandbox/no", fs::status("/sandbox/no")); // cleanup close(fd); fs::remove_all("sandbox"); } ``` Possible output: ``` "sandbox/file" is a regular file "sandbox/dir" is a directory "sandbox/pipe" is a named IPC pipe "sandbox/sock" is a named IPC socket "sandbox/symlink" is a symlink "/dev/null" is a character device "/dev/sda" is a block device "sandbox/no" does not exist ``` ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [file\_status](file_status "cpp/filesystem/file status") (C++17) | represents file type and permissions (class) | | [status\_known](status_known "cpp/filesystem/status known") (C++17) | checks whether file status is known (function) | | [is\_block\_file](is_block_file "cpp/filesystem/is block file") (C++17) | checks whether the given path refers to block device (function) | | [is\_directory](is_directory "cpp/filesystem/is directory") (C++17) | checks whether the given path refers to a directory (function) | | [is\_fifo](is_fifo "cpp/filesystem/is fifo") (C++17) | checks whether the given path refers to a named pipe (function) | | [is\_other](is_other "cpp/filesystem/is other") (C++17) | checks whether the argument refers to an *other* file (function) | | [is\_regular\_file](is_regular_file "cpp/filesystem/is regular file") (C++17) | checks whether the argument refers to a regular file (function) | | [is\_socket](is_socket "cpp/filesystem/is socket") (C++17) | checks whether the argument refers to a named IPC socket (function) | | [is\_symlink](is_symlink "cpp/filesystem/is symlink") (C++17) | checks whether the argument refers to a symbolic link (function) | | [exists](exists "cpp/filesystem/exists") (C++17) | checks whether path refers to existing file system object (function) | | [is\_character\_file](directory_entry/is_character_file "cpp/filesystem/directory entry/is character file") | checks whether the directory entry refers to a character device (public member function of `std::filesystem::directory_entry`) | cpp std::filesystem::status_known std::filesystem::status\_known ============================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool status_known( std::filesystem::file_status s ) noexcept; ``` | (1) | (since C++17) | Checks if the given file status is known, equivalent to `s.type() != file_type::none`. ### Parameters | | | | | --- | --- | --- | | s | - | file status to check | ### Return value `true` if the given file status is a known file status. ### Notes Despite the name, the function checks for the file status of `[file\_type::none](file_type "cpp/filesystem/file type")` (meaning an error occurred), not `[file\_type::unknown](file_type "cpp/filesystem/file type")` (meaning file exists, but its type cannot be determined). ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [statussymlink\_status](directory_entry/status "cpp/filesystem/directory entry/status") | status of the file designated by this directory entrysymlink\_status of the file designated by this directory entry (public member function of `std::filesystem::directory_entry`) | cpp std::filesystem::file_time_type std::filesystem::file\_time\_type ================================= | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` using file_time_type = std::chrono::time_point</*trivial-clock*/>; ``` | | (since C++17) (until C++20) | | ``` using file_time_type = std::chrono::time_point<std::chrono::file_clock>; ``` | | (since C++20) | Represents file time. | | | | --- | --- | | `trivial-clock` is an implementation-defined type that satisfies [TrivialClock](../named_req/trivialclock "cpp/named req/TrivialClock") and is sufficient to represent the resolution and range of the file time values offered by the filesystem. | (until C++20) | ### Example ``` #include <chrono> #include <filesystem> #include <format> #include <fstream> #include <iostream> using namespace std::chrono_literals; int main() { auto p = std::filesystem::temp_directory_path() / "example.bin"; std::ofstream(p.c_str()).put('a'); // create file std::filesystem::file_time_type ftime = std::filesystem::last_write_time(p); std::cout << std::format("File write time is {}\n", ftime); std::filesystem::last_write_time(p, ftime + 1h); // move file write time 1 hour to the future ftime = std::filesystem::last_write_time(p); // read back from the filesystem std::cout << std::format("File write time is {}\n", ftime); std::filesystem::remove(p); } ``` Possible output: ``` File write time is Sun May 9 23:29:58 2021 File write time is Mon May 10 00:29:58 2021 ``` ### See also | | | | --- | --- | | [last\_write\_time](last_write_time "cpp/filesystem/last write time") (C++17) | gets or sets the time of the last data modification (function) | cpp std::filesystem::is_fifo std::filesystem::is\_fifo ========================= | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool is_fifo( std::filesystem::file_status s ) noexcept; ``` | (1) | (since C++17) | | ``` bool is_fifo( const std::filesystem::path& p ); bool is_fifo( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (2) | (since C++17) | Checks if the given file status or path corresponds to a FIFO or pipe file as if determined by POSIX [`S_ISFIFO`](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html). 1) Equivalent to `s.type() == file_type::fifo`. 2) Equivalent to `is_fifo(status(p))` or `is_fifo(status(p, ec))` respectively. ### Parameters | | | | | --- | --- | --- | | s | - | file status to check | | p | - | path to query | | ec | - | error code to modify in case of errors | ### Return value `true` if the file indicated by `p` or if the type indicated `s` refers to a FIFO pipe, `false` otherwise. The non-throwing overload returns `false` if an error occurs. ### Exceptions 2) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <filesystem> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> namespace fs = std::filesystem; void demo_status(const fs::path& p, fs::file_status s) { std::cout << p; // alternative: switch(s.type()) { case fs::file_type::regular: ...} if(fs::is_regular_file(s)) std::cout << " is a regular file\n"; if(fs::is_directory(s)) std::cout << " is a directory\n"; if(fs::is_block_file(s)) std::cout << " is a block device\n"; if(fs::is_character_file(s)) std::cout << " is a character device\n"; if(fs::is_fifo(s)) std::cout << " is a named IPC pipe\n"; if(fs::is_socket(s)) std::cout << " is a named IPC socket\n"; if(fs::is_symlink(s)) std::cout << " is a symlink\n"; if(!fs::exists(s)) std::cout << " does not exist\n"; } int main() { // create files of different kinds fs::create_directory("sandbox"); std::ofstream("sandbox/file"); // create regular file fs::create_directory("sandbox/dir"); mkfifo("sandbox/pipe", 0644); sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, "sandbox/sock"); int fd = socket(PF_UNIX, SOCK_STREAM, 0); bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof addr); fs::create_symlink("file", "sandbox/symlink"); // demo different status accessors for(auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it) demo_status(*it, it->symlink_status()); // use cached status from directory entry demo_status("/dev/null", fs::status("/dev/null")); // direct calls to status demo_status("/dev/sda", fs::status("/dev/sda")); demo_status("sandbox/no", fs::status("/sandbox/no")); // cleanup close(fd); fs::remove_all("sandbox"); } ``` Possible output: ``` "sandbox/file" is a regular file "sandbox/dir" is a directory "sandbox/pipe" is a named IPC pipe "sandbox/sock" is a named IPC socket "sandbox/symlink" is a symlink "/dev/null" is a character device "/dev/sda" is a block device "sandbox/no" does not exist ``` ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [file\_status](file_status "cpp/filesystem/file status") (C++17) | represents file type and permissions (class) | | [status\_known](status_known "cpp/filesystem/status known") (C++17) | checks whether file status is known (function) | | [is\_block\_file](is_block_file "cpp/filesystem/is block file") (C++17) | checks whether the given path refers to block device (function) | | [is\_character\_file](is_character_file "cpp/filesystem/is character file") (C++17) | checks whether the given path refers to a character device (function) | | [is\_directory](is_directory "cpp/filesystem/is directory") (C++17) | checks whether the given path refers to a directory (function) | | [is\_other](is_other "cpp/filesystem/is other") (C++17) | checks whether the argument refers to an *other* file (function) | | [is\_regular\_file](is_regular_file "cpp/filesystem/is regular file") (C++17) | checks whether the argument refers to a regular file (function) | | [is\_socket](is_socket "cpp/filesystem/is socket") (C++17) | checks whether the argument refers to a named IPC socket (function) | | [is\_symlink](is_symlink "cpp/filesystem/is symlink") (C++17) | checks whether the argument refers to a symbolic link (function) | | [exists](exists "cpp/filesystem/exists") (C++17) | checks whether path refers to existing file system object (function) | | [is\_fifo](directory_entry/is_fifo "cpp/filesystem/directory entry/is fifo") | checks whether the directory entry refers to a named pipe (public member function of `std::filesystem::directory_entry`) |
programming_docs
cpp std::filesystem::exists std::filesystem::exists ======================= | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool exists( std::filesystem::file_status s ) noexcept; ``` | (1) | (since C++17) | | ``` bool exists( const std::filesystem::path& p ); bool exists( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (2) | (since C++17) | Checks if the given file status or path corresponds to an existing file or directory. 1) Equivalent to `status_known(s) && s.type() != file_type::not_found`. 2) Let `s` be a `[std::filesystem::file\_status](http://en.cppreference.com/w/cpp/filesystem/file_status)` determined as if by `status(p)` or `status(p, ec)` (symlinks are followed), respectively. Returns `exists(s)`. The non-throwing overload calls `ec.clear()` if `status_known(s)`. ### Parameters | | | | | --- | --- | --- | | s | - | file status to check | | p | - | path to examine | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the given path or file status corresponds to an existing file or directory, `false` otherwise. ### Exceptions 2) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes The information provided by this function is usually also provided as a byproduct of directory iteration. During directory iteration, calling `exists(*iterator)` is less efficient than `exists(iterator->status())`. ### Example ``` #include <iostream> #include <fstream> #include <cstdint> #include <filesystem> namespace fs = std::filesystem; void demo_exists(const fs::path& p, fs::file_status s = fs::file_status{}) { std::cout << p; if(fs::status_known(s) ? fs::exists(s) : fs::exists(p)) std::cout << " exists\n"; else std::cout << " does not exist\n"; } int main() { const fs::path sandbox{"sandbox"}; fs::create_directory(sandbox); std::ofstream{sandbox/"file"}; // create regular file fs::create_symlink("non-existing", sandbox/"symlink"); demo_exists(sandbox); for (const auto& entry : fs::directory_iterator(sandbox)) demo_exists(entry, entry.status()); // use cached status from directory entry fs::remove_all(sandbox); } ``` Output: ``` "sandbox" exists "sandbox/symlink" does not exist "sandbox/file" exists ``` ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [file\_status](file_status "cpp/filesystem/file status") (C++17) | represents file type and permissions (class) | | [exists](directory_entry/exists "cpp/filesystem/directory entry/exists") | checks whether directory entry refers to existing file system object (public member function of `std::filesystem::directory_entry`) | cpp std::filesystem::status, std::filesystem::symlink_status std::filesystem::status, std::filesystem::symlink\_status ========================================================= | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` std::filesystem::file_status status( const std::filesystem::path& p ); std::filesystem::file_status status( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (1) | (since C++17) | | ``` std::filesystem::file_status symlink_status( const std::filesystem::path& p ); std::filesystem::file_status symlink_status( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (2) | (since C++17) | 1) Determines the type and attributes of the filesystem object identified by `p` as if by POSIX [`stat`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/stat.html) (symlinks are followed to their targets). In the following description, `prms` is the result of `(m & perms::mask)`, where `m` is obtained as if by taking `st_mode` from the POSIX `struct stat` and converting it to the type `[std::filesystem::perms](http://en.cppreference.com/w/cpp/filesystem/perms)`. * If `p` is a regular file (as if by POSIX `S_ISREG`), returns `file_status(file_type::regular, prms)`. * If `p` is a directory (as if by POSIX `S_ISDIR`), returns `file_status(file_type::directory, prms)` * If `p` is a block special file (as if by POSIX `S_ISBLK`), returns `file_status(file_type::block, prms)` * If `p` is a character special file (as if by POSIX `S_ISCHR`), returns `file_status(file_type::character, prms)` * If `p` is a fifo or pipe file (as if by POSIX `S_ISFIFO`), returns `file_status(file_type::fifo, prms)` * If `p` is a socket (as if by POSIX `S_ISSOCK`), returns `file_status(file_type::socket, prms)` * If `p` has an implementation-defined file type, returns `file_status(file_type::A, prms)` where `A` is the implementation-defined [`file_type`](file_type "cpp/filesystem/file type") constant for that type. * If `p` does not exist, returns `file_status(file_type::not_found)` * If `p` exists but file attributes cannot be determined, e.g. due to lack of permissions, returns `file_status(file_type::unknown)` * If errors prevent even knowing whether `p` exists, the non-throwing overload sets `ec` and returns `file_status(file_type::none)`, and the throwing overload throws `filesystem_error` * Otherwise, returns `file_status(file_type::unknown, prms)` 2) Same as (1) except that the behavior is as if the POSIX [`lstat`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/lstat.html) is used (symlinks are not followed): * If `p` is a symlink, returns `file_status(file_type::symlink)` ### Parameters | | | | | --- | --- | --- | | p | - | path to examine | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value The file status (a `[filesystem::file\_status](file_status "cpp/filesystem/file status")` object). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes The information provided by this function is usually also provided as a byproduct of directory iteration, and may be obtained by the member functions of `[filesystem::directory\_entry](directory_entry "cpp/filesystem/directory entry")`. During directory iteration, calling `status` again is unnecessary. ### Example ``` #include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <filesystem> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> namespace fs = std::filesystem; void demo_status(const fs::path& p, fs::file_status s) { std::cout << p; // alternative: switch(s.type()) { case fs::file_type::regular: ...} if(fs::is_regular_file(s)) std::cout << " is a regular file\n"; if(fs::is_directory(s)) std::cout << " is a directory\n"; if(fs::is_block_file(s)) std::cout << " is a block device\n"; if(fs::is_character_file(s)) std::cout << " is a character device\n"; if(fs::is_fifo(s)) std::cout << " is a named IPC pipe\n"; if(fs::is_socket(s)) std::cout << " is a named IPC socket\n"; if(fs::is_symlink(s)) std::cout << " is a symlink\n"; if(!fs::exists(s)) std::cout << " does not exist\n"; } int main() { // create files of different kinds fs::create_directory("sandbox"); std::ofstream("sandbox/file"); // create regular file fs::create_directory("sandbox/dir"); mkfifo("sandbox/pipe", 0644); sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, "sandbox/sock"); int fd = socket(PF_UNIX, SOCK_STREAM, 0); bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof addr); fs::create_symlink("file", "sandbox/symlink"); // demo different status accessors for(auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it) demo_status(*it, it->symlink_status()); // use cached status from directory entry demo_status("/dev/null", fs::status("/dev/null")); // direct calls to status demo_status("/dev/sda", fs::status("/dev/sda")); demo_status("sandbox/no", fs::status("/sandbox/no")); // cleanup close(fd); fs::remove_all("sandbox"); } ``` Possible output: ``` "sandbox/file" is a regular file "sandbox/dir" is a directory "sandbox/pipe" is a named IPC pipe "sandbox/sock" is a named IPC socket "sandbox/symlink" is a symlink "/dev/null" is a character device "/dev/sda" is a block device "sandbox/no" does not exist ``` ### See also | | | | --- | --- | | [file\_status](file_status "cpp/filesystem/file status") (C++17) | represents file type and permissions (class) | | [status\_known](status_known "cpp/filesystem/status known") (C++17) | checks whether file status is known (function) | | [is\_block\_file](is_block_file "cpp/filesystem/is block file") (C++17) | checks whether the given path refers to block device (function) | | [is\_character\_file](is_character_file "cpp/filesystem/is character file") (C++17) | checks whether the given path refers to a character device (function) | | [is\_directory](is_directory "cpp/filesystem/is directory") (C++17) | checks whether the given path refers to a directory (function) | | [is\_fifo](is_fifo "cpp/filesystem/is fifo") (C++17) | checks whether the given path refers to a named pipe (function) | | [is\_other](is_other "cpp/filesystem/is other") (C++17) | checks whether the argument refers to an *other* file (function) | | [is\_regular\_file](is_regular_file "cpp/filesystem/is regular file") (C++17) | checks whether the argument refers to a regular file (function) | | [is\_socket](is_socket "cpp/filesystem/is socket") (C++17) | checks whether the argument refers to a named IPC socket (function) | | [is\_symlink](is_symlink "cpp/filesystem/is symlink") (C++17) | checks whether the argument refers to a symbolic link (function) | | [exists](exists "cpp/filesystem/exists") (C++17) | checks whether path refers to existing file system object (function) | | [statussymlink\_status](directory_entry/status "cpp/filesystem/directory entry/status") | status of the file designated by this directory entrysymlink\_status of the file designated by this directory entry (public member function of `std::filesystem::directory_entry`) | cpp std::filesystem::create_directory, std::filesystem::create_directories std::filesystem::create\_directory, std::filesystem::create\_directories ======================================================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool create_directory( const std::filesystem::path& p ); bool create_directory( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (1) | (since C++17) | | ``` bool create_directory( const std::filesystem::path& p, const std::filesystem::path& existing_p ); bool create_directory( const std::filesystem::path& p, const std::filesystem::path& existing_p, std::error_code& ec ) noexcept; ``` | (2) | (since C++17) | | ``` bool create_directories( const std::filesystem::path& p ); bool create_directories( const std::filesystem::path& p, std::error_code& ec ); ``` | (3) | (since C++17) | 1) Creates the directory `p` as if by POSIX [`mkdir()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdir.html) with a second argument of `static\_cast<int>([std::filesystem::perms::all](http://en.cppreference.com/w/cpp/filesystem/perms))` (the parent directory must already exist). If the function fails because `p` resolves to an existing directory, no error is reported. Otherwise on failure an error is reported. 2) Same as (1), except that the attributes of the new directory are copied from `existing_p` (which must be a directory that exists). It is OS-dependent which attributes are copied: on POSIX systems, the attributes are copied as if by ``` stat(existing_p.c_str(), &attributes_stat) mkdir(p.c_str(), attributes_stat.st_mode) ``` On Windows OS, no attributes of `existing_p` are copied. 3) Executes (1) for every element of `p` that does not already exist. If `p` already exists, the function does nothing (this condition is not treated as an error). ### Parameters | | | | | --- | --- | --- | | p | - | the path to the new directory to create | | existing\_p | - | the path to a directory to copy the attributes from | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if a directory was created for the directory `p` resolves to, `false` otherwise. ### Exceptions 1,3) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. 2) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument, `existing_p` as the second path argument, and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes The attribute-preserving overload (2) is implicitly invoked by [`copy()`](copy "cpp/filesystem/copy") when recursively copying directories. Its equivalent in boost.filesystem is [`copy_directory`](http://www.boost.org/doc/libs/1_57_0/libs/filesystem/doc/reference.html#copy_directory) (with argument order reversed). ### Example ``` #include <iostream> #include <fstream> #include <cstdlib> #include <filesystem> namespace fs = std::filesystem; int main() { fs::current_path(fs::temp_directory_path()); fs::create_directories("sandbox/1/2/a"); fs::create_directory("sandbox/1/2/b"); fs::permissions("sandbox/1/2/b", fs::perms::others_all, fs::perm_options::remove); fs::create_directory("sandbox/1/2/c", "sandbox/1/2/b"); std::system("ls -l sandbox/1/2"); std::system("tree sandbox"); fs::remove_all("sandbox"); } ``` Possible output: ``` drwxr-xr-x 2 user group 4096 Apr 15 09:33 a drwxr-x--- 2 user group 4096 Apr 15 09:33 b drwxr-x--- 2 user group 4096 Apr 15 09:33 c sandbox └── 1 └── 2 ├── a ├── b └── c ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2935](https://cplusplus.github.io/LWG/issue2935) | C++17 | error if target already exists but isn't a directory | not error | | [LWG 3014](https://cplusplus.github.io/LWG/issue3014) | C++17 | `error_code` overload of `create_directories` marked noexcept but can allocate memory | noexcept removed | | [P1164R1](https://wg21.link/P1164R1) | C++17 | creation failure caused by an existing non-directory file is not an error | made error | ### See also | | | | --- | --- | | [create\_symlinkcreate\_directory\_symlink](create_symlink "cpp/filesystem/create symlink") (C++17)(C++17) | creates a symbolic link (function) | | [copy](copy "cpp/filesystem/copy") (C++17) | copies files or directories (function) | | [perms](perms "cpp/filesystem/perms") (C++17) | identifies file system permissions (enum) | cpp std::filesystem::directory_options std::filesystem::directory\_options =================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` enum class directory_options { none = /* unspecified */, follow_directory_symlink = /* unspecified */, skip_permission_denied = /* unspecified */ }; ``` | | (since C++17) | This type represents available options that control the behavior of the [`directory_iterator`](directory_iterator "cpp/filesystem/directory iterator") and [`recursive_directory_iterator`](recursive_directory_iterator "cpp/filesystem/recursive directory iterator"). `directory_options` satisfies the requirements of [BitmaskType](../named_req/bitmasktype "cpp/named req/BitmaskType") (which means the bitwise operators `operator&`, `operator|`, `operator^`, `operator~`, `operator&=`, `operator|=`, and `operator^=` are defined for this type). `none` represents the empty bitmask; every other enumerator represents a distinct bitmask element. ### Member constants | Member constant | Meaning | | --- | --- | | `none` | (Default) Skip directory symlinks, permission denied is error. | | `follow_directory_symlink` | Follow rather than skip directory symlinks. | | `skip_permission_denied` | Skip directories that would otherwise result in permission denied errors. | ### Example ### See also | | | | --- | --- | | [(constructor)](directory_iterator/directory_iterator "cpp/filesystem/directory iterator/directory iterator") | constructs a directory iterator (public member function of `std::filesystem::directory_iterator`) | | [(constructor)](recursive_directory_iterator/recursive_directory_iterator "cpp/filesystem/recursive directory iterator/recursive directory iterator") | constructs a recursive directory iterator (public member function of `std::filesystem::recursive_directory_iterator`) | cpp std::filesystem::temp_directory_path std::filesystem::temp\_directory\_path ====================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` path temp_directory_path(); path temp_directory_path( std::error_code& ec ); ``` | (1) | (since C++17) | Returns the directory location suitable for temporary files. ### Parameters (none). ### Return value A directory suitable for temporary files. The path is guaranteed to exist and to be a directory. The overload that takes `error_code&` argument returns an empty path on error. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `path to be returned` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes On POSIX systems, the path may be the one specified in the environment variables `TMPDIR`, `TMP`, `TEMP`, `TEMPDIR`, and, if none of them are specified, the path `"/tmp"` is returned. On Windows systems, the path is typically the one returned by `GetTempPath`. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { std::cout << "Temp directory is " << fs::temp_directory_path() << '\n'; } ``` Possible output: ``` Temp directory is "C:\Windows\TEMP\" ``` ### See also | | | | --- | --- | | [tmpfile](../io/c/tmpfile "cpp/io/c/tmpfile") | creates and opens a temporary, auto-removing file (function) | | [current\_path](current_path "cpp/filesystem/current path") (C++17) | returns or sets the current working directory (function) |
programming_docs
cpp std::filesystem::perm_options std::filesystem::perm\_options ============================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` enum class perm_options { replace = /* unspecified */, add = /* unspecified */, remove = /* unspecified */, nofollow = /* unspecified */ }; ``` | | (since C++17) | This type represents available options that control the behavior of the function `[std::filesystem::permissions()](permissions "cpp/filesystem/permissions")`. `perm_options` satisfies the requirements of [BitmaskType](../named_req/bitmasktype "cpp/named req/BitmaskType") (which means the bitwise operators `operator&`, `operator|`, `operator^`, `operator~`, `operator&=`, `operator|=`, and `operator^=` are defined for this type). ### Member constants At most one of `add`, `remove`, `replace` may be present, otherwise the behavior of the permissions function is undefined. | Member constant | Meaning | | --- | --- | | `replace` | Permissions will be completely replaced by the argument to `permissions()` (default behavior) | | `add` | permissions will be replaced by the bitwise OR of the argument and the current permissions | | `remove` | permissions will be replaced by the bitwise AND of the negated argument and current permissions | | `nofollow` | permissions will be changed on the symlink itself, rather than on the file it resolves to | ### Example ``` #include <fstream> #include <bitset> #include <iostream> #include <filesystem> namespace fs = std::filesystem; void demo_perms(fs::perms p) { std::cout << ((p & fs::perms::owner_read) != fs::perms::none ? "r" : "-") << ((p & fs::perms::owner_write) != fs::perms::none ? "w" : "-") << ((p & fs::perms::owner_exec) != fs::perms::none ? "x" : "-") << ((p & fs::perms::group_read) != fs::perms::none ? "r" : "-") << ((p & fs::perms::group_write) != fs::perms::none ? "w" : "-") << ((p & fs::perms::group_exec) != fs::perms::none ? "x" : "-") << ((p & fs::perms::others_read) != fs::perms::none ? "r" : "-") << ((p & fs::perms::others_write) != fs::perms::none ? "w" : "-") << ((p & fs::perms::others_exec) != fs::perms::none ? "x" : "-") << '\n'; } int main() { std::ofstream("test.txt"); // create file std::cout << "Created file with permissions: "; demo_perms(fs::status("test.txt").permissions()); fs::permissions("test.txt", fs::perms::owner_all | fs::perms::group_all, fs::perm_options::add); std::cout << "After adding u+rwx and g+rwx: "; demo_perms(fs::status("test.txt").permissions()); fs::remove("test.txt"); } ``` Possible output: ``` Created file with permissions: rw-r--r-- After adding u+rwx and g+wrx: rwxrwxr-- ``` ### See also | | | | --- | --- | | [permissions](permissions "cpp/filesystem/permissions") (C++17) | modifies file access permissions (function) | | [perms](perms "cpp/filesystem/perms") (C++17) | identifies file system permissions (enum) | cpp std::filesystem::is_socket std::filesystem::is\_socket =========================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool is_socket( std::filesystem::file_status s ) noexcept; ``` | (1) | (since C++17) | | ``` bool is_socket( const std::filesystem::path& p ); bool is_socket( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (2) | (since C++17) | Checks if the given file status or path corresponds to a named IPC socket, as if determined by the POSIX [`S_IFSOCK`](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html). 1) Equivalent to `s.type() == file_type::socket`. 2) Equivalent to `is_socket(status(p))` or `is_socket(status(p, ec))`. ### Parameters | | | | | --- | --- | --- | | s | - | file status to check | | p | - | path to examine | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the file indicated by `p` or if the type indicated `s` refers to a named socket. The non-throwing overload returns `false` if an error occurs. ### Exceptions 2) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes Named sockets are UNIX domain sockets constructed with [`socket`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/socket.html) and [`bind`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/bind.html) POSIX APIs, which may be used for advanced interprocess communication. In particular, they may be used to transport open file descriptors from one running process to another. ### Example ``` #include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <filesystem> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> namespace fs = std::filesystem; void demo_status(const fs::path& p, fs::file_status s) { std::cout << p; // alternative: switch(s.type()) { case fs::file_type::regular: ...} if(fs::is_regular_file(s)) std::cout << " is a regular file\n"; if(fs::is_directory(s)) std::cout << " is a directory\n"; if(fs::is_block_file(s)) std::cout << " is a block device\n"; if(fs::is_character_file(s)) std::cout << " is a character device\n"; if(fs::is_fifo(s)) std::cout << " is a named IPC pipe\n"; if(fs::is_socket(s)) std::cout << " is a named IPC socket\n"; if(fs::is_symlink(s)) std::cout << " is a symlink\n"; if(!fs::exists(s)) std::cout << " does not exist\n"; } int main() { // create files of different kinds fs::create_directory("sandbox"); std::ofstream("sandbox/file"); // create regular file fs::create_directory("sandbox/dir"); mkfifo("sandbox/pipe", 0644); sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, "sandbox/sock"); int fd = socket(PF_UNIX, SOCK_STREAM, 0); bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof addr); fs::create_symlink("file", "sandbox/symlink"); // demo different status accessors for(auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it) demo_status(*it, it->symlink_status()); // use cached status from directory entry demo_status("/dev/null", fs::status("/dev/null")); // direct calls to status demo_status("/dev/sda", fs::status("/dev/sda")); demo_status("sandbox/no", fs::status("/sandbox/no")); // cleanup close(fd); fs::remove_all("sandbox"); } ``` Possible output: ``` "sandbox/file" is a regular file "sandbox/dir" is a directory "sandbox/pipe" is a named IPC pipe "sandbox/sock" is a named IPC socket "sandbox/symlink" is a symlink "/dev/null" is a character device "/dev/sda" is a block device "sandbox/no" does not exist ``` ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [file\_status](file_status "cpp/filesystem/file status") (C++17) | represents file type and permissions (class) | | [status\_known](status_known "cpp/filesystem/status known") (C++17) | checks whether file status is known (function) | | [is\_block\_file](is_block_file "cpp/filesystem/is block file") (C++17) | checks whether the given path refers to block device (function) | | [is\_character\_file](is_character_file "cpp/filesystem/is character file") (C++17) | checks whether the given path refers to a character device (function) | | [is\_directory](is_directory "cpp/filesystem/is directory") (C++17) | checks whether the given path refers to a directory (function) | | [is\_fifo](is_fifo "cpp/filesystem/is fifo") (C++17) | checks whether the given path refers to a named pipe (function) | | [is\_other](is_other "cpp/filesystem/is other") (C++17) | checks whether the argument refers to an *other* file (function) | | [is\_regular\_file](is_regular_file "cpp/filesystem/is regular file") (C++17) | checks whether the argument refers to a regular file (function) | | [is\_symlink](is_symlink "cpp/filesystem/is symlink") (C++17) | checks whether the argument refers to a symbolic link (function) | | [exists](exists "cpp/filesystem/exists") (C++17) | checks whether path refers to existing file system object (function) | | [is\_socket](directory_entry/is_socket "cpp/filesystem/directory entry/is socket") | checks whether the directory entry refers to a named IPC socket (public member function of `std::filesystem::directory_entry`) | cpp std::filesystem::rename std::filesystem::rename ======================= | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` void rename(const std::filesystem::path& old_p, const std::filesystem::path& new_p); void rename(const std::filesystem::path& old_p, const std::filesystem::path& new_p, std::error_code& ec) noexcept; ``` | | (since C++17) | Moves or renames the filesystem object identified by `old_p` to `new_p` as if by the POSIX [`rename`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html): * If `old_p` is a non-directory file, then `new_p` must be one of: + the same file as `old_p` or a hardlink to it: nothing is done in this case + existing non-directory file: `new_p` is first deleted, then, without allowing other processes to observe `new_p` as deleted, the pathname `new_p` is linked to the file and `old_p` is unlinked from the file. Write permissions are required to both the directory that contains `old_p` and the directory that contains `new_p`. + non-existing file in an existing directory: The pathname `new_p` is linked to the file and `old_p` is unlinked from the file. Write permissions are required to both the directory that contains `old_p` and the directory that contains `new_p`. * If `old_p` is a directory, then `new_p` must be one of: + the same directory as `old_p` or a hardlink to it: nothing is done in this case + existing directory: `new_p` is deleted if empty on POSIX systems, but this may be an error on other systems. If not an error, then `new_p` is first deleted, then, without allowing other processes to observe `new_p` as deleted, the pathname `new_p` is linked to the directory and `old_p` is unlinked from the directory. Write permissions are required to both the directory that contains `old_p` and the directory that contains `new_p`. + non-existing directory, not ending with a directory separator, and whose parent directory exists: The pathname `new_p` is linked to the directory and `old_p` is unlinked from the directory. Write permissions are required to both the directory that contains `old_p` and the directory that contains `new_p`. * Symlinks are not followed: if `old_p` is a symlink, it is itself renamed, not its target. If `new_p` is an existing symlink, it is itself erased, not its target. Rename fails if. * `new_p` ends with dot or with dot-dot * `new_p` names a non-existing directory ending with a directory separator * `old_p` is a directory which is an ancestor of `new_p` ### Parameters | | | | | --- | --- | --- | | old\_p | - | path to move or rename | | new\_p | - | target path for the move/rename operation | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value (none). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `old_p` as the first path argument, `new_p` as the second path argument, and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <iostream> #include <fstream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::path p = fs::current_path() / "sandbox"; fs::create_directories(p/"from"); std::ofstream(p/"from/file1.txt").put('a'); fs::create_directory(p/"to"); // fs::rename(p/"from/file1.txt", p/"to/"); // error: to is a directory fs::rename(p/"from/file1.txt", p/"to/file2.txt"); // OK // fs::rename(p/"from", p/"to"); // error: to is not empty fs::rename(p/"from", p/"to/subdir"); // OK fs::remove_all(p); } ``` ### See also | | | | --- | --- | | [rename](../io/c/rename "cpp/io/c/rename") | renames a file (function) | | [removeremove\_all](remove "cpp/filesystem/remove") (C++17)(C++17) | removes a file or empty directoryremoves a file or directory and all its contents, recursively (function) | cpp std::filesystem::current_path std::filesystem::current\_path ============================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` path current_path(); ``` | (1) | (since C++17) | | ``` path current_path( std::error_code& ec ); ``` | (2) | (since C++17) | | ``` void current_path( const std::filesystem::path& p ); ``` | (3) | (since C++17) | | ``` void current_path( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (4) | (since C++17) | Returns or changes the current path. 1-2) Returns the absolute path of the current working directory, obtained as if (in native format) by POSIX [`getcwd`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html). (2) returns `path()` if error occurs. 3-4) Changes the current working directory to `p`, as if by POSIX [`chdir`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/chdir.html). ### Parameters | | | | | --- | --- | --- | | p | - | path to change the current working directory to | | ec | - | out-parameter for error reporting in the non-throwing overloads. | ### Return value 1-2) Returns the current working directory. 3-4) (none). ### Exceptions 1-2) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. 3-4) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes The current working directory is the directory, associated with the process, that is used as the starting location in pathname resolution for relative paths. The current path as returned by many operating systems is a dangerous global variable. It may be changed unexpectedly by third-party or system library functions, or by another thread. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { std::cout << "Current path is " << fs::current_path() << '\n'; // (1) fs::current_path(fs::temp_directory_path()); // (3) std::cout << "Current path is " << fs::current_path() << '\n'; } ``` Possible output: ``` Current path is "D:/local/ConsoleApplication1" Current path is "E:/Temp" ``` ### See also | | | | --- | --- | | [temp\_directory\_path](temp_directory_path "cpp/filesystem/temp directory path") (C++17) | returns a directory suitable for temporary files (function) | cpp std::filesystem::is_regular_file std::filesystem::is\_regular\_file ================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool is_regular_file( std::filesystem::file_status s ) noexcept; ``` | (1) | (since C++17) | | ``` bool is_regular_file( const std::filesystem::path& p ); bool is_regular_file( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (2) | (since C++17) | Checks if the given file status or path corresponds to a regular file. 1) Equivalent to `s.type() == file_type::regular`. 2) Equivalent to `is_regular_file(status(p))` or `is_regular_file(status(p, ec))` respectively. ### Parameters | | | | | --- | --- | --- | | s | - | file status to check | | p | - | path to examine | | ec | - | error code to store the error status to | ### Return value `true` if the file indicated by `p` or if the type indicated by `s` refers to a regular file, `false` otherwise. The non-throwing overload returns `false` if an error occurs. ### Exceptions 2) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes The throwing overload is additionally specified to throw `[std::filesystem::filesystem\_error](filesystem_error "cpp/filesystem/filesystem error")` if `status(p)` would throw. ### Example ``` #include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <filesystem> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> namespace fs = std::filesystem; void demo_status(const fs::path& p, fs::file_status s) { std::cout << p; // alternative: switch(s.type()) { case fs::file_type::regular: ...} if(fs::is_regular_file(s)) std::cout << " is a regular file\n"; if(fs::is_directory(s)) std::cout << " is a directory\n"; if(fs::is_block_file(s)) std::cout << " is a block device\n"; if(fs::is_character_file(s)) std::cout << " is a character device\n"; if(fs::is_fifo(s)) std::cout << " is a named IPC pipe\n"; if(fs::is_socket(s)) std::cout << " is a named IPC socket\n"; if(fs::is_symlink(s)) std::cout << " is a symlink\n"; if(!fs::exists(s)) std::cout << " does not exist\n"; } int main() { // create files of different kinds fs::create_directory("sandbox"); std::ofstream("sandbox/file"); // create regular file fs::create_directory("sandbox/dir"); mkfifo("sandbox/pipe", 0644); sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, "sandbox/sock"); int fd = socket(PF_UNIX, SOCK_STREAM, 0); bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof addr); fs::create_symlink("file", "sandbox/symlink"); // demo different status accessors for(auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it) demo_status(*it, it->symlink_status()); // use cached status from directory entry demo_status("/dev/null", fs::status("/dev/null")); // direct calls to status demo_status("/dev/sda", fs::status("/dev/sda")); demo_status("sandbox/no", fs::status("/sandbox/no")); // cleanup close(fd); fs::remove_all("sandbox"); } ``` Possible output: ``` "sandbox/file" is a regular file "sandbox/dir" is a directory "sandbox/pipe" is a named IPC pipe "sandbox/sock" is a named IPC socket "sandbox/symlink" is a symlink "/dev/null" is a character device "/dev/sda" is a block device "sandbox/no" does not exist ``` ### See also | | | | --- | --- | | [file\_type](file_type "cpp/filesystem/file type") (C++17) | the type of a file (enum) | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [file\_status](file_status "cpp/filesystem/file status") (C++17) | represents file type and permissions (class) | | [status\_known](status_known "cpp/filesystem/status known") (C++17) | checks whether file status is known (function) | | [is\_block\_file](is_block_file "cpp/filesystem/is block file") (C++17) | checks whether the given path refers to block device (function) | | [is\_character\_file](is_character_file "cpp/filesystem/is character file") (C++17) | checks whether the given path refers to a character device (function) | | [is\_directory](is_directory "cpp/filesystem/is directory") (C++17) | checks whether the given path refers to a directory (function) | | [is\_fifo](is_fifo "cpp/filesystem/is fifo") (C++17) | checks whether the given path refers to a named pipe (function) | | [is\_other](is_other "cpp/filesystem/is other") (C++17) | checks whether the argument refers to an *other* file (function) | | [is\_socket](is_socket "cpp/filesystem/is socket") (C++17) | checks whether the argument refers to a named IPC socket (function) | | [is\_symlink](is_symlink "cpp/filesystem/is symlink") (C++17) | checks whether the argument refers to a symbolic link (function) | | [exists](exists "cpp/filesystem/exists") (C++17) | checks whether path refers to existing file system object (function) | | [is\_regular\_file](directory_entry/is_regular_file "cpp/filesystem/directory entry/is regular file") | checks whether the directory entry refers to a regular file (public member function of `std::filesystem::directory_entry`) |
programming_docs
cpp std::filesystem::last_write_time std::filesystem::last\_write\_time ================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` std::filesystem::file_time_type last_write_time(const std::filesystem::path& p); std::filesystem::file_time_type last_write_time(const std::filesystem::path& p, std::error_code& ec) noexcept; ``` | (1) | (since C++17) | | ``` void last_write_time(const std::filesystem::path& p, std::filesystem::file_time_type new_time); void last_write_time(const std::filesystem::path& p, std::filesystem::file_time_type new_time, std::error_code& ec) noexcept; ``` | (2) | (since C++17) | 1) Returns the time of the last modification of `p`, determined as if by accessing the member `st_mtime` of the POSIX [`stat`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/stat.html) (symlinks are followed). The non-throwing overload returns `file_time_type::min()` on errors. 2) Changes the time of the last modification of `p`, as if by POSIX [`futimens`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/futimens.html) (symlinks are followed). ### Parameters | | | | | --- | --- | --- | | p | - | path to examine or modify | | new\_time | - | new modification time | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value 1) The time of the last modification of `p` 2) (none) ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes It is not guaranteed that immediately after setting the write time, the value returned by (1) is the same as what was passed as the argument to (2) because the file system's time may be more granular than `[filesystem::file\_time\_type](file_time_type "cpp/filesystem/file time type")`. ### Example ``` #include <chrono> #include <filesystem> #include <format> #include <fstream> #include <iostream> using namespace std::chrono_literals; int main() { auto p = std::filesystem::temp_directory_path() / "example.bin"; std::ofstream(p.c_str()).put('a'); // create file std::filesystem::file_time_type ftime = std::filesystem::last_write_time(p); std::cout << std::format("File write time is {}\n", ftime); std::filesystem::last_write_time(p, ftime + 1h); // move file write time 1 hour to the future ftime = std::filesystem::last_write_time(p); // read back from the filesystem std::cout << std::format("File write time is {}\n", ftime); std::filesystem::remove(p); } ``` Possible output: ``` File write time is Sun May 9 23:29:58 2021 File write time is Mon May 10 00:29:58 2021 ``` ### See also | | | | --- | --- | | [file\_time\_type](file_time_type "cpp/filesystem/file time type") (C++17) | represents file time values (typedef) | | [last\_write\_time](directory_entry/last_write_time "cpp/filesystem/directory entry/last write time") | gets or sets the time of the last data modification of the file to which the directory entry refers (public member function of `std::filesystem::directory_entry`) | cpp std::filesystem::equivalent std::filesystem::equivalent =========================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool equivalent( const std::filesystem::path& p1, const std::filesystem::path& p2 ); bool equivalent( const std::filesystem::path& p1, const std::filesystem::path& p2, std::error_code& ec ) noexcept; ``` | | (since C++17) | Checks whether the paths `p1` and `p2` resolve to the same file system entity. If either `p1` or `p2` does not exist, an error is reported. The non-throwing overload returns `false` on errors. ### Parameters | | | | | --- | --- | --- | | p1, p2 | - | paths to check for equivalence | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the `p1` and `p2` refer to the same file or directory and their file status is the same. `false` otherwise. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p1` as the first path argument, `p2` as the second path argument, and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes Two paths are considered to resolve to the same file system entity if the two candidate entities the paths resolve to are located on the same device at the same location. For POSIX, this means that the `st_dev` and `st_ino` members of their POSIX [`stat` structure](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html), obtained as if by POSIX [`stat()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/stat.html), are equal. In particular, all hard links for the same file or directory are equivalent, and a symlink and its target on the same file system are equivalent. ### Example ``` #include <iostream> #include <cstdint> #include <filesystem> namespace fs = std::filesystem; int main() { // hard link equivalency fs::path p1 = "."; fs::path p2 = fs::current_path(); if(fs::equivalent(p1, p2)) std::cout << p1 << " is equivalent to " << p2 << '\n'; // symlink equivalency for(const fs::path lib : {"/lib/libc.so.6", "/lib/x86_64-linux-gnu/libc.so.6"}) { try { p2 = lib.parent_path() / fs::read_symlink(lib); } catch(std::filesystem::filesystem_error const& ex) { std::cout << ex.what() << '\n'; continue; } if(fs::equivalent(lib, p2)) std::cout << lib << " is equivalent to " << p2 << '\n'; } } ``` Possible output: ``` "." is equivalent to "/var/tmp/test" filesystem error: read_symlink: No such file or directory [/lib/libc.so.6] "/lib/x86_64-linux-gnu/libc.so.6" is equivalent to "/lib/x86_64-linux-gnu/libc-2.23.so" ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2937](https://cplusplus.github.io/LWG/issue2937) | C++17 | error condition specified incorrectly | corrected | ### See also | | | | --- | --- | | [compare](path/compare "cpp/filesystem/path/compare") | compares the lexical representations of two paths lexicographically (public member function of `std::filesystem::path`) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](path/operator_cmp "cpp/filesystem/path/operator cmp") (until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20) | lexicographically compares two paths (function) | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | cpp std::filesystem::canonical, std::filesystem::weakly_canonical std::filesystem::canonical, std::filesystem::weakly\_canonical ============================================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` path canonical( const std::filesystem::path& p ); ``` | (1) | (since C++17) | | ``` path canonical( const std::filesystem::path& p, std::error_code& ec ); ``` | (2) | (since C++17) | | ``` path weakly_canonical(const std::filesystem::path& p); ``` | (3) | (since C++17) | | ``` path weakly_canonical(const std::filesystem::path& p, std::error_code& ec); ``` | (4) | (since C++17) | 1-2) Converts path `p` to a canonical absolute path, i.e. an absolute path that has no dot, dot-dot elements or symbolic links in its generic format representation. If `p` is not an absolute path, the function behaves as if it is first made absolute by `[std::filesystem::absolute](http://en.cppreference.com/w/cpp/filesystem/absolute)(p)`. The path `p` must exist. 3-4) Returns a path composed by `operator/=` from the result of calling `canonical()` with a path argument composed of the leading elements of `p` that exist (as determined by `status(p)` or `status(p, ec)`), if any, followed by the elements of `p` that do not exist. The resulting path is in [normal form](path "cpp/filesystem/path"). ### Parameters | | | | | --- | --- | --- | | p | - | a path which may be absolute or relative; for `canonical` it must be an existing path | | ec | - | error code to store error status to | ### Return value 1-2) An absolute path that resolves to the same file as `[std::filesystem::absolute](http://en.cppreference.com/w/cpp/filesystem/absolute)(p)`. 3-4) A normal path of the form `canonical(x)/y`, where x is a path composed of the longest leading sequence of elements in p that exist, and y is a path composed of the remaining trailing non-existent elements of p ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes The function `canonical()` is modeled after the POSIX [`realpath`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/realpath.html). The function `weakly_canonical()` was introduced to simplify operational semantics of [`relative()`](relative "cpp/filesystem/relative"). ### Example ``` #include <iostream> #include <filesystem> int main() { /* set up sandbox directories: a └── b ├── c1 │ └── d <== current path └── c2 └── e */ auto old = std::filesystem::current_path(); auto tmp = std::filesystem::temp_directory_path(); std::filesystem::current_path(tmp); auto d1 = tmp / "a/b/c1/d"; auto d2 = tmp / "a/b/c2/e"; std::filesystem::create_directories(d1); std::filesystem::create_directories(d2); std::filesystem::current_path(d1); auto p1 = std::filesystem::path("../../c2/./e"); auto p2 = std::filesystem::path("../no-such-file"); std::cout << "Current path is " << std::filesystem::current_path() << '\n' << "Canonical path for " << p1 << " is " << std::filesystem::canonical(p1) << '\n' << "Weakly canonical path for " << p2 << " is " << std::filesystem::weakly_canonical(p2) << '\n'; try { std::filesystem::canonical(p2); // NOT REACHED } catch(const std::exception& ex) { std::cout << "Canonical path for " << p2 << " threw exception:\n" << ex.what() << '\n'; } // cleanup std::filesystem::current_path(old); const auto count = std::filesystem::remove_all(tmp / "a"); std::cout << "Deleted " << count << " files or directories.\n"; } ``` Possible output: ``` Current path is "/tmp/a/b/c1/d" Canonical path for "../../c2/./e" is "/tmp/a/b/c2/e" Weakly canonical path for "../no-such-file" is "/tmp/a/b/c1/no-such-file" Canonical path for "../no-such-file" threw exception: filesystem error: in canonical: No such file or directory [../no-such-file] [/tmp/a/b/c1/d] Deleted 6 files or directories. ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2956](https://cplusplus.github.io/LWG/issue2956) | C++17 | `canonical` has a spurious `base` parameter | removed | ### See also | | | | --- | --- | | [path](path "cpp/filesystem/path") (C++17) | represents a path (class) | | [absolute](absolute "cpp/filesystem/absolute") (C++17) | composes an absolute path (function) | | [relativeproximate](relative "cpp/filesystem/relative") (C++17) | composes a relative path (function) | cpp std::filesystem::remove, std::filesystem::remove_all std::filesystem::remove, std::filesystem::remove\_all ===================================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool remove( const std::filesystem::path& p ); bool remove( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (1) | (since C++17) | | ``` std::uintmax_t remove_all( const std::filesystem::path& p ); std::uintmax_t remove_all( const std::filesystem::path& p, std::error_code& ec ); ``` | (2) | (since C++17) | 1) The file or empty directory identified by the path `p` is deleted as if by the POSIX [`remove`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/remove.html). Symlinks are not followed (symlink is removed, not its target). 2) Deletes the contents of `p` (if it is a directory) and the contents of all its subdirectories, recursively, then deletes `p` itself as if by repeatedly applying the POSIX [`remove`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/remove.html). Symlinks are not followed (symlink is removed, not its target). ### Parameters | | | | | --- | --- | --- | | p | - | path to delete | | ec | - | out-parameter for error reporting in the non-throwing overload. | ### Return value 1) `true` if the file was deleted, `false` if it did not exist. The overload that takes `error_code&` argument returns `false` on errors. 2) Returns the number of files and directories that were deleted (which may be zero if `p` did not exist to begin with). The overload that takes `error_code&` argument returns `static\_cast<[std::uintmax\_t](http://en.cppreference.com/w/cpp/types/integer)>(-1)` on error. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes On POSIX systems, this function typically calls `unlink` and `rmdir` as needed, on Windows `RemoveDirectoryW` and `DeleteFileW`. ### Example ``` #include <iostream> #include <cstdint> #include <filesystem> namespace fs = std::filesystem; int main() { fs::path tmp = fs::temp_directory_path(); fs::create_directories(tmp / "abcdef/example"); std::uintmax_t n = fs::remove_all(tmp / "abcdef"); std::cout << "Deleted " << n << " files or directories\n"; } ``` Possible output: ``` Deleted 2 files or directories ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3014](https://cplusplus.github.io/LWG/issue3014) | C++17 | `error_code` overload of `remove_all` marked noexcept but can allocate memory | noexcept removed | ### See also | | | | --- | --- | | [remove](../io/c/remove "cpp/io/c/remove") | erases a file (function) | cpp std::filesystem::is_block_file std::filesystem::is\_block\_file ================================ | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool is_block_file( std::filesystem::file_status s ) noexcept; ``` | (1) | (since C++17) | | ``` bool is_block_file( const std::filesystem::path& p ); bool is_block_file( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (2) | (since C++17) | Checks if the given file status or path corresponds to a block special file, as if determined by the POSIX [`S_ISBLK`](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html). Examples of block special files are block devices such as `/dev/sda` or `/dev/loop0` on Linux. 1) Equivalent to `s.type() == file_type::block`. 2) Equivalent to `is_block_file(status(p))` or `is_block_file(status(p, ec))`. ### Parameters | | | | | --- | --- | --- | | s | - | file status to check | | p | - | path to examine | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the file indicated by `p` or if the type indicated `s` refers to a block device. The non-throwing overload returns `false` if an error occurs. ### Exceptions 2) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <filesystem> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> namespace fs = std::filesystem; void demo_status(const fs::path& p, fs::file_status s) { std::cout << p; // alternative: switch(s.type()) { case fs::file_type::regular: ...} if(fs::is_regular_file(s)) std::cout << " is a regular file\n"; if(fs::is_directory(s)) std::cout << " is a directory\n"; if(fs::is_block_file(s)) std::cout << " is a block device\n"; if(fs::is_character_file(s)) std::cout << " is a character device\n"; if(fs::is_fifo(s)) std::cout << " is a named IPC pipe\n"; if(fs::is_socket(s)) std::cout << " is a named IPC socket\n"; if(fs::is_symlink(s)) std::cout << " is a symlink\n"; if(!fs::exists(s)) std::cout << " does not exist\n"; } int main() { // create files of different kinds fs::create_directory("sandbox"); std::ofstream("sandbox/file"); // create regular file fs::create_directory("sandbox/dir"); mkfifo("sandbox/pipe", 0644); sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, "sandbox/sock"); int fd = socket(PF_UNIX, SOCK_STREAM, 0); bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof addr); fs::create_symlink("file", "sandbox/symlink"); // demo different status accessors for(auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it) demo_status(*it, it->symlink_status()); // use cached status from directory entry demo_status("/dev/null", fs::status("/dev/null")); // direct calls to status demo_status("/dev/sda", fs::status("/dev/sda")); demo_status("sandbox/no", fs::status("/sandbox/no")); // cleanup close(fd); fs::remove_all("sandbox"); } ``` Possible output: ``` "sandbox/file" is a regular file "sandbox/dir" is a directory "sandbox/pipe" is a named IPC pipe "sandbox/sock" is a named IPC socket "sandbox/symlink" is a symlink "/dev/null" is a character device "/dev/sda" is a block device "sandbox/no" does not exist ``` ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [file\_status](file_status "cpp/filesystem/file status") (C++17) | represents file type and permissions (class) | | [status\_known](status_known "cpp/filesystem/status known") (C++17) | checks whether file status is known (function) | | [is\_character\_file](is_character_file "cpp/filesystem/is character file") (C++17) | checks whether the given path refers to a character device (function) | | [is\_directory](is_directory "cpp/filesystem/is directory") (C++17) | checks whether the given path refers to a directory (function) | | [is\_fifo](is_fifo "cpp/filesystem/is fifo") (C++17) | checks whether the given path refers to a named pipe (function) | | [is\_other](is_other "cpp/filesystem/is other") (C++17) | checks whether the argument refers to an *other* file (function) | | [is\_regular\_file](is_regular_file "cpp/filesystem/is regular file") (C++17) | checks whether the argument refers to a regular file (function) | | [is\_socket](is_socket "cpp/filesystem/is socket") (C++17) | checks whether the argument refers to a named IPC socket (function) | | [is\_symlink](is_symlink "cpp/filesystem/is symlink") (C++17) | checks whether the argument refers to a symbolic link (function) | | [exists](exists "cpp/filesystem/exists") (C++17) | checks whether path refers to existing file system object (function) | | [is\_block\_file](directory_entry/is_block_file "cpp/filesystem/directory entry/is block file") | checks whether the directory entry refers to block device (public member function of `std::filesystem::directory_entry`) |
programming_docs
cpp std::filesystem::copy_options std::filesystem::copy\_options ============================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` enum class copy_options { none = /* unspecified */, skip_existing = /* unspecified */, overwrite_existing = /* unspecified */, update_existing = /* unspecified */, recursive = /* unspecified */, copy_symlinks = /* unspecified */, skip_symlinks = /* unspecified */, directories_only = /* unspecified */, create_symlinks = /* unspecified */, create_hard_links = /* unspecified */ }; ``` | | (since C++17) | This type represents available options that control the behavior of the [`copy()`](copy "cpp/filesystem/copy") and [`copy_file()`](copy_file "cpp/filesystem/copy file") function. `copy_options` satisfies the requirements of [BitmaskType](../named_req/bitmasktype "cpp/named req/BitmaskType") (which means the bitwise operators `operator&`, `operator|`, `operator^`, `operator~`, `operator&=`, `operator|=`, and `operator^=` are defined for this type). `none` represents the empty bitmask; every other enumerator represents a distinct bitmask element. ### Member constants At most one copy option in each of the following options groups may be present, otherwise the behavior of the copy functions is undefined. | Member constant | Meaning | | --- | --- | | options controlling [`copy_file()`](copy_file "cpp/filesystem/copy file") when the file already exists | | `none` | Report an error (default behavior) | | `skip_existing` | Keep the existing file, without reporting an error. | | `overwrite_existing` | Replace the existing file | | `update_existing` | Replace the existing file only if it is older than the file being copied | | options controlling the effects of [`copy()`](copy "cpp/filesystem/copy") on subdirectories | | `none` | Skip subdirectories (default behavior) | | `recursive` | Recursively copy subdirectories and their content | | options controlling the effects of [`copy()`](copy "cpp/filesystem/copy") on symbolic links | | `none` | Follow symlinks (default behavior) | | `copy_symlinks` | Copy symlinks as symlinks, not as the files they point to | | `skip_symlinks` | Ignore symlinks | | options controlling the kind of copying [`copy()`](copy "cpp/filesystem/copy") does | | `none` | Copy file content (default behavior) | | `directories_only` | Copy the directory structure, but do not copy any non-directory files | | `create_symlinks` | Instead of creating copies of files, create symlinks pointing to the originals. Note: the source path must be an absolute path unless the destination path is in the current directory. | | `create_hard_links` | Instead of creating copies of files, create hardlinks that resolve to the same files as the originals | ### Example ``` #include <cstdlib> #include <iostream> #include <fstream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::create_directories("sandbox/dir/subdir"); std::ofstream("sandbox/file1.txt").put('a'); fs::copy("sandbox/file1.txt", "sandbox/file2.txt"); // copy file fs::copy("sandbox/dir", "sandbox/dir2"); // copy directory (non-recursive) const auto copyOptions = fs::copy_options::update_existing | fs::copy_options::recursive | fs::copy_options::directories_only ; fs::copy("sandbox", "sandbox_copy", copyOptions); static_cast<void>(std::system("tree")); fs::remove_all("sandbox"); fs::remove_all("sandbox_copy"); } ``` Possible output: ``` . ├── sandbox │ ├── dir │ │ └── subdir │ ├── dir2 │ ├── file1.txt │ └── file2.txt └── sandbox_copy ├── dir │ └── subdir └── dir2 8 directories, 2 files ``` ### See also | | | | --- | --- | | [copy](copy "cpp/filesystem/copy") (C++17) | copies files or directories (function) | | [copy\_file](copy_file "cpp/filesystem/copy file") (C++17) | copies file contents (function) | cpp std::filesystem::recursive_directory_iterator std::filesystem::recursive\_directory\_iterator =============================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` class recursive_directory_iterator; ``` | | (since C++17) | `recursive_directory_iterator` is a [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator") that iterates over the [`directory_entry`](directory_entry "cpp/filesystem/directory entry") elements of a directory, and, recursively, over the entries of all subdirectories. The iteration order is unspecified, except that each directory entry is visited only once. By default, symlinks are not followed, but this can be enabled by specifying the directory option [`follow_directory_symlink`](directory_options "cpp/filesystem/directory options") at construction time. The special pathnames dot and dot-dot are skipped. If the `recursive_directory_iterator` reports an error or is advanced past the last directory entry of the top-level directory, it becomes equal to the default-constructed iterator, also known as the end iterator. Two end iterators are always equal, dereferencing or incrementing the end iterator is undefined behavior. If a file or a directory is deleted or added to the directory tree after the recursive directory iterator has been created, it is unspecified whether the change would be observed through the iterator. If the directory structure contains cycles, the end iterator may be unreachable. ### Member types | Member type | Definition | | --- | --- | | `value_type` | `[std::filesystem::directory\_entry](directory_entry "cpp/filesystem/directory entry")` | | `difference_type` | `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` | | `pointer` | `const [std::filesystem::directory\_entry](http://en.cppreference.com/w/cpp/filesystem/directory_entry)\*` | | `reference` | `const [std::filesystem::directory\_entry](http://en.cppreference.com/w/cpp/filesystem/directory_entry)&` | | `iterator_category` | `[std::input\_iterator\_tag](../iterator/iterator_tags "cpp/iterator/iterator tags")` | ### Member functions | | | | --- | --- | | [(constructor)](recursive_directory_iterator/recursive_directory_iterator "cpp/filesystem/recursive directory iterator/recursive directory iterator") | constructs a recursive directory iterator (public member function) | | (destructor) | default destructor (public member function) | | Observers | | [operator\*operator->](recursive_directory_iterator/operator* "cpp/filesystem/recursive directory iterator/operator*") | accesses the pointed-to entry (public member function) | | [options](recursive_directory_iterator/options "cpp/filesystem/recursive directory iterator/options") | returns the currently active options that affect the iteration (public member function) | | [depth](recursive_directory_iterator/depth "cpp/filesystem/recursive directory iterator/depth") | returns the current recursion depth (public member function) | | [recursion\_pending](recursive_directory_iterator/recursion_pending "cpp/filesystem/recursive directory iterator/recursion pending") | checks whether the recursion is disabled for the current directory (public member function) | | Modifiers | | [operator=](recursive_directory_iterator/operator= "cpp/filesystem/recursive directory iterator/operator=") | assigns contents (public member function) | | [incrementoperator++](recursive_directory_iterator/increment "cpp/filesystem/recursive directory iterator/increment") | advances to the next entry (public member function) | | [pop](recursive_directory_iterator/pop "cpp/filesystem/recursive directory iterator/pop") | moves the iterator one level up in the directory hierarchy (public member function) | | [disable\_recursion\_pending](recursive_directory_iterator/disable_recursion_pending "cpp/filesystem/recursive directory iterator/disable recursion pending") | disables recursion until the next increment (public member function) | ### Non-member functions | | | | --- | --- | | [begin(std::filesystem::recursive\_directory\_iterator)end(std::filesystem::recursive\_directory\_iterator)](recursive_directory_iterator/begin "cpp/filesystem/recursive directory iterator/begin") | range-based for loop support (function) | Additionally, `operator==` and `operator!=` are (until C++20)`operator==` is (since C++20) provided as required by [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). It is unspecified whether `operator!=` is provided because it can be synthesized from `operator==`, and (since C++20) whether an equality operator is a member or non-member. ### Helper templates | | | | | --- | --- | --- | | ``` namespace std::ranges { template<> inline constexpr bool enable_borrowed_range<std::filesystem::recursive_directory_iterator> = true; } ``` | | (since C++20) | | ``` namespace std::ranges { template<> inline constexpr bool enable_view<std::filesystem::recursive_directory_iterator> = true; } ``` | | (since C++20) | These specializations for `recursive_directory_iterator` make it a [`borrowed_range`](../ranges/borrowed_range "cpp/ranges/borrowed range") and a [`view`](../ranges/view "cpp/ranges/view"). ### Notes A `recursive_directory_iterator` typically holds a reference-counted *pointer* (to satisfy shallow-copy semantics of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator")) to an implementation object, which holds: * a container (such as `[std::vector](../container/vector "cpp/container/vector")`) of non-recursive [`directory_iterator`s](directory_iterator "cpp/filesystem/directory iterator") that forms the recursion stack * the recursion depth counter (accessible with [`depth()`](recursive_directory_iterator/depth "cpp/filesystem/recursive directory iterator/depth")) * the directory options used at construction (accessible with [`options()`](recursive_directory_iterator/options "cpp/filesystem/recursive directory iterator/options")) * the pending recursion flag (accessible with [`recursion_pending()`](recursive_directory_iterator/recursion_pending "cpp/filesystem/recursive directory iterator/recursion pending"), may be combined with the directory options to save space) ### Example ``` #include <fstream> #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::current_path(fs::temp_directory_path()); fs::create_directories("sandbox/a/b"); std::ofstream("sandbox/file1.txt"); fs::create_symlink("a", "sandbox/syma"); // Iterate over the `std::filesystem::directory_entry` elements explicitly for (const fs::directory_entry& dir_entry : fs::recursive_directory_iterator("sandbox")) { std::cout << dir_entry << '\n'; } std::cout << "-----------------------------\n"; // Iterate over the `std::filesystem::directory_entry` elements using `auto` for (auto const& dir_entry : fs::recursive_directory_iterator("sandbox")) { std::cout << dir_entry << '\n'; } fs::remove_all("sandbox"); } ``` Possible output: ``` "sandbox/syma" "sandbox/file1.txt" "sandbox/a" "sandbox/a/b" ----------------------------- "sandbox/syma" "sandbox/file1.txt" "sandbox/a" "sandbox/a/b" ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3480](https://cplusplus.github.io/LWG/issue3480) | C++20 | `recursive_directory_iterator` was neither a [`borrowed_range`](../ranges/borrowed_range "cpp/ranges/borrowed range") nor a [`view`](../ranges/view "cpp/ranges/view") | it is both | ### See also | | | | --- | --- | | [directory\_iterator](directory_iterator "cpp/filesystem/directory iterator") (C++17) | an iterator to the contents of the directory (class) | | [directory\_entry](directory_entry "cpp/filesystem/directory entry") (C++17) | a directory entry (class) | | [directory\_options](directory_options "cpp/filesystem/directory options") (C++17) | options for iterating directory contents (enum) | cpp std::filesystem::perms std::filesystem::perms ====================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` enum class perms; ``` | | (since C++17) | This type represents file access permissions. `perms` satisfies the requirements of [BitmaskType](../named_req/bitmasktype "cpp/named req/BitmaskType") (which means the bitwise operators `operator&`, `operator|`, `operator^`, `operator~`, `operator&=`, `operator|=`, and `operator^=` are defined for this type). `none` represents the empty bitmask; every other enumerator represents a distinct bitmask element. Access permissions model [POSIX permission bits](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html), and any individual file permissions (as reported by `[filesystem::status](status "cpp/filesystem/status")`) are a combination of some of the following bits: ### Member constants | Member constant | Value (octal) | POSIX equivalent | Meaning | | --- | --- | --- | --- | | `none` | `​0​` | | no permission bits are set | | `owner_read` | `0400` | `S_IRUSR` | File owner has read permission | | `owner_write` | `0200` | `S_IWUSR` | File owner has write permission | | `owner_exec` | `0100` | `S_IXUSR` | File owner has execute/search permission | | `owner_all` | `0700` | `S_IRWXU` | File owner has read, write, and execute/search permissions Equivalent to `owner_read | owner_write | owner_exec`. | | `group_read` | `040` | `S_IRGRP` | The file's user group has read permission | | `group_write` | `020` | `S_IWGRP` | The file's user group has write permission | | `group_exec` | `010` | `S_IXGRP` | The file's user group has execute/search permission | | `group_all` | `070` | `S_IRWXG` | The file's user group has read, write, and execute/search permissions Equivalent to `group_read | group_write | group_exec`. | | `others_read` | `04` | `S_IROTH` | Other users have read permission | | `others_write` | `02` | `S_IWOTH` | Other users have write permission | | `others_exec` | `01` | `S_IXOTH` | Other users have execute/search permission | | `others_all` | `07` | `S_IRWXO` | Other users have read, write, and execute/search permissions Equivalent to `others_read | others_write | others_exec`. | | `all` | `0777` | | All users have read, write, and execute/search permissions Equivalent to `owner_all | group_all | others_all`. | | `set_uid` | `04000` | `S_ISUID` | Set user ID to file owner user ID on execution | | `set_gid` | `02000` | `S_ISGID` | Set group ID to file's user group ID on execution | | `sticky_bit` | `01000` | `S_ISVTX` | Implementation-defined meaning, but POSIX XSI specifies that when set on a directory, only file owners may delete files even if the directory is writeable to others (used with `/tmp`) | | `mask` | `07777` | | All valid permission bits. Equivalent to `all | set_uid | set_gid | sticky_bit`. | Additionally, the following constants of this type are defined, which do not represent permissions: | Member constant | Value (hex) | Meaning | | --- | --- | --- | | `unknown` | `0xFFFF` | Unknown permissions (e.g. when `[filesystem::file\_status](file_status "cpp/filesystem/file status")` is created without permissions) | ### Notes Permissions may not necessarily be implemented as bits, but they are treated that way conceptually. Some permission bits may be ignored on some systems, and changing some bits may automatically change others (e.g. on platforms without owner/group/all distinction, setting any of the three write bits set all three). ### Example ``` #include <fstream> #include <bitset> #include <iostream> #include <filesystem> namespace fs = std::filesystem; void demo_perms(fs::perms p) { std::cout << ((p & fs::perms::owner_read) != fs::perms::none ? "r" : "-") << ((p & fs::perms::owner_write) != fs::perms::none ? "w" : "-") << ((p & fs::perms::owner_exec) != fs::perms::none ? "x" : "-") << ((p & fs::perms::group_read) != fs::perms::none ? "r" : "-") << ((p & fs::perms::group_write) != fs::perms::none ? "w" : "-") << ((p & fs::perms::group_exec) != fs::perms::none ? "x" : "-") << ((p & fs::perms::others_read) != fs::perms::none ? "r" : "-") << ((p & fs::perms::others_write) != fs::perms::none ? "w" : "-") << ((p & fs::perms::others_exec) != fs::perms::none ? "x" : "-") << '\n'; } int main() { std::ofstream("test.txt"); // create file std::cout << "Created file with permissions: "; demo_perms(fs::status("test.txt").permissions()); fs::permissions("test.txt", fs::perms::owner_all | fs::perms::group_all, fs::perm_options::add); std::cout << "After adding u+rwx and g+rwx: "; demo_perms(fs::status("test.txt").permissions()); fs::remove("test.txt"); } ``` Possible output: ``` Created file with permissions: rw-r--r-- After adding u+rwx and g+wrx: rwxrwxr-- ``` ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [permissions](permissions "cpp/filesystem/permissions") (C++17) | modifies file access permissions (function) | cpp std::filesystem::filesystem_error std::filesystem::filesystem\_error ================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` class filesystem_error; ``` | | (since C++17) | The class `std::filesystem::filesystem_error` defines an exception object that is thrown on failure by the throwing overloads of the functions in the filesystem library. ![std-filesystem-filesystem error-inheritance.svg]() Inheritance diagram. ### Member functions | | | | --- | --- | | [(constructor)](filesystem_error/filesystem_error "cpp/filesystem/filesystem error/filesystem error") | constructs the exception object (public member function) | | [operator=](filesystem_error/operator= "cpp/filesystem/filesystem error/operator=") | replaces the exception object (public member function) | | [path1path2](filesystem_error/path "cpp/filesystem/filesystem error/path") | returns the paths that were involved in the operation that caused the error (public member function) | | [what](filesystem_error/what "cpp/filesystem/filesystem error/what") | returns the explanatory string (public member function) | Inherited from [std::system\_error](../error/system_error "cpp/error/system error") ------------------------------------------------------------------------------------- ### Member functions | | | | --- | --- | | [code](../error/system_error/code "cpp/error/system error/code") | returns error code (public member function of `std::system_error`) | | [what](../error/system_error/what "cpp/error/system error/what") [virtual] | returns an explanatory string (virtual public member function of `std::system_error`) | Inherited from [std::runtime\_error](../error/runtime_error "cpp/error/runtime error") ---------------------------------------------------------------------------------------- Inherited from [std::exception](../error/exception "cpp/error/exception") --------------------------------------------------------------------------- ### Member functions | | | | --- | --- | | [(destructor)](../error/exception/~exception "cpp/error/exception/~exception") [virtual] | destroys the exception object (virtual public member function of `std::exception`) | | [what](../error/exception/what "cpp/error/exception/what") [virtual] | returns an explanatory string (virtual public member function of `std::exception`) | ### Notes In order to ensure that copy functions of `filesystem_error` are noexcept, typical implementations store an object holding the return value of `[what()](filesystem_error/what "cpp/filesystem/filesystem error/what")` and two `[std::filesystem::path](path "cpp/filesystem/path")` objects referenced by `[path1()](filesystem_error/path "cpp/filesystem/filesystem error/path")` and `[path2()](filesystem_error/path "cpp/filesystem/filesystem error/path")` respectively in a separately-allocated reference-counted storage. Currently the [MS STL implementation](https://github.com/microsoft/STL/blob/master/stl/inc/filesystem#L1749) is non-conforming: objects mentioned above are stored directly in the `filesystem` object, which makes the copy functions not noexcept. ### Example ``` #include <system_error> #include <filesystem> #include <iostream> int main() { const std::filesystem::path from{"/nonexistent1/a"}, to{"/nonexistent2/b"}; try { std::filesystem::copy_file(from, to); // throws: files do not exist } catch(std::filesystem::filesystem_error const& ex) { std::cout << "what(): " << ex.what() << '\n' << "path1(): " << ex.path1() << '\n' << "path2(): " << ex.path2() << '\n' << "code().value(): " << ex.code().value() << '\n' << "code().message(): " << ex.code().message() << '\n' << "code().category(): " << ex.code().category().name() << '\n'; } // All functions have non-throwing equivalents std::error_code ec; std::filesystem::copy_file(from, to, ec); // does not throw std::cout << "\nnon-throwing form sets error_code: " << ec.message() << '\n'; } ``` Possible output: ``` what(): filesystem error: cannot copy file: No such file or directory [/nonexistent1/a] [/nonexistent2/b] path1(): "/nonexistent1/a" path2(): "/nonexistent2/b" code().value(): 2 code().message(): No such file or directory code().category(): generic non-throwing form sets error_code: No such file or directory ```
programming_docs
cpp std::filesystem::is_other std::filesystem::is\_other ========================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool is_other( std::filesystem::file_status s ) noexcept; ``` | (1) | (since C++17) | | ``` bool is_other( const std::filesystem::path& p ); bool is_other( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (2) | (since C++17) | Checks if the given file status or path corresponds to a file of type *other* type. That is, the file exists, but is neither regular file, nor directory nor a symlink. 1) Equivalent to `exists(s) && !is_regular_file(s) && !is_directory(s) && !is_symlink(s)`. 2) Equivalent to `is_other(status(p))` or `is_other(status(p, ec))`, respectively. ### Parameters | | | | | --- | --- | --- | | s | - | file status to check | | p | - | path to examine | | ec | - | error code to store the error status to | ### Return value `true` if the file indicated by `p` or if the type indicated `s` refers to a file that is not regular file, directory, or a symlink, `false` otherwise. The non-throwing overload returns `false` if an error occurs. ### Exceptions 2) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [file\_status](file_status "cpp/filesystem/file status") (C++17) | represents file type and permissions (class) | | [status\_known](status_known "cpp/filesystem/status known") (C++17) | checks whether file status is known (function) | | [is\_block\_file](is_block_file "cpp/filesystem/is block file") (C++17) | checks whether the given path refers to block device (function) | | [is\_character\_file](is_character_file "cpp/filesystem/is character file") (C++17) | checks whether the given path refers to a character device (function) | | [is\_directory](is_directory "cpp/filesystem/is directory") (C++17) | checks whether the given path refers to a directory (function) | | [is\_fifo](is_fifo "cpp/filesystem/is fifo") (C++17) | checks whether the given path refers to a named pipe (function) | | [is\_regular\_file](is_regular_file "cpp/filesystem/is regular file") (C++17) | checks whether the argument refers to a regular file (function) | | [is\_socket](is_socket "cpp/filesystem/is socket") (C++17) | checks whether the argument refers to a named IPC socket (function) | | [is\_symlink](is_symlink "cpp/filesystem/is symlink") (C++17) | checks whether the argument refers to a symbolic link (function) | | [exists](exists "cpp/filesystem/exists") (C++17) | checks whether path refers to existing file system object (function) | | [is\_other](directory_entry/is_other "cpp/filesystem/directory entry/is other") | checks whether the directory entry refers to an *other* file (public member function of `std::filesystem::directory_entry`) | cpp std::filesystem::relative, std::filesystem::proximate std::filesystem::relative, std::filesystem::proximate ===================================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` path relative( const std::filesystem::path& p, std::error_code& ec ); ``` | (1) | (since C++17) | | ``` path relative( const std::filesystem::path& p, const std::filesystem::path& base = std::filesystem::current_path()); path relative( const std::filesystem::path& p, const std::filesystem::path& base, std::error_code& ec ); ``` | (2) | (since C++17) | | ``` path proximate( const std::filesystem::path& p, std::error_code& ec ); ``` | (3) | (since C++17) | | ``` path proximate( const std::filesystem::path& p, const std::filesystem::path& base = std::filesystem::current_path()); path proximate( const std::filesystem::path& p, const std::filesystem::path& base, std::error_code& ec ); ``` | (4) | (since C++17) | 1) Returns `relative(p, current_path(), ec)` 2) Returns `p` made relative to `base`. Resolves symlinks and normalizes both `p` and `base` before other processing. Effectively returns `[std::filesystem::weakly\_canonical](http://en.cppreference.com/w/cpp/filesystem/canonical)(p).lexically\_relative([std::filesystem::weakly\_canonical](http://en.cppreference.com/w/cpp/filesystem/canonical)(base))` or `[std::filesystem::weakly\_canonical](http://en.cppreference.com/w/cpp/filesystem/canonical)(p, ec).lexically\_relative([std::filesystem::weakly\_canonical](http://en.cppreference.com/w/cpp/filesystem/canonical)(base, ec))`, except the error code form returns `path()` at the first error occurrence, if any. 3) Returns `proximate(p, current_path(), ec)` 4) Effectively returns `[std::filesystem::weakly\_canonical](http://en.cppreference.com/w/cpp/filesystem/canonical)(p).lexically\_proximate([std::filesystem::weakly\_canonical](http://en.cppreference.com/w/cpp/filesystem/canonical)(base))` or `[std::filesystem::weakly\_canonical](http://en.cppreference.com/w/cpp/filesystem/canonical)(p, ec).lexically\_proximate([std::filesystem::weakly\_canonical](http://en.cppreference.com/w/cpp/filesystem/canonical)(base, ec))`, except the error code form returns `path()` at the first error occurrence, if any. ### Parameters | | | | | --- | --- | --- | | p | - | an existing path | | base | - | base path, against which `p` will be made relative/proximate | | ec | - | error code to store error status to | ### Return value 1) p made relative against base. 2) p made proximate against base ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument, `base` as the second path argument, and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <iostream> #include <filesystem> void show(std::filesystem::path x, std::filesystem::path y) { std::cout << "x:\t\t " << x << "\ny:\t\t " << y << '\n' << "relative(x, y): " << std::filesystem::relative(x, y) << '\n' << "proximate(x, y): " << std::filesystem::proximate(x, y) << "\n\n"; } int main() { show("/a/b/c", "/a/b"); show("/a/c", "/a/b"); show("c", "/a/b"); show("/a/b", "c"); } ``` Possible output: ``` x: "/a/b/c" y: "/a/b" relative(x, y): "c" proximate(x, y): "c" x: "/a/c" y: "/a/b" relative(x, y): "../c" proximate(x, y): "../c" x: "c" y: "/a/b" relative(x, y): "" proximate(x, y): "c" x: "/a/b" y: "c" relative(x, y): "" proximate(x, y): "/a/b" ``` ### See also | | | | --- | --- | | [path](path "cpp/filesystem/path") (C++17) | represents a path (class) | | [absolute](absolute "cpp/filesystem/absolute") (C++17) | composes an absolute path (function) | | [canonicalweakly\_canonical](canonical "cpp/filesystem/canonical") (C++17) | composes a canonical path (function) | | [lexically\_normallexically\_relativelexically\_proximate](path/lexically_normal "cpp/filesystem/path/lexically normal") | converts path to normal formconverts path to relative formconverts path to proximate form (public member function of `std::filesystem::path`) | cpp std::filesystem::space_info std::filesystem::space\_info ============================ | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` struct space_info { std::uintmax_t capacity; std::uintmax_t free; std::uintmax_t available; }; ``` | | (since C++17) | Represents the filesystem information as determined by [`filesystem::space`](space "cpp/filesystem/space"). ### Member objects | | | | --- | --- | | capacity | total size of the filesystem, in bytes (public member object) | | free | free space on the filesystem, in bytes (public member object) | | available | free space available to a non-privileged process (may be equal or less than `free`) (public member object) | ### Non-member functions | | | | --- | --- | | **operator==** (C++20) | compares two `space_info`s (function) | operator==(std::filesystem::space\_info) ----------------------------------------- | | | | | --- | --- | --- | | ``` friend bool operator==( const space_info&, const space_info& ) = default; ``` | | (since C++20) | Checks if `capacity`, `free` and `available` of both arguments are equal respectively. This function is not visible to ordinary [unqualified](../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../language/adl "cpp/language/adl") when `std::filesystem::space_info` is an associated class of the arguments. The `!=` operator is [synthesized](../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Example ``` #include <iostream> #include <filesystem> #include <cstdint> void print_space_info(auto const& dirs, int width = 14) { std::cout << std::left; for (const auto s : {"Capacity", "Free", "Available", "Dir"}) std::cout << "│ " << std::setw(width) << s << ' '; std::cout << '\n'; std::error_code ec; for (auto const& dir : dirs) { const std::filesystem::space_info si = std::filesystem::space(dir, ec); std::cout << "│ " << std::setw(width) << static_cast<std::intmax_t>(si.capacity) << ' ' << "│ " << std::setw(width) << static_cast<std::intmax_t>(si.free) << ' ' << "│ " << std::setw(width) << static_cast<std::intmax_t>(si.available) << ' ' << "│ " << dir << '\n'; } } int main() { const auto dirs = { "/dev/null", "/tmp", "/home", "/null" }; print_space_info(dirs); } ``` Possible output: ``` │ Capacity │ Free │ Available │ Dir │ 8342851584 │ 8342851584 │ 8342851584 │ /dev/null │ 12884901888 │ 3045265408 │ 3045265408 │ /tmp │ 250321567744 │ 37623181312 │ 25152159744 │ /home │ -1 │ -1 │ -1 │ /null ``` ### See also | | | | --- | --- | | [space](space "cpp/filesystem/space") (C++17) | determines available free space on the file system (function) | cpp std::filesystem::read_symlink std::filesystem::read\_symlink ============================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` std::filesystem::path read_symlink(const std::filesystem::path& p); std::filesystem::path read_symlink(const std::filesystem::path& p, std::error_code& ec); ``` | | (since C++17) | If the path `p` refers to a symbolic link, returns a new path object which refers to the target of that symbolic link. It is an error if `p` does not refer to a symbolic link. The non-throwing overload returns an empty path on errors. ### Parameters | | | | | --- | --- | --- | | p | - | path to a symlink | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value The target of the symlink (which may not necessarily exist). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { for(fs::path p : {"/usr/bin/gcc", "/bin/cat", "/bin/mouse"}) { std::cout << p; fs::exists(p) ? fs::is_symlink(p) ? std::cout << " -> " << fs::read_symlink(p) << '\n' : std::cout << " exists but it is not a symlink\n" : std::cout << " does not exist\n"; } } ``` Possible output: ``` "/usr/bin/gcc" -> "gcc-5" "/bin/cat" exists but it is not a symlink "/bin/mouse" does not exist ``` ### See also | | | | --- | --- | | [is\_symlink](is_symlink "cpp/filesystem/is symlink") (C++17) | checks whether the argument refers to a symbolic link (function) | | [create\_symlinkcreate\_directory\_symlink](create_symlink "cpp/filesystem/create symlink") (C++17)(C++17) | creates a symbolic link (function) | | [copy\_symlink](copy_symlink "cpp/filesystem/copy symlink") (C++17) | copies a symbolic link (function) | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | cpp std::filesystem::copy_symlink std::filesystem::copy\_symlink ============================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` void copy_symlink( const std::filesystem::path& from, const std::filesystem::path& to); ``` | (1) | (since C++17) | | ``` void copy_symlink( const std::filesystem::path& from, const std::filesystem::path& to, std::error_code& ec ) noexcept; ``` | (2) | (since C++17) | Copies a symlink to another location. 1) Effectively calls `f(read_symlink(from), to)` where `f` is [`create_symlink`](create_symlink "cpp/filesystem/create symlink") or [`create_directory_symlink`](create_symlink "cpp/filesystem/create symlink") depending on whether `from` resolves to a file or directory. 2) Effectively calls `f(read_symlink(from, ec), to, ec)` where `f` is [`create_symlink`](create_symlink "cpp/filesystem/create symlink") or [`create_directory_symlink`](create_symlink "cpp/filesystem/create symlink") depending on whether `from` resolves to a file or directory. ### Parameters | | | | | --- | --- | --- | | from | - | path to a symbolic link to copy | | to | - | destination path of the new symlink | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value (none). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `from` as the first path argument, `to` as the second path argument, and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### See also | | | | --- | --- | | [copy](copy "cpp/filesystem/copy") (C++17) | copies files or directories (function) | | [copy\_file](copy_file "cpp/filesystem/copy file") (C++17) | copies file contents (function) | | [create\_symlinkcreate\_directory\_symlink](create_symlink "cpp/filesystem/create symlink") (C++17)(C++17) | creates a symbolic link (function) | | [read\_symlink](read_symlink "cpp/filesystem/read symlink") (C++17) | obtains the target of a symbolic link (function) | cpp std::filesystem::is_empty std::filesystem::is\_empty ========================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool is_empty( const std::filesystem::path& p ); bool is_empty( const std::filesystem::path& p, std::error_code& ec ); ``` | | (since C++17) | Checks whether the given path refers to an empty file or directory. ### Parameters | | | | | --- | --- | --- | | p | - | path to examine | | ec | - | error code to modify in case of error | ### Return value `true` if the file indicated by `p` or if the type indicated `s` refers to an empty file or directory, `false` otherwise. The non-throwing overload returns `false` if an error occurs. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <filesystem> #include <fstream> #include <iostream> #include <cstdio> int main() { namespace fs = std::filesystem; const fs::path tmp_dir{ fs::temp_directory_path() }; std::cout << std::boolalpha << "Temp dir: " << tmp_dir << '\n' << "is_empty(): " << fs::is_empty(tmp_dir) << '\n'; const fs::path tmp_name{ tmp_dir / std::tmpnam(nullptr) }; std::cout << "Temp file: " << tmp_name << '\n'; std::ofstream file{ tmp_name.string() }; std::cout << "is_empty(): " << fs::is_empty(tmp_name) << '\n'; file << "cppreference.com"; file.flush(); std::cout << "is_empty(): " << fs::is_empty(tmp_name) << '\n' << "file_size(): " << fs::file_size(tmp_name) << '\n'; file.close(); fs::remove(tmp_name); } ``` Possible output: ``` Temp dir: "/tmp" is_empty(): false Temp file: "/tmp/fileCqd9DM" is_empty(): true is_empty(): false file_size(): 16 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3013](https://cplusplus.github.io/LWG/issue3013) | C++17 | `error_code` overload marked noexcept but can allocate memory | noexcept removed | ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [exists](exists "cpp/filesystem/exists") (C++17) | checks whether path refers to existing file system object (function) |
programming_docs
cpp std::filesystem::file_size std::filesystem::file\_size =========================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` std::uintmax_t file_size( const std::filesystem::path& p ); std::uintmax_t file_size( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (1) | (since C++17) | If `p` does not exist, reports an error. For a regular file `p`, returns the size determined as if by reading the `st_size` member of the structure obtained by POSIX [`stat`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/stat.html) (symlinks are followed). The result of attempting to determine the size of a directory (as well as any other file that is not a regular file or a symlink) is implementation-defined. The non-throwing overload returns `static\_cast<[std::uintmax\_t](http://en.cppreference.com/w/cpp/types/integer)>(-1)` on errors. ### Parameters | | | | | --- | --- | --- | | p | - | path to examine | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value The size of the file, in bytes. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <cmath> #include <filesystem> #include <fstream> #include <iostream> namespace fs = std::filesystem; struct HumanReadable { std::uintmax_t size{}; private: friend std::ostream& operator<<(std::ostream& os, HumanReadable hr) { int i{}; double mantissa = hr.size; for (; mantissa >= 1024.; mantissa /= 1024., ++i) { } mantissa = std::ceil(mantissa * 10.) / 10.; os << mantissa << "BKMGTPE"[i]; return i == 0 ? os : os << "B (" << hr.size << ')'; } }; int main(int, char const* argv[]) { fs::path example = "example.bin"; fs::path p = fs::current_path() / example; std::ofstream(p).put('a'); // create file of size 1 std::cout << example << " size = " << fs::file_size(p) << '\n'; fs::remove(p); p = argv[0]; std::cout << p << " size = " << HumanReadable{fs::file_size(p)} << '\n'; try { std::cout << "Attempt to get size of a directory:\n"; fs::file_size("/dev"); } catch(fs::filesystem_error& e) { std::cout << e.what() << '\n'; } std::error_code ec; for (fs::path bin: {"cat", "mouse"}) { bin = "/bin"/bin; std::uintmax_t size = fs::file_size(bin, ec); if (ec) { std::cout << bin << " : " << ec.message() << '\n'; } else { std::cout << bin << " size = " << HumanReadable{size} << '\n'; } } } ``` Possible output: ``` "example.bin" size = 1 "./a.out" size = 22KB (22512) Attempt to get size of a directory: filesystem error: cannot get file size: Is a directory [/dev] "/bin/cat" size = 50.9KB (52080) "/bin/mouse" : No such file or directory ``` ### See also | | | | --- | --- | | [resize\_file](resize_file "cpp/filesystem/resize file") (C++17) | changes the size of a regular file by truncation or zero-fill (function) | | [space](space "cpp/filesystem/space") (C++17) | determines available free space on the file system (function) | | [file\_size](directory_entry/file_size "cpp/filesystem/directory entry/file size") | returns the size of the file to which the directory entry refers (public member function of `std::filesystem::directory_entry`) | cpp std::filesystem::resize_file std::filesystem::resize\_file ============================= | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` void resize_file( const std::filesystem::path& p, std::uintmax_t new_size ); void resize_file( const std::filesystem::path& p, std::uintmax_t new_size, std::error_code& ec ) noexcept; ``` | | (since C++17) | Changes the size of the regular file named by `p` as if by POSIX [`truncate`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/truncate.html): if the file size was previously larger than `new_size`, the remainder of the file is discarded. If the file was previously smaller than `new_size`, the file size is increased and the new area appears as if zero-filled. ### Parameters | | | | | --- | --- | --- | | p | - | path to resize | | new\_size | - | size that the file will now have | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value (none). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes On systems that support sparse files, increasing the file size does not increase the space it occupies on the file system: space allocation takes place only when non-zero bytes are written to the file. ### Example demonstrates the effect of creating a sparse file on the free space. ``` #include <iostream> #include <fstream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::path p = fs::temp_directory_path() / "example.bin"; std::ofstream(p).put('a'); std::cout << "File size: " << fs::file_size(p) << '\n' << "Free space: " << fs::space(p).free << '\n'; fs::resize_file(p, 64*1024); // resize to 64 KB std::cout << "File size: " << fs::file_size(p) << '\n' << "Free space: " << fs::space(p).free << '\n'; fs::remove(p); } ``` Possible output: ``` File size: 1 Free space: 31805444096 File size: 65536 Free space: 31805444096 ``` ### See also | | | | --- | --- | | [file\_size](file_size "cpp/filesystem/file size") (C++17) | returns the size of a file (function) | | [space](space "cpp/filesystem/space") (C++17) | determines available free space on the file system (function) | cpp std::filesystem::copy std::filesystem::copy ===================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` void copy( const std::filesystem::path& from, const std::filesystem::path& to ); void copy( const std::filesystem::path& from, const std::filesystem::path& to, std::error_code& ec ); ``` | (1) | (since C++17) | | ``` void copy( const std::filesystem::path& from, const std::filesystem::path& to, std::filesystem::copy_options options ); void copy( const std::filesystem::path& from, const std::filesystem::path& to, std::filesystem::copy_options options, std::error_code& ec ); ``` | (2) | (since C++17) | Copies files and directories, with a variety of options. 1) The default, equivalent to (2) with `copy_options::none` used as `options` 2) Copies the file or directory `from` to file or directory `to`, using the copy options indicated by `options`. The behavior is undefined if there is more than one option in any of the [copy\_options](copy_options "cpp/filesystem/copy options") option group present in `options` (even in the `copy_file` group). The behavior is as follows: * First, before doing anything else, obtains type and permissions of `from` by no more than a single call to + `[std::filesystem::symlink\_status](status "cpp/filesystem/status")`, if `copy_options::skip_symlinks`, `copy_options::copy_symlinks`, or `copy_options::create_symlinks` is present in `options`; + `[std::filesystem::status](status "cpp/filesystem/status")` otherwise. * If necessary, obtains the status of `to`, by no more than a single call to + `[std::filesystem::symlink\_status](status "cpp/filesystem/status")`, if `copy_options::skip_symlinks` or `copy_options::create_symlinks` is present in `options`; + `[std::filesystem::status](status "cpp/filesystem/status")` otherwise (including the case where `copy_options::copy_symlinks` is present in `options`). * If either `from` or `to` has an implementation-defined [file type](file_type "cpp/filesystem/file type"), the effects of this function are implementation-defined. * If `from` does not exist, reports an error. * If `from` and `to` are the same file as determined by `[std::filesystem::equivalent](equivalent "cpp/filesystem/equivalent")`, reports an error * If either `from` or `to` is not a regular file, a directory, or a symlink, as determined by `[std::filesystem::is\_other](is_other "cpp/filesystem/is other")`, reports an error * If `from` is a directory, but `to` is a regular file, reports an error * If `from` is a symbolic link, then + If `copy_options::skip_symlink` is present in `options`, does nothing. + Otherwise, if `to` does not exist and `copy_options::copy_symlinks` is present in `options`, then behaves as if `copy_symlink(from, to)` + Otherwise, reports an error * Otherwise, if `from` is a regular file, then + If `copy_options::directories_only` is present in `options`, does nothing + Otherwise, if `copy_options::create_symlinks` is present in `options`, creates a symlink to `to`. Note: `from` must be an absolute path unless `to` is in the current directory. + Otherwise, if `copy_options::create_hard_links` is present in `options`, creates a hard link to `to` + Otherwise, if `to` is a directory, then behaves as if `copy_file(from, to/from.filename(), options)` (creates a copy of `from` as a file in the directory `to`) + Otherwise, behaves as if `copy_file(from, to, options)` (copies the file) * Otherwise, if `from` is a directory and `copy_options::create_symlinks` is set in `options`, reports an error with an error code equal to `std::make\_error\_code([std::errc::is\_a\_directory](http://en.cppreference.com/w/cpp/error/errc))`. * Otherwise, if `from` is a directory and either `options` has `copy_options::recursive` or is `copy_options::none`, + If `to` does not exist, first executes `create_directory(to, from)` (creates the new directory with a copy of the old directory's attributes) + Then, whether `to` already existed or was just created, iterates over the files contained in `from` as if by `for (const [std::filesystem::directory\_entry](http://en.cppreference.com/w/cpp/filesystem/directory_entry)& x : [std::filesystem::directory\_iterator](http://en.cppreference.com/w/cpp/filesystem/directory_iterator)(from))` and for each directory entry, recursively calls `copy(x.path(), to/x.path().filename(), options | in-recursive-copy)`, where *in-recursive-copy* is a special bit that has no other effect when set in `options`. (The sole purpose of setting this bit is to prevent recursive copying subdirectories if `options` is `copy_options::none`.) * Otherwise does nothing ### Parameters | | | | | --- | --- | --- | | from | - | path to the source file, directory, or symlink | | to | - | path to the target file, directory, or symlink | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value (none). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `from` as the first path argument, `to` as the second path argument, and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes The default behavior when copying directories is the non-recursive copy: the files are copied, but not the subdirectories: ``` // Given // /dir1 contains /dir1/file1, /dir1/file2, /dir1/dir2 // and /dir1/dir2 contains /dir1/dir2/file3 // After std::filesystem::copy("/dir1", "/dir3"); // /dir3 is created (with the attributes of /dir1) // /dir1/file1 is copied to /dir3/file1 // /dir1/file2 is copied to /dir3/file2 ``` While with `copy_options::recursive`, the subdirectories are also copied, with their content, recursively. ``` // ...but after std::filesystem::copy("/dir1", "/dir3", std::filesystem::copy_options::recursive); // /dir3 is created (with the attributes of /dir1) // /dir1/file1 is copied to /dir3/file1 // /dir1/file2 is copied to /dir3/file2 // /dir3/dir2 is created (with the attributes of /dir1/dir2) // /dir1/dir2/file3 is copied to /dir3/dir2/file3 ``` ### Example ``` #include <cstdlib> #include <iostream> #include <fstream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::create_directories("sandbox/dir/subdir"); std::ofstream("sandbox/file1.txt").put('a'); fs::copy("sandbox/file1.txt", "sandbox/file2.txt"); // copy file fs::copy("sandbox/dir", "sandbox/dir2"); // copy directory (non-recursive) const auto copyOptions = fs::copy_options::update_existing | fs::copy_options::recursive | fs::copy_options::directories_only ; fs::copy("sandbox", "sandbox_copy", copyOptions); static_cast<void>(std::system("tree")); fs::remove_all("sandbox"); fs::remove_all("sandbox_copy"); } ``` Possible output: ``` . ├── sandbox │ ├── dir │ │ └── subdir │ ├── dir2 │ ├── file1.txt │ └── file2.txt └── sandbox_copy ├── dir │ └── subdir └── dir2 8 directories, 2 files ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3013](https://cplusplus.github.io/LWG/issue3013) | C++17 | `error_code` overload marked noexcept but can allocate memory | noexcept removed | | [LWG 2682](https://cplusplus.github.io/LWG/issue2682) | C++17 | attempting to create a symlink for a directory succeeds but does nothing | reports an error | ### See also | | | | --- | --- | | [copy\_options](copy_options "cpp/filesystem/copy options") (C++17) | specifies semantics of copy operations (enum) | | [copy\_symlink](copy_symlink "cpp/filesystem/copy symlink") (C++17) | copies a symbolic link (function) | | [copy\_file](copy_file "cpp/filesystem/copy file") (C++17) | copies file contents (function) | cpp std::filesystem::create_hard_link std::filesystem::create\_hard\_link =================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` void create_hard_link( const std::filesystem::path& target, const std::filesystem::path& link ); void create_hard_link( const std::filesystem::path& target, const std::filesystem::path& link, std::error_code& ec ) noexcept; ``` | | (since C++17) | Creates a hard link `link` with its target set to `target` as if by POSIX [`link()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/link.html): the pathname `target` must exist. Once created, `link` and `target` are two logical names that refer to the same file (they are [`equivalent`](equivalent "cpp/filesystem/equivalent")). Even if the original name `target` is deleted, the file continues to exist and is accessible as `link`. ### Parameters | | | | | --- | --- | --- | | target | - | path of the file or directory to link to | | link | - | path of the new hard link | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value (none). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `target` as the first path argument, `link` as the second path argument, and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes Some operating systems do not support hard links at all or support them only for regular files. Some file systems do not support hard links regardless of the operating system: the FAT file system used on memory cards and flash drives, for example. Some file systems limit the number of links per file. Hardlinking to directories is typically restricted to the superuser. Hard links typically cannot cross filesystem boundaries. The special pathname dot (`"."`) is a hard link to its parent directory. The special pathname dot-dot `".."` is a hard link to the directory that is the parent of its parent. ### Example ``` #include <iostream> #include <fstream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::create_directories("sandbox/subdir"); std::ofstream("sandbox/a").put('a'); // create regular file fs::create_hard_link("sandbox/a", "sandbox/b"); fs::remove("sandbox/a"); // read from the original file via surviving hard link char c = std::ifstream("sandbox/b").get(); std::cout << c << '\n'; fs::remove_all("sandbox"); } ``` Output: ``` a ``` ### See also | | | | --- | --- | | [create\_symlinkcreate\_directory\_symlink](create_symlink "cpp/filesystem/create symlink") (C++17)(C++17) | creates a symbolic link (function) | | [hard\_link\_count](hard_link_count "cpp/filesystem/hard link count") (C++17) | returns the number of hard links referring to the specific file (function) | cpp std::filesystem::directory_iterator std::filesystem::directory\_iterator ==================================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` class directory_iterator; ``` | | (since C++17) | `directory_iterator` is a [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator") that iterates over the [`directory_entry`](directory_entry "cpp/filesystem/directory entry") elements of a directory (but does not visit the subdirectories). The iteration order is unspecified, except that each directory entry is visited only once. The special pathnames dot and dot-dot are skipped. If the `directory_iterator` reports an error or is advanced past the last directory entry, it becomes equal to the default-constructed iterator, also known as the end iterator. Two end iterators are always equal, dereferencing or incrementing the end iterator is undefined behavior. If a file or a directory is deleted or added to the directory tree after the directory iterator has been created, it is unspecified whether the change would be observed through the iterator. ### Member types | Member type | Definition | | --- | --- | | `value_type` | `[std::filesystem::directory\_entry](directory_entry "cpp/filesystem/directory entry")` | | `difference_type` | `[std::ptrdiff\_t](../types/ptrdiff_t "cpp/types/ptrdiff t")` | | `pointer` | `const [std::filesystem::directory\_entry](http://en.cppreference.com/w/cpp/filesystem/directory_entry)\*` | | `reference` | `const [std::filesystem::directory\_entry](http://en.cppreference.com/w/cpp/filesystem/directory_entry)&` | | `iterator_category` | `[std::input\_iterator\_tag](../iterator/iterator_tags "cpp/iterator/iterator tags")` | ### Member functions | | | | --- | --- | | [(constructor)](directory_iterator/directory_iterator "cpp/filesystem/directory iterator/directory iterator") | constructs a directory iterator (public member function) | | (destructor) | default destructor (public member function) | | [operator=](directory_iterator/operator= "cpp/filesystem/directory iterator/operator=") | assigns contents (public member function) | | [operator\*operator->](directory_iterator/operator* "cpp/filesystem/directory iterator/operator*") | accesses the pointed-to entry (public member function) | | [incrementoperator++](directory_iterator/increment "cpp/filesystem/directory iterator/increment") | advances to the next entry (public member function) | ### Non-member functions | | | | --- | --- | | [begin(std::filesystem::directory\_iterator)end(std::filesystem::directory\_iterator)](directory_iterator/begin "cpp/filesystem/directory iterator/begin") (C++17) | range-based for loop support (function) | Additionally, `operator==` and `operator!=` are (until C++20)`operator==` is (since C++20) provided as required by [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). It is unspecified whether `operator!=` is provided because it can be synthesized from `operator==`, and (since C++20) whether an equality operator is a member or non-member. ### Helper templates | | | | | --- | --- | --- | | ``` namespace std::ranges { template<> inline constexpr bool enable_borrowed_range<std::filesystem::directory_iterator> = true; } ``` | | (since C++20) | | ``` namespace std::ranges { template<> inline constexpr bool enable_view<std::filesystem::directory_iterator> = true; } ``` | | (since C++20) | These specializations for `directory_iterator` make it a [`borrowed_range`](../ranges/borrowed_range "cpp/ranges/borrowed range") and a [`view`](../ranges/view "cpp/ranges/view"). ### Notes Many low-level OS APIs for directory traversal retrieve file attributes along with the next directory entry. The constructors and the non-const member functions of `std::filesystem::directory_iterator` store these attributes, if any, in the pointed-to `[std::filesystem::directory\_entry](directory_entry "cpp/filesystem/directory entry")` without calling [`directory_entry::refresh`](directory_entry/refresh "cpp/filesystem/directory entry/refresh"), which makes it possible to examine the attributes of the directory entries as they are being iterated over, without making additional system calls. ### Example ``` #include <fstream> #include <iostream> #include <filesystem> #include <algorithm> int main() { const std::filesystem::path sandbox{"sandbox"}; std::filesystem::create_directories(sandbox/"dir1"/"dir2"); std::ofstream{sandbox/"file1.txt"}; std::ofstream{sandbox/"file2.txt"}; std::cout << "directory_iterator:\n"; // directory_iterator can be iterated using a range-for loop for (auto const& dir_entry : std::filesystem::directory_iterator{sandbox}) { std::cout << dir_entry.path() << '\n'; } std::cout << "\ndirectory_iterator as a range:\n"; // directory_iterator behaves as a range in other ways, too std::ranges::for_each( std::filesystem::directory_iterator{sandbox}, [](const auto& dir_entry) { std::cout << dir_entry << '\n'; } ); std::cout << "\nrecursive_directory_iterator:\n"; for (auto const& dir_entry : std::filesystem::recursive_directory_iterator{sandbox}) { std::cout << dir_entry << '\n'; } // delete the sandbox dir and all contents within it, including subdirs std::filesystem::remove_all(sandbox); } ``` Possible output: ``` directory_iterator: "sandbox/file2.txt" "sandbox/file1.txt" "sandbox/dir1" directory_iterator as a range: "sandbox/file2.txt" "sandbox/file1.txt" "sandbox/dir1" recursive_directory_iterator: "sandbox/file2.txt" "sandbox/file1.txt" "sandbox/dir1" "sandbox/dir1/dir2" ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3480](https://cplusplus.github.io/LWG/issue3480) | C++20 | `directory_iterator` was neither a [`borrowed_range`](../ranges/borrowed_range "cpp/ranges/borrowed range") nor a [`view`](../ranges/view "cpp/ranges/view") | it is both | ### See also | | | | --- | --- | | [recursive\_directory\_iterator](recursive_directory_iterator "cpp/filesystem/recursive directory iterator") (C++17) | an iterator to the contents of a directory and its subdirectories (class) | | [directory\_options](directory_options "cpp/filesystem/directory options") (C++17) | options for iterating directory contents (enum) | | [directory\_entry](directory_entry "cpp/filesystem/directory entry") (C++17) | a directory entry (class) |
programming_docs
cpp std::filesystem::directory_entry std::filesystem::directory\_entry ================================= | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` class directory_entry; ``` | | (since C++17) | Represents a directory entry. The object stores a `path` as a member and may also store additional file attributes (hard link count, status, symlink status, file size, and last write time) during directory iteration. ### Member functions | | | | --- | --- | | [(constructor)](directory_entry/directory_entry "cpp/filesystem/directory entry/directory entry") | constructs a directory entry (public member function) | | (destructor) | default destructor (public member function) | | Modifiers | | [operator=](directory_entry/operator= "cpp/filesystem/directory entry/operator=") | assigns contents (public member function) | | [assign](directory_entry/assign "cpp/filesystem/directory entry/assign") | assigns contents (public member function) | | [replace\_filename](directory_entry/replace_filename "cpp/filesystem/directory entry/replace filename") | sets the filename (public member function) | | [refresh](directory_entry/refresh "cpp/filesystem/directory entry/refresh") | updates the cached file attributes (public member function) | | Observers | | [pathoperator const path&](directory_entry/path "cpp/filesystem/directory entry/path") | returns the path the entry refers to (public member function) | | [exists](directory_entry/exists "cpp/filesystem/directory entry/exists") | checks whether directory entry refers to existing file system object (public member function) | | [is\_block\_file](directory_entry/is_block_file "cpp/filesystem/directory entry/is block file") | checks whether the directory entry refers to block device (public member function) | | [is\_character\_file](directory_entry/is_character_file "cpp/filesystem/directory entry/is character file") | checks whether the directory entry refers to a character device (public member function) | | [is\_directory](directory_entry/is_directory "cpp/filesystem/directory entry/is directory") | checks whether the directory entry refers to a directory (public member function) | | [is\_fifo](directory_entry/is_fifo "cpp/filesystem/directory entry/is fifo") | checks whether the directory entry refers to a named pipe (public member function) | | [is\_other](directory_entry/is_other "cpp/filesystem/directory entry/is other") | checks whether the directory entry refers to an *other* file (public member function) | | [is\_regular\_file](directory_entry/is_regular_file "cpp/filesystem/directory entry/is regular file") | checks whether the directory entry refers to a regular file (public member function) | | [is\_socket](directory_entry/is_socket "cpp/filesystem/directory entry/is socket") | checks whether the directory entry refers to a named IPC socket (public member function) | | [is\_symlink](directory_entry/is_symlink "cpp/filesystem/directory entry/is symlink") | checks whether the directory entry refers to a symbolic link (public member function) | | [file\_size](directory_entry/file_size "cpp/filesystem/directory entry/file size") | returns the size of the file to which the directory entry refers (public member function) | | [hard\_link\_count](directory_entry/hard_link_count "cpp/filesystem/directory entry/hard link count") | returns the number of hard links referring to the file to which the directory entry refers (public member function) | | [last\_write\_time](directory_entry/last_write_time "cpp/filesystem/directory entry/last write time") | gets or sets the time of the last data modification of the file to which the directory entry refers (public member function) | | [statussymlink\_status](directory_entry/status "cpp/filesystem/directory entry/status") | status of the file designated by this directory entrysymlink\_status of the file designated by this directory entry (public member function) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](directory_entry/operator_cmp "cpp/filesystem/directory entry/operator cmp") (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) | compares two directory entries (public member function) | ### Non-member functions | | | | --- | --- | | [operator<<](directory_entry/operator_ltlt "cpp/filesystem/directory entry/operator ltlt") | performs stream output on a directory entry (function) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3171](https://cplusplus.github.io/LWG/issue3171) | C++17 | `directory_entry` couldn't be inserted by `operator<<` because of LWG2989 | output enabled again | cpp std::filesystem::file_status std::filesystem::file\_status ============================= | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` class file_status; ``` | | (since C++17) | Stores information about the type and permissions of a file. ### Member functions | | | | --- | --- | | [(constructor)](file_status/file_status "cpp/filesystem/file status/file status") | constructs a `file_status` object (public member function) | | [operator=](file_status/operator= "cpp/filesystem/file status/operator=") | assigns contents (public member function) | | (destructor) | implicit destructor (public member function) | | [type](file_status/type "cpp/filesystem/file status/type") | gets or sets the type of the file (public member function) | | [permissions](file_status/permissions "cpp/filesystem/file status/permissions") | gets or sets the permissions of the file (public member function) | ### Non-member functions | | | | --- | --- | | [operator==](file_status/operator== "cpp/filesystem/file status/operator==") (C++20) | compares two `file_status` objects (function) | ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [statussymlink\_status](directory_entry/status "cpp/filesystem/directory entry/status") | status of the file designated by this directory entrysymlink\_status of the file designated by this directory entry (public member function of `std::filesystem::directory_entry`) | cpp std::filesystem::is_directory std::filesystem::is\_directory ============================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool is_directory( std::filesystem::file_status s ) noexcept; ``` | (1) | (since C++17) | | ``` bool is_directory( const std::filesystem::path& p ); bool is_directory( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (2) | (since C++17) | Checks if the given file status or path corresponds to a directory. 1) Equivalent to `s.type() == file_type::directory`. 2) Equivalent to `is_directory(status(p))` or `is_directory(status(p, ec))`, respectively. ### Parameters | | | | | --- | --- | --- | | s | - | file status to check | | p | - | path to query | | ec | - | error code to modify in case of errors | ### Return value `true` if the file indicated by `p` or if the type indicated `s` refers to a directory, `false` otherwise. The non-throwing overload returns `false` if an error occurs. ### Exceptions 2) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <filesystem> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> namespace fs = std::filesystem; void demo_status(const fs::path& p, fs::file_status s) { std::cout << p; // alternative: switch(s.type()) { case fs::file_type::regular: ...} if(fs::is_regular_file(s)) std::cout << " is a regular file\n"; if(fs::is_directory(s)) std::cout << " is a directory\n"; if(fs::is_block_file(s)) std::cout << " is a block device\n"; if(fs::is_character_file(s)) std::cout << " is a character device\n"; if(fs::is_fifo(s)) std::cout << " is a named IPC pipe\n"; if(fs::is_socket(s)) std::cout << " is a named IPC socket\n"; if(fs::is_symlink(s)) std::cout << " is a symlink\n"; if(!fs::exists(s)) std::cout << " does not exist\n"; } int main() { // create files of different kinds fs::create_directory("sandbox"); std::ofstream("sandbox/file"); // create regular file fs::create_directory("sandbox/dir"); mkfifo("sandbox/pipe", 0644); sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, "sandbox/sock"); int fd = socket(PF_UNIX, SOCK_STREAM, 0); bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof addr); fs::create_symlink("file", "sandbox/symlink"); // demo different status accessors for(auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it) demo_status(*it, it->symlink_status()); // use cached status from directory entry demo_status("/dev/null", fs::status("/dev/null")); // direct calls to status demo_status("/dev/sda", fs::status("/dev/sda")); demo_status("sandbox/no", fs::status("/sandbox/no")); // cleanup close(fd); fs::remove_all("sandbox"); } ``` Possible output: ``` "sandbox/file" is a regular file "sandbox/dir" is a directory "sandbox/pipe" is a named IPC pipe "sandbox/sock" is a named IPC socket "sandbox/symlink" is a symlink "/dev/null" is a character device "/dev/sda" is a block device "sandbox/no" does not exist ``` ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [file\_status](file_status "cpp/filesystem/file status") (C++17) | represents file type and permissions (class) | | [status\_known](status_known "cpp/filesystem/status known") (C++17) | checks whether file status is known (function) | | [is\_block\_file](is_block_file "cpp/filesystem/is block file") (C++17) | checks whether the given path refers to block device (function) | | [is\_character\_file](is_character_file "cpp/filesystem/is character file") (C++17) | checks whether the given path refers to a character device (function) | | [is\_fifo](is_fifo "cpp/filesystem/is fifo") (C++17) | checks whether the given path refers to a named pipe (function) | | [is\_other](is_other "cpp/filesystem/is other") (C++17) | checks whether the argument refers to an *other* file (function) | | [is\_regular\_file](is_regular_file "cpp/filesystem/is regular file") (C++17) | checks whether the argument refers to a regular file (function) | | [is\_socket](is_socket "cpp/filesystem/is socket") (C++17) | checks whether the argument refers to a named IPC socket (function) | | [is\_symlink](is_symlink "cpp/filesystem/is symlink") (C++17) | checks whether the argument refers to a symbolic link (function) | | [exists](exists "cpp/filesystem/exists") (C++17) | checks whether path refers to existing file system object (function) | | [is\_directory](directory_entry/is_directory "cpp/filesystem/directory entry/is directory") | checks whether the directory entry refers to a directory (public member function of `std::filesystem::directory_entry`) | cpp std::filesystem::absolute std::filesystem::absolute ========================= | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` path absolute(const std::filesystem::path& p); path absolute(const std::filesystem::path& p, std::error_code& ec); ``` | | (since C++17) | Returns a path referencing the same file system location as `p`, for which [`filesystem::is_absolute()`](path/is_absrel "cpp/filesystem/path/is absrel") is `true`. The non-throwing overload returns default-constructed path if an error occurs. ### Parameters | | | | | --- | --- | --- | | p | - | path to convert to absolute form | | ec | - | out-parameter for error reporting in the non-throwing overload. | ### Return value Returns an absolute (although not necessarily canonical) pathname referencing the same file as `p`. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes Implementations are encouraged to not consider `p` not existing to be an error. For POSIX-based operating systems, `std::filesystem::absolute(p)` is equivalent to `[std::filesystem::current\_path](http://en.cppreference.com/w/cpp/filesystem/current_path)() / p` except for when `p` is the empty path. For Windows, `std::filesystem::absolute` may be implemented as a call to [`GetFullPathNameW`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364963(v=vs.85).aspx). ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { std::filesystem::path p = "foo.c"; std::cout << "Current path is " << fs::current_path() << '\n'; std::cout << "Absolute path for " << p << " is " << std::filesystem::absolute(p) << '\n'; } ``` Possible output: ``` Current path is "/tmp/1622355667.5363104" Absolute path for "foo.c" is "/tmp/1622355667.5363104/foo.c" ``` ### See also | | | | --- | --- | | [canonicalweakly\_canonical](canonical "cpp/filesystem/canonical") (C++17) | composes a canonical path (function) | | [relativeproximate](relative "cpp/filesystem/relative") (C++17) | composes a relative path (function) | cpp std::filesystem::file_type std::filesystem::file\_type =========================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` enum class file_type { none = /* unspecified */, not_found = /* unspecified */, regular = /* unspecified */, directory = /* unspecified */, symlink = /* unspecified */, block = /* unspecified */, character = /* unspecified */, fifo = /* unspecified */, socket = /* unspecified */, unknown = /* unspecified */, /* implementation-defined */ }; ``` | | (since C++17) | `file_type` defines constants that indicate a type of a file or directory a path refers to. The value of the enumerators are distinct. ### Constants | Constant | Meaning | | --- | --- | | `none` | indicates that the file status has not been evaluated yet, or an error occurred when evaluating it | | `not_found` | indicates that the file was not found (this is not considered an error) | | `regular` | a regular file | | `directory` | a directory | | `symlink` | a symbolic link | | `block` | a block special file | | `character` | a character special file | | `fifo` | a FIFO (also known as pipe) file | | `socket` | a socket file | | implementation-defined | an additional implementation-defined constant for each additional file type supported by the implementation (e.g. MSVC STL defines `junction` for [NTFS junctions](https://docs.microsoft.com/en-us/sysinternals/downloads/junction)) | | `unknown` | the file exists but its type could not be determined | ### Example ``` #include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <filesystem> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> namespace fs = std::filesystem; void demo_status(const fs::path& p, fs::file_status s) { std::cout << p; switch(s.type()) { case fs::file_type::none: std::cout << " has `not-evaluated-yet` type"; break; case fs::file_type::not_found: std::cout << " does not exist"; break; case fs::file_type::regular: std::cout << " is a regular file"; break; case fs::file_type::directory: std::cout << " is a directory"; break; case fs::file_type::symlink: std::cout << " is a symlink"; break; case fs::file_type::block: std::cout << " is a block device"; break; case fs::file_type::character: std::cout << " is a character device"; break; case fs::file_type::fifo: std::cout << " is a named IPC pipe"; break; case fs::file_type::socket: std::cout << " is a named IPC socket"; break; case fs::file_type::unknown: std::cout << " has `unknown` type"; break; default: std::cout << " has `implementation-defined` type"; break; } std::cout << '\n'; } int main() { // create files of different kinds fs::create_directory("sandbox"); std::ofstream("sandbox/file"); // create regular file fs::create_directory("sandbox/dir"); mkfifo("sandbox/pipe", 0644); sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, "sandbox/sock"); int fd = socket(PF_UNIX, SOCK_STREAM, 0); bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof addr); fs::create_symlink("file", "sandbox/symlink"); // demo different status accessors for(auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it) demo_status(*it, it->symlink_status()); // use cached status from directory entry demo_status("/dev/null", fs::status("/dev/null")); // direct calls to status demo_status("/dev/sda", fs::status("/dev/sda")); demo_status("sandbox/no", fs::status("/sandbox/no")); // cleanup close(fd); fs::remove_all("sandbox"); } ``` Possible output: ``` "sandbox/file" is a regular file "sandbox/dir" is a directory "sandbox/pipe" is a named IPC pipe "sandbox/sock" is a named IPC socket "sandbox/symlink" is a symlink "/dev/null" is a character device "/dev/sda" is a block device "sandbox/no" does not exist ``` ### See also | | | | --- | --- | | [file\_status](file_status "cpp/filesystem/file status") (C++17) | represents file type and permissions (class) | | [is\_block\_file](is_block_file "cpp/filesystem/is block file") (C++17) | checks whether the given path refers to block device (function) | | [is\_character\_file](is_character_file "cpp/filesystem/is character file") (C++17) | checks whether the given path refers to a character device (function) | | [is\_directory](is_directory "cpp/filesystem/is directory") (C++17) | checks whether the given path refers to a directory (function) | | [is\_fifo](is_fifo "cpp/filesystem/is fifo") (C++17) | checks whether the given path refers to a named pipe (function) | | [is\_other](is_other "cpp/filesystem/is other") (C++17) | checks whether the argument refers to an *other* file (function) | | [is\_socket](is_socket "cpp/filesystem/is socket") (C++17) | checks whether the argument refers to a named IPC socket (function) | | [is\_symlink](is_symlink "cpp/filesystem/is symlink") (C++17) | checks whether the argument refers to a symbolic link (function) | | [is\_regular\_file](directory_entry/is_regular_file "cpp/filesystem/directory entry/is regular file") | checks whether the directory entry refers to a regular file (public member function of `std::filesystem::directory_entry`) |
programming_docs
cpp std::filesystem::create_symlink, std::filesystem::create_directory_symlink std::filesystem::create\_symlink, std::filesystem::create\_directory\_symlink ============================================================================= | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` void create_symlink( const std::filesystem::path& target, const std::filesystem::path& link ); void create_symlink( const std::filesystem::path& target, const std::filesystem::path& link, std::error_code& ec ) noexcept; ``` | (1) | (since C++17) | | ``` void create_directory_symlink( const std::filesystem::path& target, const std::filesystem::path& link ); void create_directory_symlink( const std::filesystem::path& target, const std::filesystem::path& link, std::error_code& ec ) noexcept; ``` | (2) | (since C++17) | Creates a symbolic link `link` with its target set to `target` as if by POSIX [`symlink()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/symlink.html): the pathname `target` may be invalid or non-existing. Some operating systems require symlink creation to identify that the link is to a directory. Portable code should use (2) to create directory symlinks rather than (1), even though there is no distinction on POSIX systems. ### Parameters | | | | | --- | --- | --- | | target | - | path to point the symlink to, does not have to exist | | link | - | path of the new symbolic link | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value (none). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `target` as the first path argument, `link` as the second path argument, and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes Some operating systems do not support symbolic links at all or support them only for regular files. Some file systems do not support symbolic links regardless of the operating system, for example the FAT system used on some memory cards and flash drives. Like a hard link, a symbolic link allows a file to have multiple logical names. The presence of a hard link guarantees the existence of a file, even after the original name has been removed. A symbolic link provides no such assurance; in fact, the file named by the `target` argument need not exist when the link is created. A symbolic link can cross file system boundaries. ### Example ``` #include <iostream> #include <filesystem> #include <cassert> namespace fs = std::filesystem; int main() { fs::create_directories("sandbox/subdir"); fs::create_symlink("target", "sandbox/sym1"); fs::create_directory_symlink("subdir", "sandbox/sym2"); for(auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it) if(is_symlink(it->symlink_status())) std::cout << *it << "->" << read_symlink(*it) << '\n'; assert( std::filesystem::equivalent("sandbox/sym2", "sandbox/subdir") ); fs::remove_all("sandbox"); } ``` Possible output: ``` "sandbox/sym1"->"target" "sandbox/sym2"->"subdir" ``` ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [read\_symlink](read_symlink "cpp/filesystem/read symlink") (C++17) | obtains the target of a symbolic link (function) | | [create\_hard\_link](create_hard_link "cpp/filesystem/create hard link") (C++17) | creates a hard link (function) | cpp std::filesystem::space std::filesystem::space ====================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` std::filesystem::space_info space(const std::filesystem::path& p); std::filesystem::space_info space(const std::filesystem::path& p, std::error_code& ec) noexcept; ``` | | (since C++17) | Determines the information about the filesystem on which the pathname `p` is located, as if by POSIX [`statvfs`.](http://pubs.opengroup.org/onlinepubs/9699919799/functions/statvfs.html) Populates and returns an object of type [`filesystem::space_info`](space_info "cpp/filesystem/space info"), set from the members of the POSIX `struct statvfs` as follows. * [`space_info.capacity`](space_info "cpp/filesystem/space info") is set as if by `f_blocks*f_frsize` * [`space_info.free`](space_info "cpp/filesystem/space info") is set to `f_bfree*f_frsize` * [`space_info.available`](space_info "cpp/filesystem/space info") is set to `f_bavail*f_frsize` * Any member that could not be determined is set to `static\_cast<[std::uintmax\_t](http://en.cppreference.com/w/cpp/types/integer)>(-1)` The non-throwing overload sets all members to `static\_cast<[std::uintmax\_t](http://en.cppreference.com/w/cpp/types/integer)>(-1)` on error. ### Parameters | | | | | --- | --- | --- | | p | - | path to examine | | ec | - | out-parameter for error reporting in the non-throwing overload. | ### Return value The filesystem information (a [`filesystem::space_info`](space_info "cpp/filesystem/space info") object). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes [`space_info.available`](space_info "cpp/filesystem/space info") may be less than [`space_info.free`](space_info "cpp/filesystem/space info"). ### Example ``` #include <iostream> #include <filesystem> #include <cstdint> void print_space_info(auto const& dirs, int width = 14) { std::cout << std::left; for (const auto s : {"Capacity", "Free", "Available", "Dir"}) std::cout << "│ " << std::setw(width) << s << ' '; std::cout << '\n'; std::error_code ec; for (auto const& dir : dirs) { const std::filesystem::space_info si = std::filesystem::space(dir, ec); std::cout << "│ " << std::setw(width) << static_cast<std::intmax_t>(si.capacity) << ' ' << "│ " << std::setw(width) << static_cast<std::intmax_t>(si.free) << ' ' << "│ " << std::setw(width) << static_cast<std::intmax_t>(si.available) << ' ' << "│ " << dir << '\n'; } } int main() { const auto dirs = { "/dev/null", "/tmp", "/home", "/null" }; print_space_info(dirs); } ``` Possible output: ``` │ Capacity │ Free │ Available │ Dir │ 8342851584 │ 8342851584 │ 8342851584 │ /dev/null │ 12884901888 │ 3045265408 │ 3045265408 │ /tmp │ 250321567744 │ 37623181312 │ 25152159744 │ /home │ -1 │ -1 │ -1 │ /null ``` ### See also | | | | --- | --- | | [space\_info](space_info "cpp/filesystem/space info") (C++17) | information about free and available space on the filesystem (class) | cpp std::filesystem::is_symlink std::filesystem::is\_symlink ============================ | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` bool is_symlink( std::filesystem::file_status s ) noexcept; ``` | (1) | (since C++17) | | ``` bool is_symlink( const std::filesystem::path& p ); bool is_symlink( const std::filesystem::path& p, std::error_code& ec ) noexcept; ``` | (2) | (since C++17) | Checks if the given file status or path corresponds to a symbolic link, as if determined by the POSIX [`S_IFLNK`](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html). 1) Equivalent to `s.type() == file_type::symlink`. 2) Equivalent to `is_symlink(symlink_status(p))` or `is_symlink(symlink_status(p, ec))`. ### Parameters | | | | | --- | --- | --- | | s | - | file status to check | | p | - | path to examine | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the file indicated by `p` or if the type indicated `s` refers to a symbolic link. The non-throwing overload returns `false` if an error occurs. ### Exceptions 2) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <filesystem> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> namespace fs = std::filesystem; void demo_status(const fs::path& p, fs::file_status s) { std::cout << p; // alternative: switch(s.type()) { case fs::file_type::regular: ...} if(fs::is_regular_file(s)) std::cout << " is a regular file\n"; if(fs::is_directory(s)) std::cout << " is a directory\n"; if(fs::is_block_file(s)) std::cout << " is a block device\n"; if(fs::is_character_file(s)) std::cout << " is a character device\n"; if(fs::is_fifo(s)) std::cout << " is a named IPC pipe\n"; if(fs::is_socket(s)) std::cout << " is a named IPC socket\n"; if(fs::is_symlink(s)) std::cout << " is a symlink\n"; if(!fs::exists(s)) std::cout << " does not exist\n"; } int main() { // create files of different kinds fs::create_directory("sandbox"); std::ofstream("sandbox/file"); // create regular file fs::create_directory("sandbox/dir"); mkfifo("sandbox/pipe", 0644); sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, "sandbox/sock"); int fd = socket(PF_UNIX, SOCK_STREAM, 0); bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof addr); fs::create_symlink("file", "sandbox/symlink"); // demo different status accessors for(auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it) demo_status(*it, it->symlink_status()); // use cached status from directory entry demo_status("/dev/null", fs::status("/dev/null")); // direct calls to status demo_status("/dev/sda", fs::status("/dev/sda")); demo_status("sandbox/no", fs::status("/sandbox/no")); // cleanup close(fd); fs::remove_all("sandbox"); } ``` Possible output: ``` "sandbox/file" is a regular file "sandbox/dir" is a directory "sandbox/pipe" is a named IPC pipe "sandbox/sock" is a named IPC socket "sandbox/symlink" is a symlink "/dev/null" is a character device "/dev/sda" is a block device "sandbox/no" does not exist ``` ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | | [file\_status](file_status "cpp/filesystem/file status") (C++17) | represents file type and permissions (class) | | [status\_known](status_known "cpp/filesystem/status known") (C++17) | checks whether file status is known (function) | | [is\_block\_file](is_block_file "cpp/filesystem/is block file") (C++17) | checks whether the given path refers to block device (function) | | [is\_character\_file](is_character_file "cpp/filesystem/is character file") (C++17) | checks whether the given path refers to a character device (function) | | [is\_directory](is_directory "cpp/filesystem/is directory") (C++17) | checks whether the given path refers to a directory (function) | | [is\_fifo](is_fifo "cpp/filesystem/is fifo") (C++17) | checks whether the given path refers to a named pipe (function) | | [is\_other](is_other "cpp/filesystem/is other") (C++17) | checks whether the argument refers to an *other* file (function) | | [is\_regular\_file](is_regular_file "cpp/filesystem/is regular file") (C++17) | checks whether the argument refers to a regular file (function) | | [is\_socket](is_socket "cpp/filesystem/is socket") (C++17) | checks whether the argument refers to a named IPC socket (function) | | [exists](exists "cpp/filesystem/exists") (C++17) | checks whether path refers to existing file system object (function) | | [is\_symlink](directory_entry/is_symlink "cpp/filesystem/directory entry/is symlink") | checks whether the directory entry refers to a symbolic link (public member function of `std::filesystem::directory_entry`) | cpp std::filesystem::permissions std::filesystem::permissions ============================ | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` void permissions( const std::filesystem::path& p, std::filesystem::perms prms, std::filesystem::perm_options opts = perm_options::replace ); void permissions( const std::filesystem::path& p, std::filesystem::perms prms, std::error_code& ec ) noexcept; void permissions( const std::filesystem::path& p, std::filesystem::perms prms, std::filesystem::perm_options opts, std::error_code& ec ); ``` | | (since C++17) | Changes access permissions of the file to which `p` resolves, as if by POSIX [`fchmodat`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fchmodat.html). Symlinks are followed unless `perm_options::nofollow` is set in `opts`. The second signature behaves as if called with `opts` set to `perm_options::replace`. The effects depend on `prms` and `opts` as follows: * If `opts` is `perm_options::replace`, file permissions are set to exactly `prms & [std::filesystem::perms::mask](http://en.cppreference.com/w/cpp/filesystem/perms)` (meaning, every valid bit of `prms` is applied) * If `opts` is `perm_options::add`, the file permissions are set to exactly `status(p).permissions() | (prms & perms::mask)` (meaning, any valid bit that is set in `prms`, but not in the file's current permissions is added to the file's permissions) * If `opts` is `perm_options::remove`, the file permissions are set to exactly `status(p).permissions() & ~(prms & perms::mask)` (meaning, any valid bit that is clear in `prms`, but set in the file's current permissions is cleared in the file's permissions) `opts` is required to have only one of `replace`, `add`, or `remove` to be set. The non-throwing overload has no special action on error. ### Parameters | | | | | --- | --- | --- | | p | - | path to examine | | prms | - | permissions to set, add, or remove | | opts | - | options controlling the action taken by this function | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value (none). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes Permissions may not necessarily be implemented as bits, but they are treated that way conceptually. Some permission bits may be ignored on some systems, and changing some bits may automatically change others (e.g. on platforms without owner/group/all distinction, setting any of the three write bits set all three). ### Example ``` #include <fstream> #include <bitset> #include <iostream> #include <filesystem> namespace fs = std::filesystem; void demo_perms(fs::perms p) { std::cout << ((p & fs::perms::owner_read) != fs::perms::none ? "r" : "-") << ((p & fs::perms::owner_write) != fs::perms::none ? "w" : "-") << ((p & fs::perms::owner_exec) != fs::perms::none ? "x" : "-") << ((p & fs::perms::group_read) != fs::perms::none ? "r" : "-") << ((p & fs::perms::group_write) != fs::perms::none ? "w" : "-") << ((p & fs::perms::group_exec) != fs::perms::none ? "x" : "-") << ((p & fs::perms::others_read) != fs::perms::none ? "r" : "-") << ((p & fs::perms::others_write) != fs::perms::none ? "w" : "-") << ((p & fs::perms::others_exec) != fs::perms::none ? "x" : "-") << '\n'; } int main() { std::ofstream("test.txt"); // create file std::cout << "Created file with permissions: "; demo_perms(fs::status("test.txt").permissions()); fs::permissions("test.txt", fs::perms::owner_all | fs::perms::group_all, fs::perm_options::add); std::cout << "After adding u+rwx and g+rwx: "; demo_perms(fs::status("test.txt").permissions()); fs::remove("test.txt"); } ``` Possible output: ``` Created file with permissions: rw-r--r-- After adding u+rwx and g+wrx: rwxrwxr-- ``` ### See also | | | | --- | --- | | [perms](perms "cpp/filesystem/perms") (C++17) | identifies file system permissions (enum) | | [statussymlink\_status](status "cpp/filesystem/status") (C++17)(C++17) | determines file attributesdetermines file attributes, checking the symlink target (function) | cpp std::filesystem::path std::filesystem::path ===================== | Defined in header `[<filesystem>](../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` class path; ``` | | (since C++17) | Objects of type `path` represent paths on a filesystem. Only syntactic aspects of paths are handled: the pathname may represent a non-existing path or even one that is not allowed to exist on the current file system or OS. The path name has the following syntax: 1. root-name(optional): identifies the root on a filesystem with multiple roots (such as `"C:"` or `"//myserver"`). In case of ambiguity, the longest sequence of characters that forms a valid root-name is treated as the root-name. The standard library may define additional root-names besides the ones understood by the OS API. 2. root-directory(optional): a directory separator that, if present, marks this path as *absolute*. If it is missing (and the first element other than the root name is a file name), then the path is *relative* and requires another path as the starting location to resolve to a file name. 3. Zero or more of the following: * file-name: sequence of characters that aren't directory separators or preferred directory separators (additional limitations may be imposed by the OS or file system). This name may identify a file, a hard link, a symbolic link, or a directory. Two special file-names are recognized: + dot: the file name consisting of a single dot character `.` is a directory name that refers to the current directory + dot-dot: the file name consisting of two dot characters `..` is a directory name that refers to the parent directory. * directory-separators: the forward slash character `/` or the alternative character provided as `path::preferred_separator`. If this character is repeated, it is treated as a single directory separator: `/usr///////lib` is the same as `/usr/lib` A path can be *normalized* by following this algorithm: 1. If the path is empty, stop (normal form of an empty path is an empty path) 2. Replace each directory-separator (which may consist of multiple slashes) with a single `path::preferred_separator`. 3. Replace each slash character in the root-name with `path::preferred_separator`. 4. Remove each dot and any immediately following directory-separator. 5. Remove each non-dot-dot filename immediately followed by a directory-separator and a dot-dot, along with any immediately following directory-separator. 6. If there is root-directory, remove all dot-dots and any directory-separators immediately following them. 7. If the last filename is dot-dot, remove any trailing directory-separator. 8. If the path is empty, add a dot (normal form of `./` is `.`) The path can be traversed element-wise via iterators returned by the `[begin()](path/begin "cpp/filesystem/path/begin")` and `[end()](path/begin "cpp/filesystem/path/begin")` functions, which views the path in generic format and iterates over root name, root directory, and the subsequent file name elements (directory separators are skipped except the one that identifies the root directory). If the very last element in the path is a directory separator, the last iterator will dereference to an empty element. Calling any non-const member function of a `path` invalidates all iterators referring to elements of that object. If the OS uses a *native* syntax that is different from the portable *generic* syntax described above, library functions that are defined to accept "detected format" accept path names in both formats: a detected format argument is taken to be in the generic format if and only if it matches the generic format but is not acceptable to the operating system as a native path. On those OS where native format differs between pathnames of directories and pathnames of files, a generic pathname is treated as a directory path if it ends on a directory separator and a regular file otherwise. In any case, the path class behaves as if it stores a pathname in the native format and automatically converts to generic format as needed (each member function specifies which format it interprets the path as). On POSIX systems, the generic format is the native format and there is no need to distinguish or convert between them. Paths are implicitly convertible to and from `[std::basic\_string](../string/basic_string "cpp/string/basic string")`s, which makes it possible to use them with other file APIs. The [stream operators](path/operator_ltltgtgt "cpp/filesystem/path/operator ltltgtgt") use `[std::quoted](../io/manip/quoted "cpp/io/manip/quoted")` so that spaces do not cause truncation when later read by [stream input operator](path/operator_ltltgtgt "cpp/filesystem/path/operator ltltgtgt"). [Decomposition member functions](#Decomposition) (e.g. `[extension](path/extension "cpp/filesystem/path/extension")`) return `filesystem::path` objects instead of string objects as other APIs do. ### Member types and constants | Type | Definition | | --- | --- | | `value_type` | character type used by the native encoding of the filesystem: `char` on POSIX, `wchar_t` on Windows | | `string_type` | `[std::basic\_string](http://en.cppreference.com/w/cpp/string/basic_string)<value_type>` | | `const_iterator` | a constant [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") with a `value_type` of `path`, except that for dereferenceable iterators `a` and `b` of type `path::iterator` with `a == b`, there is no requirement that `*a` and `*b` are bound to the same object | | `iterator` | an alias to `const_iterator` | | [format](path/format "cpp/filesystem/path/format") | determines how to interpret string representations of pathnames The following enumerators are also defined: | Constant | Explanation | | --- | --- | | [`native_format`](path/format "cpp/filesystem/path/format") | native pathname format | | [`generic_format`](path/format "cpp/filesystem/path/format") | generic pathname format | | [`auto_format`](path/format "cpp/filesystem/path/format") | implementation-defined format, auto-detected where possible | (enum) | ### Member constants | | | | --- | --- | | constexpr value\_type preferred\_separator [static] | alternative directory separator which may be used in addition to the portable `/`. On Windows, this is the backslash character `\`. On POSIX, this is the same forward slash `/` as the portable separator (public static member constant) | ### Member functions | | | | --- | --- | | [(constructor)](path/path "cpp/filesystem/path/path") | constructs a `path` (public member function) | | [(destructor)](path/~path "cpp/filesystem/path/~path") | destroys a `path` object (public member function) | | [operator=](path/operator= "cpp/filesystem/path/operator=") | assigns another path (public member function) | | [assign](path/assign "cpp/filesystem/path/assign") | assigns contents (public member function) | | Concatenation | | [appendoperator/=](path/append "cpp/filesystem/path/append") | appends elements to the path with a directory separator (public member function) | | [concatoperator+=](path/concat "cpp/filesystem/path/concat") | concatenates two paths without introducing a directory separator (public member function) | | Modifiers | | [clear](path/clear "cpp/filesystem/path/clear") | erases the contents (public member function) | | [make\_preferred](path/make_preferred "cpp/filesystem/path/make preferred") | converts directory separators to preferred directory separator (public member function) | | [remove\_filename](path/remove_filename "cpp/filesystem/path/remove filename") | removes filename path component (public member function) | | [replace\_filename](path/replace_filename "cpp/filesystem/path/replace filename") | replaces the last path component with another path (public member function) | | [replace\_extension](path/replace_extension "cpp/filesystem/path/replace extension") | replaces the extension (public member function) | | [swap](path/swap "cpp/filesystem/path/swap") | swaps two paths (public member function) | | Format observers | | [c\_strnativeoperator string\_type](path/native "cpp/filesystem/path/native") | returns the native version of the path (public member function) | | [stringwstringu8stringu16stringu32string](path/string "cpp/filesystem/path/string") | returns the path in native pathname format converted to a string (public member function) | | [generic\_stringgeneric\_wstringgeneric\_u8stringgeneric\_u16stringgeneric\_u32string](path/generic_string "cpp/filesystem/path/generic string") | returns the path in generic pathname format converted to a string (public member function) | | Compare | | [compare](path/compare "cpp/filesystem/path/compare") | compares the lexical representations of two paths lexicographically (public member function) | | Generation | | [lexically\_normallexically\_relativelexically\_proximate](path/lexically_normal "cpp/filesystem/path/lexically normal") | converts path to normal formconverts path to relative formconverts path to proximate form (public member function) | | Decomposition | | [root\_name](path/root_name "cpp/filesystem/path/root name") | returns the root-name of the path, if present (public member function) | | [root\_directory](path/root_directory "cpp/filesystem/path/root directory") | returns the root directory of the path, if present (public member function) | | [root\_path](path/root_path "cpp/filesystem/path/root path") | returns the root path of the path, if present (public member function) | | [relative\_path](path/relative_path "cpp/filesystem/path/relative path") | returns path relative to the root path (public member function) | | [parent\_path](path/parent_path "cpp/filesystem/path/parent path") | returns the path of the parent path (public member function) | | [filename](path/filename "cpp/filesystem/path/filename") | returns the filename path component (public member function) | | [stem](path/stem "cpp/filesystem/path/stem") | returns the stem path component (filename without the final extension) (public member function) | | [extension](path/extension "cpp/filesystem/path/extension") | returns the file extension path component (public member function) | | Queries | | [empty](path/empty "cpp/filesystem/path/empty") | checks if the path is empty (public member function) | | [has\_root\_pathhas\_root\_namehas\_root\_directoryhas\_relative\_pathhas\_parent\_pathhas\_filenamehas\_stemhas\_extension](path/has_path "cpp/filesystem/path/has path") | checks if the corresponding path element is not empty (public member function) | | [is\_absoluteis\_relative](path/is_absrel "cpp/filesystem/path/is absrel") | checks if `[root\_path()](path/root_path "cpp/filesystem/path/root path")` uniquely identifies file system location (public member function) | | Iterators | | [beginend](path/begin "cpp/filesystem/path/begin") | iterator access to the path as a sequence of elements (public member function) | ### Non-member functions | Defined in namespace `std::filesystem` | | --- | | [swap(std::filesystem::path)](path/swap2 "cpp/filesystem/path/swap2") (C++17) | swaps two paths (function) | | [hash\_value](path/hash_value "cpp/filesystem/path/hash value") | calculates a hash value for a path object (function) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](path/operator_cmp "cpp/filesystem/path/operator cmp") (until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20) | lexicographically compares two paths (function) | | [operator/](path/operator_slash "cpp/filesystem/path/operator slash") | concatenates two paths with a directory separator (function) | | [operator<<operator>>](path/operator_ltltgtgt "cpp/filesystem/path/operator ltltgtgt") | performs stream input and output on a quoted path (function) | | [u8path](path/u8path "cpp/filesystem/path/u8path") (C++17)(deprecated in C++20) | creates a `path` from a UTF-8 encoded source (function) | ### Helper classes | Defined in namespace `std` | | --- | | [std::hash<std::filesystem::path>](path/hash "cpp/filesystem/path/hash") (C++17) | hash support for `std::filesystem::path` (class template specialization) | ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3657](https://cplusplus.github.io/LWG/issue3657) | C++17 | `hash` for `path` was disabled | enabled |
programming_docs
cpp std::filesystem::directory_entry::hard_link_count std::filesystem::directory\_entry::hard\_link\_count ==================================================== | | | | | --- | --- | --- | | ``` std::uintmax_t hard_link_count() const; std::uintmax_t hard_link_count( std::error_code& ec ) const noexcept; ``` | | (since C++17) | If the number of hard links is cached in this [`directory_entry`](directory_entry "cpp/filesystem/directory entry/directory entry"), returns the cached value. Otherwise, returns `[std::filesystem::hard\_link\_count](http://en.cppreference.com/w/cpp/filesystem/hard_link_count)(path())` or `[std::filesystem::hard\_link\_count](http://en.cppreference.com/w/cpp/filesystem/hard_link_count)(path(), ec)`, respectively. ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value The number of hard links for the referred-to filesystem object. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ### See also | | | | --- | --- | | [hard\_link\_count](../hard_link_count "cpp/filesystem/hard link count") (C++17) | returns the number of hard links referring to the specific file (function) | cpp std::filesystem::directory_entry::is_character_file std::filesystem::directory\_entry::is\_character\_file ====================================================== | | | | | --- | --- | --- | | ``` bool is_character_file() const; bool is_character_file( std::error_code& ec ) const noexcept; ``` | | (since C++17) | Checks whether the pointed-to object is a character device. Effectively returns `[std::filesystem::is\_character\_file](http://en.cppreference.com/w/cpp/filesystem/is_character_file)(status())` or `[std::filesystem::is\_character\_file](http://en.cppreference.com/w/cpp/filesystem/is_character_file)(status(ec))`, respectively. ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the referred-to filesystem object is a character device, `false` otherwise. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <cstdio> #include <cstring> #include <filesystem> #include <fstream> #include <functional> #include <iostream> #include <memory> #include <sys/socket.h> #include <sys/stat.h> #include <sys/un.h> #include <unistd.h> namespace fs = std::filesystem; void print_entry_type(std::filesystem::directory_entry const& entry) { std::cout << entry.path() << ": "; if (!entry.exists()) std::cout << "does not exist "; if (entry.is_block_file()) std::cout << "is a block device "; if (entry.is_character_file()) std::cout << "is a character device "; if (entry.is_directory()) std::cout << "is a directory "; if (entry.is_fifo()) std::cout << "is a named IPC pipe "; if (entry.is_regular_file()) std::cout << "is a regular file "; if (entry.is_socket()) std::cout << "is a named IPC socket "; if (entry.is_symlink()) std::cout << "(a symlink) "; if (entry.is_other()) std::cout << "(an `other` file) "; std::cout <<'\n'; } template <typename Type, typename Fun> class scoped_cleanup { std::unique_ptr<Type, std::function<void(const Type*)>> u; public: scoped_cleanup(Type* ptr, Fun fun) : u{ptr, std::move(fun)} {} }; int main() { // create files of different kinds std::filesystem::current_path(fs::temp_directory_path()); const std::filesystem::path sandbox{"sandbox"}; scoped_cleanup remove_all_at_exit{&sandbox, [](const fs::path* p) { std::cout << "cleanup: remove_all(" << *p << ")\n"; fs::remove_all(*p); } }; std::filesystem::create_directory(sandbox); std::ofstream{sandbox/"file"}; // creates a regular file std::filesystem::create_directory(sandbox/"dir"); mkfifo((sandbox/"pipe").string().data(), 0644); struct sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, (sandbox/"sock").string().data()); int fd {socket(PF_UNIX, SOCK_STREAM, 0)}; scoped_cleanup close_socket_at_exit{&fd, [](const int* f) { std::cout << "cleanup: close socket #" << *f << '\n'; close(*f); } }; bind(fd, reinterpret_cast<sockaddr*>(std::addressof(addr)), sizeof addr); fs::create_symlink("file", sandbox/"symlink"); for (std::filesystem::directory_entry entry: fs::directory_iterator(sandbox)) { print_entry_type(entry); } // direct calls to status: for (const char* str: {"/dev/null", "/dev/cpu", "/usr/include/c++", "/usr/include/asm", "/usr/include/time.h"}) { print_entry_type(fs::directory_entry{str}); } } // cleanup via `scoped_cleanup` objects ``` Possible output: ``` "sandbox/symlink": is a regular file (a symlink) "sandbox/sock": is a named IPC socket (an `other` file) "sandbox/pipe": is a named IPC pipe (an `other` file) "sandbox/dir": is a directory "sandbox/file": is a regular file "/dev/null": is a character device (an `other` file) "/dev/cpu": does not exist "/usr/include/c++": is a directory "/usr/include/asm": is a directory (a symlink) "/usr/include/time.h": is a regular file cleanup: close socket #3 cleanup: remove_all("sandbox") ``` ### See also | | | | --- | --- | | [is\_character\_file](../is_character_file "cpp/filesystem/is character file") (C++17) | checks whether the given path refers to a character device (function) | cpp std::filesystem::directory_entry::is_fifo std::filesystem::directory\_entry::is\_fifo =========================================== | | | | | --- | --- | --- | | ``` bool is_fifo() const; bool is_fifo( std::error_code& ec ) const noexcept; ``` | | (since C++17) | Checks whether the pointed-to object is a FIFO or pipe file. Effectively returns `[std::filesystem::is\_fifo](http://en.cppreference.com/w/cpp/filesystem/is_fifo)(status())` or `[std::filesystem::is\_fifo](http://en.cppreference.com/w/cpp/filesystem/is_fifo)(status(ec))`, respectively. ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the referred-to filesystem object is a FIFO or pipe file, `false` otherwise. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <cstdio> #include <cstring> #include <filesystem> #include <fstream> #include <functional> #include <iostream> #include <memory> #include <sys/socket.h> #include <sys/stat.h> #include <sys/un.h> #include <unistd.h> namespace fs = std::filesystem; void print_entry_type(std::filesystem::directory_entry const& entry) { std::cout << entry.path() << ": "; if (!entry.exists()) std::cout << "does not exist "; if (entry.is_block_file()) std::cout << "is a block device "; if (entry.is_character_file()) std::cout << "is a character device "; if (entry.is_directory()) std::cout << "is a directory "; if (entry.is_fifo()) std::cout << "is a named IPC pipe "; if (entry.is_regular_file()) std::cout << "is a regular file "; if (entry.is_socket()) std::cout << "is a named IPC socket "; if (entry.is_symlink()) std::cout << "(a symlink) "; if (entry.is_other()) std::cout << "(an `other` file) "; std::cout <<'\n'; } template <typename Type, typename Fun> class scoped_cleanup { std::unique_ptr<Type, std::function<void(const Type*)>> u; public: scoped_cleanup(Type* ptr, Fun fun) : u{ptr, std::move(fun)} {} }; int main() { // create files of different kinds std::filesystem::current_path(fs::temp_directory_path()); const std::filesystem::path sandbox{"sandbox"}; scoped_cleanup remove_all_at_exit{&sandbox, [](const fs::path* p) { std::cout << "cleanup: remove_all(" << *p << ")\n"; fs::remove_all(*p); } }; std::filesystem::create_directory(sandbox); std::ofstream{sandbox/"file"}; // creates a regular file std::filesystem::create_directory(sandbox/"dir"); mkfifo((sandbox/"pipe").string().data(), 0644); struct sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, (sandbox/"sock").string().data()); int fd {socket(PF_UNIX, SOCK_STREAM, 0)}; scoped_cleanup close_socket_at_exit{&fd, [](const int* f) { std::cout << "cleanup: close socket #" << *f << '\n'; close(*f); } }; bind(fd, reinterpret_cast<sockaddr*>(std::addressof(addr)), sizeof addr); fs::create_symlink("file", sandbox/"symlink"); for (std::filesystem::directory_entry entry: fs::directory_iterator(sandbox)) { print_entry_type(entry); } // direct calls to status: for (const char* str: {"/dev/null", "/dev/cpu", "/usr/include/c++", "/usr/include/asm", "/usr/include/time.h"}) { print_entry_type(fs::directory_entry{str}); } } // cleanup via `scoped_cleanup` objects ``` Possible output: ``` "sandbox/symlink": is a regular file (a symlink) "sandbox/sock": is a named IPC socket (an `other` file) "sandbox/pipe": is a named IPC pipe (an `other` file) "sandbox/dir": is a directory "sandbox/file": is a regular file "/dev/null": is a character device (an `other` file) "/dev/cpu": does not exist "/usr/include/c++": is a directory "/usr/include/asm": is a directory (a symlink) "/usr/include/time.h": is a regular file cleanup: close socket #3 cleanup: remove_all("sandbox") ``` ### See also | | | | --- | --- | | [is\_fifo](../is_fifo "cpp/filesystem/is fifo") (C++17) | checks whether the given path refers to a named pipe (function) | cpp std::filesystem::directory_entry::exists std::filesystem::directory\_entry::exists ========================================= | | | | | --- | --- | --- | | ``` bool exists() const; bool exists( std::error_code& ec ) const noexcept; ``` | | (since C++17) | Checks whether the pointed-to object exists. Effectively returns `[std::filesystem::exists](http://en.cppreference.com/w/cpp/filesystem/exists)(status())` or `[std::filesystem::exists](http://en.cppreference.com/w/cpp/filesystem/exists)(status(ec))`, respectively. ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the referred-to filesystem object exists. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <filesystem> #include <fstream> #include <iostream> #include <string> namespace fs = std::filesystem; int main() { // store current path to restore it at exit const auto old_current_path = fs::current_path(); // create "sanbox" directory in temp dir const auto dir_sandbox = fs::temp_directory_path() / "sandbox"; if (!fs::create_directory(dir_sandbox)) { std::cout << "ERROR #1" << '\n'; return -1; } fs::current_path(dir_sandbox); // switch to newly created dir fs::directory_entry entry_sandbox { dir_sandbox }; if (!entry_sandbox.exists()) { std::cout << "ERROR #2" << '\n'; return -1; } std::cout << "Current dir: " << entry_sandbox.path().filename() << '\n'; fs::path path_tmp_file = dir_sandbox / "tmp_file"; std::ofstream file( path_tmp_file.string() ); // create regular file file << "cppreference.com"; // write 16 bytes file.flush(); fs::directory_entry entry_tmp_file{ path_tmp_file }; if (entry_tmp_file.exists()) { std::cout << "File " << entry_tmp_file.path().filename() << " has size: " << entry_tmp_file.file_size() << '\n'; } else { std::cout << "ERROR #3" << '\n'; } // cleanup fs::current_path(old_current_path); fs::remove_all(dir_sandbox); } ``` Possible output: ``` Current dir: "sandbox" File "tmp_file" has size: 16 ``` ### See also | | | | --- | --- | | [exists](../exists "cpp/filesystem/exists") (C++17) | checks whether path refers to existing file system object (function) | cpp std::filesystem::directory_entry::status, std::filesystem::directory_entry::symlink_status std::filesystem::directory\_entry::status, std::filesystem::directory\_entry::symlink\_status ============================================================================================= | | | | | --- | --- | --- | | ``` std::filesystem::file_status status() const; std::filesystem::file_status status( std::error_code& ec ) const noexcept; ``` | (1) | (since C++17) | | ``` std::filesystem::file_status symlink_status() const; std::filesystem::file_status symlink_status( std::error_code& ec ) const noexcept; ``` | (2) | (since C++17) | 1) Returns status of the entry, as if determined by a `[filesystem::status](../status "cpp/filesystem/status")` call (symlinks are followed to their targets). 2) Returns status of the entry, as if determined by a `[filesystem::symlink\_status](../status "cpp/filesystem/status")` call (symlinks are not followed). ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value The status of the file referred to by the entry. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes Many low-level OS APIs for directory traversal retrieve file attributes along with the next directory entry. The constructors and the non-const member functions of `[std::filesystem::directory\_iterator](../directory_iterator "cpp/filesystem/directory iterator")` store these attributes, if any, in the pointed-to `[std::filesystem::directory\_entry](../directory_entry "cpp/filesystem/directory entry")` without calling [`directory_entry::refresh`](refresh "cpp/filesystem/directory entry/refresh"), which makes it possible to examine the attributes of the directory entries as they are being iterated over, without making additional system calls. ### Example ``` #include <iostream> #include <fstream> #include <cstdio> #include <cstring> #include <filesystem> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> namespace fs = std::filesystem; void demo_status(const fs::path& p, fs::file_status s) { std::cout << p; // alternative: switch(s.type()) { case fs::file_type::regular: ...} if(fs::is_regular_file(s)) std::cout << " is a regular file\n"; if(fs::is_directory(s)) std::cout << " is a directory\n"; if(fs::is_block_file(s)) std::cout << " is a block device\n"; if(fs::is_character_file(s)) std::cout << " is a character device\n"; if(fs::is_fifo(s)) std::cout << " is a named IPC pipe\n"; if(fs::is_socket(s)) std::cout << " is a named IPC socket\n"; if(fs::is_symlink(s)) std::cout << " is a symlink\n"; if(!fs::exists(s)) std::cout << " does not exist\n"; } int main() { // create files of different kinds fs::create_directory("sandbox"); std::ofstream("sandbox/file"); // create regular file fs::create_directory("sandbox/dir"); mkfifo("sandbox/pipe", 0644); sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, "sandbox/sock"); int fd = socket(PF_UNIX, SOCK_STREAM, 0); bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof addr); fs::create_symlink("file", "sandbox/symlink"); // demo different status accessors for(auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it) demo_status(*it, it->symlink_status()); // use cached status from directory entry demo_status("/dev/null", fs::status("/dev/null")); // direct calls to status demo_status("/dev/sda", fs::status("/dev/sda")); demo_status("sandbox/no", fs::status("/sandbox/no")); // cleanup close(fd); fs::remove_all("sandbox"); } ``` Possible output: ``` "sandbox/file" is a regular file "sandbox/dir" is a directory "sandbox/pipe" is a named IPC pipe "sandbox/sock" is a named IPC socket "sandbox/symlink" is a symlink "/dev/null" is a character device "/dev/sda" is a block device "sandbox/no" does not exist ``` ### See also | | | | --- | --- | | [refresh](refresh "cpp/filesystem/directory entry/refresh") | updates the cached file attributes (public member function) | | [exists](exists "cpp/filesystem/directory entry/exists") | checks whether directory entry refers to existing file system object (public member function) | | [is\_block\_file](is_block_file "cpp/filesystem/directory entry/is block file") | checks whether the directory entry refers to block device (public member function) | | [is\_character\_file](is_character_file "cpp/filesystem/directory entry/is character file") | checks whether the directory entry refers to a character device (public member function) | | [is\_directory](is_directory "cpp/filesystem/directory entry/is directory") | checks whether the directory entry refers to a directory (public member function) | | [is\_fifo](is_fifo "cpp/filesystem/directory entry/is fifo") | checks whether the directory entry refers to a named pipe (public member function) | | [is\_other](is_other "cpp/filesystem/directory entry/is other") | checks whether the directory entry refers to an *other* file (public member function) | | [is\_regular\_file](is_regular_file "cpp/filesystem/directory entry/is regular file") | checks whether the directory entry refers to a regular file (public member function) | | [is\_socket](is_socket "cpp/filesystem/directory entry/is socket") | checks whether the directory entry refers to a named IPC socket (public member function) | | [is\_symlink](is_symlink "cpp/filesystem/directory entry/is symlink") | checks whether the directory entry refers to a symbolic link (public member function) | | [file\_size](file_size "cpp/filesystem/directory entry/file size") | returns the size of the file to which the directory entry refers (public member function) | | [hard\_link\_count](hard_link_count "cpp/filesystem/directory entry/hard link count") | returns the number of hard links referring to the file to which the directory entry refers (public member function) | | [last\_write\_time](last_write_time "cpp/filesystem/directory entry/last write time") | gets or sets the time of the last data modification of the file to which the directory entry refers (public member function) |
programming_docs
cpp operator<<(std::filesystem::directory_entry) operator<<(std::filesystem::directory\_entry) ============================================= | | | | | --- | --- | --- | | ``` template< class CharT, class Traits > friend std::basic_ostream<CharT,Traits>& operator<<( std::basic_ostream<CharT,Traits>& os, const directory_entry& d ); ``` | | (since C++17) | Performs stream output on the directory entry `d`. Equivalent to `return os << d.path();`. This function template is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::filesystem::directory_entry` is an associated class of the arguments. This prevents undesirable conversions in the presence of a `using namespace std::filesystem;` [using-directive](../../language/namespace#Using-directives "cpp/language/namespace"). ### Parameters | | | | | --- | --- | --- | | os | - | stream to perform output on | | d | - | `directory_entry` to be inserted | ### Return value `os`. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { const auto entries = { fs::directory_entry{fs::current_path()}, fs::directory_entry{fs::temp_directory_path()} }; for (const fs::directory_entry& de : entries) { std::cout << de << '\n'; } } ``` Possible output: ``` "/home/猫" "/tmp" ``` ### See also | | | | --- | --- | | [operator<<operator>>](../path/operator_ltltgtgt "cpp/filesystem/path/operator ltltgtgt") | performs stream input and output on a quoted path (function) | cpp std::filesystem::directory_entry::is_socket std::filesystem::directory\_entry::is\_socket ============================================= | | | | | --- | --- | --- | | ``` bool is_socket() const; bool is_socket( std::error_code& ec ) const noexcept; ``` | | (since C++17) | Checks whether the pointed-to object is a named socket. Effectively returns `[std::filesystem::is\_socket](http://en.cppreference.com/w/cpp/filesystem/is_socket)(status())` or `[std::filesystem::is\_socket](http://en.cppreference.com/w/cpp/filesystem/is_socket)(status(ec))`, respectively. ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the referred-to filesystem object is a named socket, `false` otherwise. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <cstdio> #include <cstring> #include <filesystem> #include <fstream> #include <functional> #include <iostream> #include <memory> #include <sys/socket.h> #include <sys/stat.h> #include <sys/un.h> #include <unistd.h> namespace fs = std::filesystem; void print_entry_type(std::filesystem::directory_entry const& entry) { std::cout << entry.path() << ": "; if (!entry.exists()) std::cout << "does not exist "; if (entry.is_block_file()) std::cout << "is a block device "; if (entry.is_character_file()) std::cout << "is a character device "; if (entry.is_directory()) std::cout << "is a directory "; if (entry.is_fifo()) std::cout << "is a named IPC pipe "; if (entry.is_regular_file()) std::cout << "is a regular file "; if (entry.is_socket()) std::cout << "is a named IPC socket "; if (entry.is_symlink()) std::cout << "(a symlink) "; if (entry.is_other()) std::cout << "(an `other` file) "; std::cout <<'\n'; } template <typename Type, typename Fun> class scoped_cleanup { std::unique_ptr<Type, std::function<void(const Type*)>> u; public: scoped_cleanup(Type* ptr, Fun fun) : u{ptr, std::move(fun)} {} }; int main() { // create files of different kinds std::filesystem::current_path(fs::temp_directory_path()); const std::filesystem::path sandbox{"sandbox"}; scoped_cleanup remove_all_at_exit{&sandbox, [](const fs::path* p) { std::cout << "cleanup: remove_all(" << *p << ")\n"; fs::remove_all(*p); } }; std::filesystem::create_directory(sandbox); std::ofstream{sandbox/"file"}; // creates a regular file std::filesystem::create_directory(sandbox/"dir"); mkfifo((sandbox/"pipe").string().data(), 0644); struct sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, (sandbox/"sock").string().data()); int fd {socket(PF_UNIX, SOCK_STREAM, 0)}; scoped_cleanup close_socket_at_exit{&fd, [](const int* f) { std::cout << "cleanup: close socket #" << *f << '\n'; close(*f); } }; bind(fd, reinterpret_cast<sockaddr*>(std::addressof(addr)), sizeof addr); fs::create_symlink("file", sandbox/"symlink"); for (std::filesystem::directory_entry entry: fs::directory_iterator(sandbox)) { print_entry_type(entry); } // direct calls to status: for (const char* str: {"/dev/null", "/dev/cpu", "/usr/include/c++", "/usr/include/asm", "/usr/include/time.h"}) { print_entry_type(fs::directory_entry{str}); } } // cleanup via `scoped_cleanup` objects ``` Possible output: ``` "sandbox/symlink": is a regular file (a symlink) "sandbox/sock": is a named IPC socket (an `other` file) "sandbox/pipe": is a named IPC pipe (an `other` file) "sandbox/dir": is a directory "sandbox/file": is a regular file "/dev/null": is a character device (an `other` file) "/dev/cpu": does not exist "/usr/include/c++": is a directory "/usr/include/asm": is a directory (a symlink) "/usr/include/time.h": is a regular file cleanup: close socket #3 cleanup: remove_all("sandbox") ``` ### See also | | | | --- | --- | | [is\_socket](../is_socket "cpp/filesystem/is socket") (C++17) | checks whether the argument refers to a named IPC socket (function) | cpp std::filesystem::directory_entry::refresh std::filesystem::directory\_entry::refresh ========================================== | | | | | --- | --- | --- | | ``` void refresh(); void refresh( std::error_code& ec ) noexcept; ``` | | (since C++17) | Examines the filesystem object referred to by this directory entry and stores its attributes for retrieval with [`status`](status "cpp/filesystem/directory entry/status"), [`exists`](exists "cpp/filesystem/directory entry/exists"), [`is_regular_file`](is_regular_file "cpp/filesystem/directory entry/is regular file"), and other status accessors. If an error occurs, the value of any cached attributes is unspecified. ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value (none). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes Many low-level OS APIs for directory traversal retrieve file attributes along with the next directory entry. The constructors and the non-const member functions of `[std::filesystem::directory\_iterator](../directory_iterator "cpp/filesystem/directory iterator")` store these attributes, if any, in the pointed-to `[std::filesystem::directory\_entry](../directory_entry "cpp/filesystem/directory entry")` without calling **`directory_entry::refresh`**, which makes it possible to examine the attributes of the directory entries as they are being iterated over, without making additional system calls. ### Example ### See also | | | | --- | --- | | [statussymlink\_status](status "cpp/filesystem/directory entry/status") | status of the file designated by this directory entrysymlink\_status of the file designated by this directory entry (public member function) | | [exists](exists "cpp/filesystem/directory entry/exists") | checks whether directory entry refers to existing file system object (public member function) | | [is\_block\_file](is_block_file "cpp/filesystem/directory entry/is block file") | checks whether the directory entry refers to block device (public member function) | | [is\_character\_file](is_character_file "cpp/filesystem/directory entry/is character file") | checks whether the directory entry refers to a character device (public member function) | | [is\_directory](is_directory "cpp/filesystem/directory entry/is directory") | checks whether the directory entry refers to a directory (public member function) | | [is\_fifo](is_fifo "cpp/filesystem/directory entry/is fifo") | checks whether the directory entry refers to a named pipe (public member function) | | [is\_other](is_other "cpp/filesystem/directory entry/is other") | checks whether the directory entry refers to an *other* file (public member function) | | [is\_regular\_file](is_regular_file "cpp/filesystem/directory entry/is regular file") | checks whether the directory entry refers to a regular file (public member function) | | [is\_socket](is_socket "cpp/filesystem/directory entry/is socket") | checks whether the directory entry refers to a named IPC socket (public member function) | | [is\_symlink](is_symlink "cpp/filesystem/directory entry/is symlink") | checks whether the directory entry refers to a symbolic link (public member function) | | [file\_size](file_size "cpp/filesystem/directory entry/file size") | returns the size of the file to which the directory entry refers (public member function) | | [hard\_link\_count](hard_link_count "cpp/filesystem/directory entry/hard link count") | returns the number of hard links referring to the file to which the directory entry refers (public member function) | | [last\_write\_time](last_write_time "cpp/filesystem/directory entry/last write time") | gets or sets the time of the last data modification of the file to which the directory entry refers (public member function) | cpp std::filesystem::directory_entry::is_regular_file std::filesystem::directory\_entry::is\_regular\_file ==================================================== | | | | | --- | --- | --- | | ``` bool is_regular_file() const; bool is_regular_file( std::error_code& ec ) const noexcept; ``` | | (since C++17) | Checks whether the pointed-to object is a regular file. Effectively returns `[std::filesystem::is\_regular\_file](http://en.cppreference.com/w/cpp/filesystem/is_regular_file)(status())` or `[std::filesystem::is\_regular\_file](http://en.cppreference.com/w/cpp/filesystem/is_regular_file)(status(ec))`, respectively. ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the referred-to filesystem object is a regular file, `false` otherwise. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <filesystem> #include <iostream> #include <string> namespace fs = std::filesystem; int main(int argc, const char* argv[]) { // Print out all regular files in a directory 'dir'. try { const auto dir = argc == 2 ? fs::path{ argv[1] } : fs::current_path(); std::cout << "Current dir: " << dir << '\n' << std::string(40, '-') << '\n'; for (fs::directory_entry const& entry : fs::directory_iterator(dir)) { if (entry.is_regular_file()) { std::cout << entry.path().filename() << '\n'; } } } catch(fs::filesystem_error const& e) { std::cout << e.what() << '\n'; } } ``` Possible output: ``` Current dir: "/tmp/1588616534.9884143" ---------------------------------------- "main.cpp" "a.out" ``` ### See also | | | | --- | --- | | [is\_regular\_file](../is_regular_file "cpp/filesystem/is regular file") (C++17) | checks whether the argument refers to a regular file (function) | cpp std::filesystem::directory_entry::last_write_time std::filesystem::directory\_entry::last\_write\_time ==================================================== | | | | | --- | --- | --- | | ``` std::filesystem::file_time_type last_write_time() const; std::filesystem::file_time_type last_write_time( std::error_code& ec ) const noexcept; ``` | | (since C++17) | If the last modification time is cached in this [`directory_entry`](directory_entry "cpp/filesystem/directory entry/directory entry"), returns the cached value. Otherwise, returns `[std::filesystem::last\_write\_time](http://en.cppreference.com/w/cpp/filesystem/last_write_time)(path())` or `[std::filesystem::last\_write\_time](http://en.cppreference.com/w/cpp/filesystem/last_write_time)(path(), ec)`, respectively. ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value The last modification time for the referred-to filesystem object. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <filesystem> #include <iostream> #include <string> #include <chrono> #include <ctime> std::string to_string(std::filesystem::file_time_type const& ftime) { std::time_t cftime = std::chrono::system_clock::to_time_t( std::chrono::file_clock::to_sys(ftime)); std::string str = std::asctime(std::localtime(&cftime)); str.pop_back(); // rm the trailing '\n' put by `asctime` return str; } int main() { auto dir = std::filesystem::current_path(); using Entry = std::filesystem::directory_entry; for (Entry const& entry : std::filesystem::directory_iterator(dir)) { std::cout << to_string(entry.last_write_time()) << " : " << entry.path().filename() << '\n'; } } ``` Possible output: ``` Sat Aug 21 07:39:13 2021 : "main.cpp" Sat Aug 21 07:39:16 2021 : "a.out" ``` ### See also | | | | --- | --- | | [last\_write\_time](../last_write_time "cpp/filesystem/last write time") (C++17) | gets or sets the time of the last data modification (function) | cpp std::filesystem::directory_entry::assign std::filesystem::directory\_entry::assign ========================================= | | | | | --- | --- | --- | | ``` void assign( const std::filesystem::path& p ); void assign( const std::filesystem::path& p, std::error_code& ec ); ``` | | (since C++17) | Assigns new content to the directory entry object. Sets the path to `p` and calls [`refresh`](refresh "cpp/filesystem/directory entry/refresh") to update the cached attributes. If an error occurs, the values of the cached attributes are unspecified. This function does not commit any changes to the filesystem. ### Parameters | | | | | --- | --- | --- | | p | - | path to the filesystem object to which the directory entry will refer | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value (none). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <filesystem> #include <fstream> #include <iostream> void print_entry_info(const std::filesystem::directory_entry& entry) { std::cout << "the entry " << entry; if (not entry.exists()) { std::cout << " does not exists on the file system\n"; return; } std::cout << " is "; if (entry.is_directory()) std::cout << "a directory\n"; if (entry.is_regular_file()) std::cout << "a regular file\n"; /*...*/ } int main() { std::filesystem::current_path(std::filesystem::temp_directory_path()); std::filesystem::directory_entry entry{std::filesystem::current_path()}; print_entry_info(entry); std::filesystem::path name{"cppreference.html"}; std::ofstream{name} << "C++"; std::cout << "entry.assign();\n"; entry.assign(entry/name); print_entry_info(entry); std::cout << "remove(entry);\n"; std::filesystem::remove(entry); print_entry_info(entry); // the entry still contains old "state" std::cout << "entry.assign();\n"; entry.assign(entry); // or just call entry.refresh() print_entry_info(entry); } ``` Possible output: ``` the entry "/tmp" is a directory entry.assign(); the entry "/tmp/cppreference.html" is a regular file remove(entry); the entry "/tmp/cppreference.html" is a regular file entry.assign(); the entry "/tmp/cppreference.html" does not exists on the file system ``` ### See also | | | | --- | --- | | [operator=](operator= "cpp/filesystem/directory entry/operator=") | assigns contents (public member function) | cpp std::filesystem::directory_entry::is_block_file std::filesystem::directory\_entry::is\_block\_file ================================================== | | | | | --- | --- | --- | | ``` bool is_block_file() const; bool is_block_file( std::error_code& ec ) const noexcept; ``` | | (since C++17) | Checks whether the pointed-to object is a block device. Effectively returns `[std::filesystem::is\_block\_file](http://en.cppreference.com/w/cpp/filesystem/is_block_file)(status())` or `[std::filesystem::is\_block\_file](http://en.cppreference.com/w/cpp/filesystem/is_block_file)(status(ec))`, respectively. ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the referred-to filesystem object is a block device, false otherwise. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <cstdio> #include <cstring> #include <filesystem> #include <fstream> #include <functional> #include <iostream> #include <memory> #include <sys/socket.h> #include <sys/stat.h> #include <sys/un.h> #include <unistd.h> namespace fs = std::filesystem; void print_entry_type(std::filesystem::directory_entry const& entry) { std::cout << entry.path() << ": "; if (!entry.exists()) std::cout << "does not exist "; if (entry.is_block_file()) std::cout << "is a block device "; if (entry.is_character_file()) std::cout << "is a character device "; if (entry.is_directory()) std::cout << "is a directory "; if (entry.is_fifo()) std::cout << "is a named IPC pipe "; if (entry.is_regular_file()) std::cout << "is a regular file "; if (entry.is_socket()) std::cout << "is a named IPC socket "; if (entry.is_symlink()) std::cout << "(a symlink) "; if (entry.is_other()) std::cout << "(an `other` file) "; std::cout <<'\n'; } template <typename Type, typename Fun> class scoped_cleanup { std::unique_ptr<Type, std::function<void(const Type*)>> u; public: scoped_cleanup(Type* ptr, Fun fun) : u{ptr, std::move(fun)} {} }; int main() { // create files of different kinds std::filesystem::current_path(fs::temp_directory_path()); const std::filesystem::path sandbox{"sandbox"}; scoped_cleanup remove_all_at_exit{&sandbox, [](const fs::path* p) { std::cout << "cleanup: remove_all(" << *p << ")\n"; fs::remove_all(*p); } }; std::filesystem::create_directory(sandbox); std::ofstream{sandbox/"file"}; // creates a regular file std::filesystem::create_directory(sandbox/"dir"); mkfifo((sandbox/"pipe").string().data(), 0644); struct sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, (sandbox/"sock").string().data()); int fd {socket(PF_UNIX, SOCK_STREAM, 0)}; scoped_cleanup close_socket_at_exit{&fd, [](const int* f) { std::cout << "cleanup: close socket #" << *f << '\n'; close(*f); } }; bind(fd, reinterpret_cast<sockaddr*>(std::addressof(addr)), sizeof addr); fs::create_symlink("file", sandbox/"symlink"); for (std::filesystem::directory_entry entry: fs::directory_iterator(sandbox)) { print_entry_type(entry); } // direct calls to status: for (const char* str: {"/dev/null", "/dev/cpu", "/usr/include/c++", "/usr/include/asm", "/usr/include/time.h"}) { print_entry_type(fs::directory_entry{str}); } } // cleanup via `scoped_cleanup` objects ``` Possible output: ``` "sandbox/symlink": is a regular file (a symlink) "sandbox/sock": is a named IPC socket (an `other` file) "sandbox/pipe": is a named IPC pipe (an `other` file) "sandbox/dir": is a directory "sandbox/file": is a regular file "/dev/null": is a character device (an `other` file) "/dev/cpu": does not exist "/usr/include/c++": is a directory "/usr/include/asm": is a directory (a symlink) "/usr/include/time.h": is a regular file cleanup: close socket #3 cleanup: remove_all("sandbox") ``` ### See also | | | | --- | --- | | [is\_block\_file](../is_block_file "cpp/filesystem/is block file") (C++17) | checks whether the given path refers to block device (function) |
programming_docs
cpp std::filesystem::directory_entry::is_other std::filesystem::directory\_entry::is\_other ============================================ | | | | | --- | --- | --- | | ``` bool is_other() const; bool is_other( std::error_code& ec ) const noexcept; ``` | | (since C++17) | Checks whether the pointed-to object is an *other* file (not a regular file, directory or symlink). Effectively returns `[std::filesystem::is\_other](http://en.cppreference.com/w/cpp/filesystem/is_other)(status())` or `[std::filesystem::is\_other](http://en.cppreference.com/w/cpp/filesystem/is_other)(status(ec))`, respectively. ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the referred-to filesystem object is an *other* file, `false` otherwise. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <cstdio> #include <cstring> #include <filesystem> #include <fstream> #include <functional> #include <iostream> #include <memory> #include <sys/socket.h> #include <sys/stat.h> #include <sys/un.h> #include <unistd.h> namespace fs = std::filesystem; void print_entry_type(std::filesystem::directory_entry const& entry) { std::cout << entry.path() << ": "; if (!entry.exists()) std::cout << "does not exist "; if (entry.is_block_file()) std::cout << "is a block device "; if (entry.is_character_file()) std::cout << "is a character device "; if (entry.is_directory()) std::cout << "is a directory "; if (entry.is_fifo()) std::cout << "is a named IPC pipe "; if (entry.is_regular_file()) std::cout << "is a regular file "; if (entry.is_socket()) std::cout << "is a named IPC socket "; if (entry.is_symlink()) std::cout << "(a symlink) "; if (entry.is_other()) std::cout << "(an `other` file) "; std::cout <<'\n'; } template <typename Type, typename Fun> class scoped_cleanup { std::unique_ptr<Type, std::function<void(const Type*)>> u; public: scoped_cleanup(Type* ptr, Fun fun) : u{ptr, std::move(fun)} {} }; int main() { // create files of different kinds std::filesystem::current_path(fs::temp_directory_path()); const std::filesystem::path sandbox{"sandbox"}; scoped_cleanup remove_all_at_exit{&sandbox, [](const fs::path* p) { std::cout << "cleanup: remove_all(" << *p << ")\n"; fs::remove_all(*p); } }; std::filesystem::create_directory(sandbox); std::ofstream{sandbox/"file"}; // creates a regular file std::filesystem::create_directory(sandbox/"dir"); mkfifo((sandbox/"pipe").string().data(), 0644); struct sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, (sandbox/"sock").string().data()); int fd {socket(PF_UNIX, SOCK_STREAM, 0)}; scoped_cleanup close_socket_at_exit{&fd, [](const int* f) { std::cout << "cleanup: close socket #" << *f << '\n'; close(*f); } }; bind(fd, reinterpret_cast<sockaddr*>(std::addressof(addr)), sizeof addr); fs::create_symlink("file", sandbox/"symlink"); for (std::filesystem::directory_entry entry: fs::directory_iterator(sandbox)) { print_entry_type(entry); } // direct calls to status: for (const char* str: {"/dev/null", "/dev/cpu", "/usr/include/c++", "/usr/include/asm", "/usr/include/time.h"}) { print_entry_type(fs::directory_entry{str}); } } // cleanup via `scoped_cleanup` objects ``` Possible output: ``` "sandbox/symlink": is a regular file (a symlink) "sandbox/sock": is a named IPC socket (an `other` file) "sandbox/pipe": is a named IPC pipe (an `other` file) "sandbox/dir": is a directory "sandbox/file": is a regular file "/dev/null": is a character device (an `other` file) "/dev/cpu": does not exist "/usr/include/c++": is a directory "/usr/include/asm": is a directory (a symlink) "/usr/include/time.h": is a regular file cleanup: close socket #3 cleanup: remove_all("sandbox") ``` ### See also | | | | --- | --- | | [is\_other](../is_other "cpp/filesystem/is other") (C++17) | checks whether the argument refers to an *other* file (function) | cpp std::filesystem::directory_entry::operator= std::filesystem::directory\_entry::operator= ============================================ | | | | | --- | --- | --- | | ``` directory_entry& operator=( const directory_entry& other ) = default; ``` | (1) | (since C++17) | | ``` directory_entry& operator=( directory_entry&& other ) noexcept = default; ``` | (2) | (since C++17) | Replaces the contents of the directory entry (path and cached attributes, if any) with the contents of `other`. Both copy- and move-assignment operators for `directory_entry` are defaulted. ### Parameters | | | | | --- | --- | --- | | other | - | other `directory_entry` | ### Return value `*this`. ### Example ### See also | | | | --- | --- | | [assign](assign "cpp/filesystem/directory entry/assign") | assigns contents (public member function) | cpp std::filesystem::directory_entry::replace_filename std::filesystem::directory\_entry::replace\_filename ==================================================== | | | | | --- | --- | --- | | ``` void replace_filename( const std::filesystem::path& p ); void replace_filename( const std::filesystem::path& p, std::error_code& ec ); ``` | | (since C++17) | Changes the filename of the directory entry. Effectively modifies the path member by `path.replace_filename(p)` and calls [`refresh`](refresh "cpp/filesystem/directory entry/refresh") to update the cached attributes. If an error occurs, the values of the cached attributes are unspecified. This function does not commit any changes to the filesystem. ### Parameters | | | | | --- | --- | --- | | p | - | the path to append to the parent path of the currently stored path | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value (none). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <iostream> #include <filesystem> int main() { namespace fs = std::filesystem; { fs::directory_entry entry{ "omega" }; std::cout << entry << '\n'; entry.replace_filename("alpha"); std::cout << entry << '\n'; }{ fs::directory_entry entry{ "/omega/" }; std::cout << entry << '\n'; entry.replace_filename("alpha"); std::cout << entry << '\n'; } } ``` Output: ``` "omega" "alpha" "/omega/" "/omega/alpha" ``` ### See also | | | | --- | --- | | [assign](assign "cpp/filesystem/directory entry/assign") | assigns contents (public member function) | | [replace\_filename](../path/replace_filename "cpp/filesystem/path/replace filename") | replaces the last path component with another path (public member function of `std::filesystem::path`) | cpp std::filesystem::directory_entry::file_size std::filesystem::directory\_entry::file\_size ============================================= | | | | | --- | --- | --- | | ``` std::uintmax_t file_size() const; std::uintmax_t file_size( std::error_code& ec ) const noexcept; ``` | | (since C++17) | If the file size is cached in this [`directory_entry`](directory_entry "cpp/filesystem/directory entry/directory entry"), returns the cached value. Otherwise, returns `[std::filesystem::file\_size](http://en.cppreference.com/w/cpp/filesystem/file_size)(path())` or `[std::filesystem::file\_size](http://en.cppreference.com/w/cpp/filesystem/file_size)(path(), ec)`, respectively. ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value The size of the referred-to filesystem object. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example Prints the list of files in a given directory alongside with their sizes in human readable form. ``` #include <filesystem> #include <iostream> #include <cstdint> #include <cmath> struct HumanReadable { std::uintmax_t size {}; template <typename Os> friend Os& operator<< (Os& os, HumanReadable hr) { int i{}; double mantissa = hr.size; for (; mantissa >= 1024.; ++i) { mantissa /= 1024.; } mantissa = std::ceil(mantissa * 10.) / 10.; os << mantissa << "BKMGTPE"[i]; return i == 0 ? os : os << "B (" << hr.size << ')'; } }; int main(int argc, const char* argv[]) { const auto dir = argc == 2 ? std::filesystem::path{ argv[1] } : std::filesystem::current_path(); for (std::filesystem::directory_entry const& entry : std::filesystem::directory_iterator(dir)) { if (entry.is_regular_file()) { std::cout << entry.path().filename() << " size: " << HumanReadable{entry.file_size()} << '\n'; } } } ``` Possible output: ``` "boost_1_73_0.tar.bz2" size: 104.2MB (109247910) "CppCon 2018 - Jon Kalb “Copy Elision”.mp4" size: 15.7MB (16411990) "cppreference-doc-20190607.tar.xz" size: 6.3MB (6531336) "hana.hpp" size: 6.7KB (6807) ``` ### See also | | | | --- | --- | | [file\_size](../file_size "cpp/filesystem/file size") (C++17) | returns the size of a file (function) | cpp std::filesystem::directory_entry::directory_entry std::filesystem::directory\_entry::directory\_entry =================================================== | | | | | --- | --- | --- | | ``` directory_entry() noexcept = default; ``` | (1) | (since C++17) | | ``` directory_entry( const directory_entry& ) = default; ``` | (2) | (since C++17) | | ``` directory_entry( directory_entry&& ) noexcept = default; ``` | (3) | (since C++17) | | ``` explicit directory_entry( const std::filesystem::path& p ); directory_entry( const std::filesystem::path& p, std::error_code& ec ); ``` | (4) | (since C++17) | Constructs a new `directory_entry` object. 1) Default constructor. 2) Defaulted copy constructor. 3) Defaulted move constructor. 4) Initializes the directory entry with path `p` and calls [`refresh`](refresh "cpp/filesystem/directory entry/refresh") to update the cached attributes. If an error occurs, the non-throwing overload leaves the `directory_entry` holding a default-constructed path. ### Parameters | | | | | --- | --- | --- | | p | - | path to the filesystem object to which the directory entry will refer | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example cpp std::filesystem::directory_entry::is_directory std::filesystem::directory\_entry::is\_directory ================================================ | | | | | --- | --- | --- | | ``` bool is_directory() const; bool is_directory( std::error_code& ec ) const noexcept; ``` | | (since C++17) | Checks whether the pointed-to object is a directory. Effectively returns `[std::filesystem::is\_directory](http://en.cppreference.com/w/cpp/filesystem/is_directory)(status())` or `[std::filesystem::is\_directory](http://en.cppreference.com/w/cpp/filesystem/is_directory)(status(ec))`, respectively. ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the referred-to filesystem object is a directory, `false` otherwise. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::directory_entry d1("."); fs::directory_entry d2("file.txt"); fs::directory_entry d3("new_dir"); std::cout << std::boolalpha << ". d1 " << d1.is_directory() << '\n' << "file.txt d2 " << d2.is_directory() << '\n' // false because it has not been created << "new_dir d3 " << d3.is_directory() << '\n'; fs::create_directory("new_dir"); std::cout << "new_dir d3 before refresh " << d3.is_directory() << '\n'; d3.refresh(); std::cout << "new_dir d3 after refresh " << d3.is_directory() << '\n'; } ``` Possible output: ``` . d1 true file.txt d2 false new_dir d3 false new_dir d3 before refresh false new_dir d3 after refresh true ``` ### See also | | | | --- | --- | | [is\_directory](../is_directory "cpp/filesystem/is directory") (C++17) | checks whether the given path refers to a directory (function) | cpp std::filesystem::directory_entry::operator==,!=,<,<=,>,>=,<=> std::filesystem::directory\_entry::operator==,!=,<,<=,>,>=,<=> ============================================================== | | | | | --- | --- | --- | | ``` bool operator==( const directory_entry& rhs ) const noexcept; ``` | (1) | (since C++17) | | ``` bool operator!=( const directory_entry& rhs ) const noexcept; ``` | (2) | (since C++17) (until C++20) | | ``` bool operator<( const directory_entry& rhs ) const noexcept; ``` | (3) | (since C++17) (until C++20) | | ``` bool operator<=( const directory_entry& rhs ) const noexcept; ``` | (4) | (since C++17) (until C++20) | | ``` bool operator>( const directory_entry& rhs ) const noexcept; ``` | (5) | (since C++17) (until C++20) | | ``` bool operator>=( const directory_entry& rhs ) const noexcept; ``` | (6) | (since C++17) (until C++20) | | ``` std::strong_ordering operator<=>( const directory_entry& rhs ) const noexcept; ``` | (7) | (since C++20) | Compares the path with the directory entry `rhs`. | | | | --- | --- | | The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | rhs | - | directory\_entry to compare | ### Return value 1) `true` if `path() == rhs.path()`, `false` otherwise. 2) `true` if `path() != rhs.path()`, `false` otherwise. 3) `true` if `path() < rhs.path()`, `false` otherwise. 4) `true` if `path() <= rhs.path()`, `false` otherwise. 5) `true` if `path() > rhs.path()`, `false` otherwise. 6) `true` if `path() >= rhs.path()`, `false` otherwise. 7) The result of `path() <=> rhs.path()`. ### See also | | | | --- | --- | | [pathoperator const path&](path "cpp/filesystem/directory entry/path") | returns the path the entry refers to (public member function) | cpp std::filesystem::directory_entry::is_symlink std::filesystem::directory\_entry::is\_symlink ============================================== | | | | | --- | --- | --- | | ``` bool is_symlink() const; bool is_symlink( std::error_code& ec ) const noexcept; ``` | | (since C++17) | Checks whether the pointed-to object is a symlink. Effectively returns `[std::filesystem::is\_symlink](http://en.cppreference.com/w/cpp/filesystem/is_symlink)(symlink_status())` or `[std::filesystem::is\_symlink](http://en.cppreference.com/w/cpp/filesystem/is_symlink)(symlink_status(ec))`, respectively. ### Parameters | | | | | --- | --- | --- | | ec | - | out-parameter for error reporting in the non-throwing overload | ### Return value `true` if the referred-to filesystem object is a symlink, `false` otherwise. ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Example ``` #include <cstdio> #include <cstring> #include <filesystem> #include <fstream> #include <functional> #include <iostream> #include <memory> #include <sys/socket.h> #include <sys/stat.h> #include <sys/un.h> #include <unistd.h> namespace fs = std::filesystem; void print_entry_type(std::filesystem::directory_entry const& entry) { std::cout << entry.path() << ": "; if (!entry.exists()) std::cout << "does not exist "; if (entry.is_block_file()) std::cout << "is a block device "; if (entry.is_character_file()) std::cout << "is a character device "; if (entry.is_directory()) std::cout << "is a directory "; if (entry.is_fifo()) std::cout << "is a named IPC pipe "; if (entry.is_regular_file()) std::cout << "is a regular file "; if (entry.is_socket()) std::cout << "is a named IPC socket "; if (entry.is_symlink()) std::cout << "(a symlink) "; if (entry.is_other()) std::cout << "(an `other` file) "; std::cout <<'\n'; } template <typename Type, typename Fun> class scoped_cleanup { std::unique_ptr<Type, std::function<void(const Type*)>> u; public: scoped_cleanup(Type* ptr, Fun fun) : u{ptr, std::move(fun)} {} }; int main() { // create files of different kinds std::filesystem::current_path(fs::temp_directory_path()); const std::filesystem::path sandbox{"sandbox"}; scoped_cleanup remove_all_at_exit{&sandbox, [](const fs::path* p) { std::cout << "cleanup: remove_all(" << *p << ")\n"; fs::remove_all(*p); } }; std::filesystem::create_directory(sandbox); std::ofstream{sandbox/"file"}; // creates a regular file std::filesystem::create_directory(sandbox/"dir"); mkfifo((sandbox/"pipe").string().data(), 0644); struct sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, (sandbox/"sock").string().data()); int fd {socket(PF_UNIX, SOCK_STREAM, 0)}; scoped_cleanup close_socket_at_exit{&fd, [](const int* f) { std::cout << "cleanup: close socket #" << *f << '\n'; close(*f); } }; bind(fd, reinterpret_cast<sockaddr*>(std::addressof(addr)), sizeof addr); fs::create_symlink("file", sandbox/"symlink"); for (std::filesystem::directory_entry entry: fs::directory_iterator(sandbox)) { print_entry_type(entry); } // direct calls to status: for (const char* str: {"/dev/null", "/dev/cpu", "/usr/include/c++", "/usr/include/asm", "/usr/include/time.h"}) { print_entry_type(fs::directory_entry{str}); } } // cleanup via `scoped_cleanup` objects ``` Possible output: ``` "sandbox/symlink": is a regular file (a symlink) "sandbox/sock": is a named IPC socket (an `other` file) "sandbox/pipe": is a named IPC pipe (an `other` file) "sandbox/dir": is a directory "sandbox/file": is a regular file "/dev/null": is a character device (an `other` file) "/dev/cpu": does not exist "/usr/include/c++": is a directory "/usr/include/asm": is a directory (a symlink) "/usr/include/time.h": is a regular file cleanup: close socket #3 cleanup: remove_all("sandbox") ``` ### See also | | | | --- | --- | | [is\_symlink](../is_symlink "cpp/filesystem/is symlink") (C++17) | checks whether the argument refers to a symbolic link (function) |
programming_docs
cpp std::filesystem::directory_entry::path std::filesystem::directory\_entry::path ======================================= | | | | | --- | --- | --- | | ``` const std::filesystem::path& path() const noexcept; ``` | | (since C++17) | | ``` operator const std::filesystem::path& () const noexcept; ``` | | (since C++17) | Returns the full path the directory entry refers to. ### Parameters (none). ### Return value The full path the directory entry refers to. ### Example ``` #include <filesystem> #include <fstream> #include <iostream> namespace fs = std::filesystem; std::string get_stem(const fs::path &p) { return (p.stem().string()); } void create_file(const fs::path &p) { std::ofstream o{p}; } int main() { const fs::path dir{"tmp_dir"}; fs::create_directory(dir); create_file(dir / "one"); create_file(dir / "two"); create_file(dir / "three"); for (const auto &file : fs::directory_iterator(dir)) { // Explicit conversion std::cout << get_stem(file.path()) << '\n'; // Implicit conversion std::cout << get_stem(file) << '\n'; } fs::remove_all(dir); } ``` Possible output: ``` two two one one three three ``` ### See also | | | | --- | --- | | [path](../path "cpp/filesystem/path") (C++17) | represents a path (class) | cpp std::filesystem::directory_iterator::operator*, std::filesystem::directory_iterator::operator-> std::filesystem::directory\_iterator::operator\*, std::filesystem::directory\_iterator::operator-> ================================================================================================== | | | | | --- | --- | --- | | ``` const std::filesystem::directory_entry& operator*() const; ``` | (1) | (since C++17) | | ``` const std::filesystem::directory_entry* operator->() const; ``` | (2) | (since C++17) | Accesses the pointed-to [`directory_entry`](../directory_entry "cpp/filesystem/directory entry"). The result of `operator*` or `operator->` on the end iterator is undefined behavior. ### Parameters (none). ### Return value 1) Value of the [`directory_entry`](../directory_entry "cpp/filesystem/directory entry") referred to by this iterator. 2) Pointer to the [`directory_entry`](../directory_entry "cpp/filesystem/directory entry") referred to by this iterator. ### Exceptions May throw implementation-defined exceptions. ### See also | | | | --- | --- | | [operator\*operator->](../recursive_directory_iterator/operator* "cpp/filesystem/recursive directory iterator/operator*") | accesses the pointed-to entry (public member function of `std::filesystem::recursive_directory_iterator`) | cpp std::filesystem::directory_iterator::operator= std::filesystem::directory\_iterator::operator= =============================================== | | | | | --- | --- | --- | | ``` directory_iterator& operator=(const directory_iterator&) = default; directory_iterator& operator=(directory_iterator&&) = default; ``` | | (since C++17) | ### Parameters ### Return value `*this`. ### Exceptions cpp std::filesystem::directory_iterator::directory_iterator std::filesystem::directory\_iterator::directory\_iterator ========================================================= | | | | | --- | --- | --- | | ``` directory_iterator() noexcept; ``` | (1) | (since C++17) | | ``` explicit directory_iterator( const std::filesystem::path& p ); ``` | (2) | (since C++17) | | ``` directory_iterator( const std::filesystem::path& p, std::filesystem::directory_options options); ``` | (3) | (since C++17) | | ``` directory_iterator( const std::filesystem::path& p, std::error_code& ec ); ``` | (4) | (since C++17) | | ``` directory_iterator( const std::filesystem::path& p, std::filesystem::directory_options options, std::error_code& ec ); ``` | (5) | (since C++17) | | ``` directory_iterator( const directory_iterator& ) = default; ``` | (6) | (since C++17) | | ``` directory_iterator( directory_iterator&& ) = default; ``` | (7) | (since C++17) | Constructs a new directory iterator. 1) Constructs the end iterator. 2) Constructs a directory iterator that refers to the first directory entry of a directory identified by `p`. If `p` refers to an non-existing file or not a directory, throws `[std::filesystem::filesystem\_error](../filesystem_error "cpp/filesystem/filesystem error")`. 3) Same as (2), but if `[std::filesystem::directory\_options::skip\_permission\_denied](../directory_options "cpp/filesystem/directory options")` is set in `options` and construction encounters a permissions denied error, constructs the end iterator and does not report an error. 4) Constructs a directory iterator that refers to the first directory entry of a directory identified by `p`. If `p` refers to an non-existing file or not a directory, returns the end iterator and sets `ec`. 5) Same as (4), but if `[std::filesystem::directory\_options::skip\_permission\_denied](../directory_options "cpp/filesystem/directory options")` is set in `options` and construction encounters a permissions denied error, constructs the end iterator and does not report an error. ### Parameters ### Exceptions 2-5) The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes To iterate over the current directory, construct the iterator as `directory_iterator(".")` instead of `directory_iterator("")`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3013](https://cplusplus.github.io/LWG/issue3013) | C++17 | `error_code` overload marked noexcept but can allocate memory | noexcept removed | cpp std::filesystem::begin(directory_iterator), std::filesystem::end(directory_iterator) std::filesystem::begin(directory\_iterator), std::filesystem::end(directory\_iterator) ====================================================================================== | Defined in header `[<filesystem>](../../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` directory_iterator begin( directory_iterator iter ) noexcept; ``` | (1) | (since C++17) | | ``` directory_iterator end( directory_iterator ) noexcept; ``` | (2) | (since C++17) | 1) Returns `iter` unchanged. 2) Returns a default-constructed [`directory_iterator`](../directory_iterator "cpp/filesystem/directory iterator"), which serves as the end iterator. The argument is ignored. These non-member functions enable the use of `directory_iterator`s with range-based for loops and make `directory_iterator` a [`range`](../../ranges/range "cpp/ranges/range") type (since C++20). ### Parameters | | | | | --- | --- | --- | | iter | - | a `directory_iterator` | ### Return value 1) `iter` unchanged. 2) End iterator (default-constructed `directory_iterator`). ### Example ``` #include <fstream> #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::create_directories("sandbox/a/b"); std::ofstream("sandbox/file1.txt"); std::ofstream("sandbox/file2.txt"); for(auto& p: fs::directory_iterator("sandbox")) std::cout << p << '\n'; fs::remove_all("sandbox"); } ``` Possible output: ``` "sandbox/a" "sandbox/file1.txt" "sandbox/file2.txt" ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3480](https://cplusplus.github.io/LWG/issue3480) | C++17 | `end` took the argument by reference | takes the argument by value | ### See also | | | | --- | --- | | [begin(std::filesystem::recursive\_directory\_iterator)end(std::filesystem::recursive\_directory\_iterator)](../recursive_directory_iterator/begin "cpp/filesystem/recursive directory iterator/begin") | range-based for loop support (function) | cpp operator<<,>>(std::filesystem::path) operator<<,>>(std::filesystem::path) ==================================== | | | | | --- | --- | --- | | ``` template< class CharT, class Traits > friend std::basic_ostream<CharT,Traits>& operator<<( std::basic_ostream<CharT,Traits>& os, const path& p ); ``` | (1) | (since C++17) | | ``` template< class CharT, class Traits > friend std::basic_istream<CharT,Traits>& operator>>( std::basic_istream<CharT,Traits>& is, path& p ); ``` | (2) | (since C++17) | Performs stream input or output on the path `p`. `[std::quoted](http://en.cppreference.com/w/cpp/io/manip/quoted)` is used so that spaces do not cause truncation when later read by stream input operator. These function templates are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::filesystem::path` is an associated class of the arguments. This prevents undesirable conversions in the presence of a `using namespace std::filesystem;` *using-directive*. ### Parameters | | | | | --- | --- | --- | | os | - | stream to perform output on | | is | - | stream to perform input on | | p | - | path to insert or extract | ### Return value 1) `os` 2) `is` ### Exceptions May throw implementation-defined exceptions. ### Possible implementation | First version | | --- | | ``` template< class CharT, class Traits > friend std::basic_ostream<CharT,Traits>& operator<<( std::basic_ostream<CharT,Traits>& os, const path& p ) { os << std::quoted(p.string<CharT,Traits>()); return os; } ``` | | Second version | | ``` template< class CharT, class Traits > friend std::basic_istream<CharT,Traits>& operator>>( std::basic_istream<CharT,Traits>& is, path& p ) { std::basic_string<CharT, Traits> t; is >> std::quoted(t); p = t; return is; } ``` | ### Example ``` #include <iostream> #include <filesystem> int main() { std::cout << std::filesystem::current_path() << '\n'; std::cout << std::filesystem::temp_directory_path() << '\n'; } ``` Possible output: ``` "/home/user" "/tmp" ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2989](https://cplusplus.github.io/LWG/issue2989) | C++17 | allowed insertion of everything convertible to `path` in the presence of a *using-directive* | made hidden friend | cpp std::filesystem::path::replace_extension std::filesystem::path::replace\_extension ========================================= | | | | | --- | --- | --- | | ``` path& replace_extension( const path& replacement = path() ); ``` | | (since C++17) | Replaces the extension with `replacement` or removes it when the default value of `replacement` is used. Firstly, if this path has an [`extension()`](extension "cpp/filesystem/path/extension"), it is removed from the generic-format view of the pathname. Then, a dot character is appended to the generic-format view of the pathname, if `replacement` is not empty and does not begin with a dot character. Then `replacement` is appended as if by `operator+=(replacement)`. ### Parameters | | | | | --- | --- | --- | | replacement | - | the extension to replace with | ### Return value `*this`. ### Exceptions May throw implementation-defined exceptions. ### Notes The type of `replacement` is `[std::filesystem::path](../path "cpp/filesystem/path")` even though it is not intended to represent an object on the file system in order to correctly account for the filesystem character encoding. ### Example ``` #include <filesystem> #include <iomanip> #include <iostream> #include <utility> namespace fs = std::filesystem; int main() { std::cout << "Path: Ext: Result:\n" << std::left; for (const auto& [path, extension] : { std::make_pair( "/foo/bar.jpg", ".png" ), std::make_pair( "/foo/bar.jpg", "png" ), std::make_pair( "/foo/bar.jpg", "." ), std::make_pair( "/foo/bar.jpg", "" ), std::make_pair( "/foo/bar." , "png" ), std::make_pair( "/foo/bar" , ".png" ), std::make_pair( "/foo/bar" , "png" ), std::make_pair( "/foo/bar" , "." ), std::make_pair( "/foo/bar" , "" ), std::make_pair( "/foo/." , ".png" ), std::make_pair( "/foo/." , "png" ), std::make_pair( "/foo/." , "." ), std::make_pair( "/foo/." , "" ), std::make_pair( "/foo/" , ".png" ), std::make_pair( "/foo/" , "png" ), }) { fs::path p = path, e = extension; std::cout << std::setw(18) << p << std::setw(11) << e; p.replace_extension(e); std::cout << p << '\n'; } } ``` Output: ``` Path: Ext: Result: "/foo/bar.jpg" ".png" "/foo/bar.png" "/foo/bar.jpg" "png" "/foo/bar.png" "/foo/bar.jpg" "." "/foo/bar." "/foo/bar.jpg" "" "/foo/bar" "/foo/bar." "png" "/foo/bar.png" "/foo/bar" ".png" "/foo/bar.png" "/foo/bar" "png" "/foo/bar.png" "/foo/bar" "." "/foo/bar." "/foo/bar" "" "/foo/bar" "/foo/." ".png" "/foo/..png" "/foo/." "png" "/foo/..png" "/foo/." "." "/foo/.." "/foo/." "" "/foo/." "/foo/" ".png" "/foo/.png" "/foo/" "png" "/foo/.png" ``` ### See also | | | | --- | --- | | [extension](extension "cpp/filesystem/path/extension") | returns the file extension path component (public member function) | | [filename](filename "cpp/filesystem/path/filename") | returns the filename path component (public member function) | | [stem](stem "cpp/filesystem/path/stem") | returns the stem path component (filename without the final extension) (public member function) | | [has\_extension](has_path "cpp/filesystem/path/has path") | checks if the corresponding path element is not empty (public member function) | cpp std::filesystem::path::compare std::filesystem::path::compare ============================== | | | | | --- | --- | --- | | ``` int compare( const path& p ) const noexcept; ``` | (1) | (since C++17) | | ``` int compare( const string_type& str ) const; int compare( std::basic_string_view<value_type> str ) const; ``` | (2) | (since C++17) | | ``` int compare( const value_type* s ) const; ``` | (3) | (since C++17) | Compares the lexical representations of the path and another path. 1) If `root_name().native().compare(p.root_name().native())` is nonzero, returns that value. Otherwise, if `has_root_directory() != p.has_root_directory()`, returns a value less than zero if [`has_root_directory()`](has_path "cpp/filesystem/path/has path") is `false` and a value greater than zero otherwise. Otherwise returns a value less than, equal to or greater than `​0​` if the relative portion of the path ([`relative_path()`](relative_path "cpp/filesystem/path/relative path")) is respectively lexicographically less than, equal to or greater than the relative portion of `p` (`p.relative_path()`). Comparison is performed element-wise, as if by iterating both paths from [`begin()`](begin "cpp/filesystem/path/begin") to [`end()`](begin "cpp/filesystem/path/begin") and comparing the result of [`native()`](native "cpp/filesystem/path/native") for each element. 2) Equivalent to `compare(path(str))`. 3) Equivalent to `compare(path(s))`. ### Parameters | | | | | --- | --- | --- | | p | - | a path to compare to | | str | - | a string or string view representing path to compare to | | s | - | a null-terminated string representing path to compare to | ### Return value A value less than `​0​` if the path is lexicographically less than the given path. A value equal to `​0​` if the path is lexicographically equal to the given path. A value greater than `​0​` if the path is lexicographically greater than the given path. ### Exceptions 2-3) May throw implementation-defined exceptions. ### Notes For two-way comparisons, [binary operators](operator_cmp "cpp/filesystem/path/operator cmp") may be more suitable. ### Example ``` #include <iostream> #include <filesystem> #include <string_view> namespace fs = std::filesystem; void demo(fs::path p1, fs::path p2, std::string_view msg) { using std::cout; cout << p1; const int rc = p1.compare(p2); if(rc < 0) cout << " < "; else if(rc > 0) cout << " > "; else cout << " == "; cout << p2 << " \t: " << msg << '\n'; } int main() { demo("/a/b/", "/a/b/", "simple"); demo("/a/b/", "/a/b/c", "simple"); demo("/a/b/../b", "/a/b", "no canonical conversion"); demo("/a/b", "/a/b/.", "no canonical conversion"); demo("/a/b/", "a/c", "absolute paths order after relative ones"); } ``` Output: ``` "/a/b/" == "/a/b/" : simple "/a/b/" < "/a/b/c" : simple "/a/b/../b" > "/a/b" : no canonical conversion "/a/b" < "/a/b/." : no canonical conversion "/a/b/" > "a/c" : absolute paths order after relative ones ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2936](https://cplusplus.github.io/LWG/issue2936) | C++17 | compared all path elements directly | root name and root directory handled separately | ### See also | | | | --- | --- | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](operator_cmp "cpp/filesystem/path/operator cmp") (until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20) | lexicographically compares two paths (function) | cpp std::filesystem::path::remove_filename std::filesystem::path::remove\_filename ======================================= | | | | | --- | --- | --- | | ``` path& remove_filename(); ``` | | (since C++17) | Removes a single generic-format filename component (as returned by [`filename`](filename "cpp/filesystem/path/filename")) from the given generic-format path. After this function completes, [`has_filename`](has_path "cpp/filesystem/path/has path") returns `false`. ### Parameters (none). ### Return value `*this`. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::path p; std::cout << std::boolalpha << (p = "foo/bar").remove_filename() << '\t' << p.has_filename() << '\n' << (p = "foo/" ).remove_filename() << '\t' << p.has_filename() << '\n' << (p = "/foo" ).remove_filename() << '\t' << p.has_filename() << '\n' << (p = "/" ).remove_filename() << '\t' << p.has_filename() << '\n' << (p = "" ).remove_filename() << '\t' << p.has_filename() << '\n' ; } ``` Output: ``` "foo/" false "foo/" false "/" false "/" false "" false ``` ### See also | | | | --- | --- | | [filename](filename "cpp/filesystem/path/filename") | returns the filename path component (public member function) | | [replace\_filename](replace_filename "cpp/filesystem/path/replace filename") | replaces the last path component with another path (public member function) | | [has\_filename](has_path "cpp/filesystem/path/has path") | checks if the corresponding path element is not empty (public member function) |
programming_docs
cpp std::filesystem::path::format std::filesystem::path::format ============================= | | | | | --- | --- | --- | | ``` enum format { native_format, generic_format, auto_format }; ``` | | (since C++17) | Determines how string representations of pathnames are interpreted by the constructors of [`std::filesystem::path`](../path "cpp/filesystem/path") that accept strings. ### Constants | Value | Explanation | | --- | --- | | `native_format` | Native pathname format | | `generic_format` | Generic pathname format | | `auto_format` | Implementation-defined pathname format, auto-detected where possible | ### Notes On POSIX systems, there is no difference between native and generic format. ### See also | | | | --- | --- | | [(constructor)](path "cpp/filesystem/path/path") | constructs a `path` (public member function) | cpp std::filesystem::path::extension std::filesystem::path::extension ================================ | | | | | --- | --- | --- | | ``` path extension() const; ``` | | (since C++17) | Returns the extension of the filename component of the generic-format view of `*this`. If the [`filename()`](filename "cpp/filesystem/path/filename") component of the generic-format path contains a period (`.`), and is not one of the special filesystem elements dot or dot-dot, then the *extension* is the substring beginning at the rightmost period (including the period) and until the end of the pathname. If the first character in the filename is a period, that period is ignored (a filename like ".profile" is not treated as an extension). If the pathname is either `.` or `..`, or if [`filename()`](filename "cpp/filesystem/path/filename") does not contain the `'.'` character, then empty path is returned. Additional behavior may be defined by the implementations for file systems which append additional elements (such as alternate data streams or partitioned dataset names) to extensions. ### Parameters (none). ### Return value The extension of the current pathname or an empty path if there's no extension. ### Exceptions May throw implementation-defined exceptions. ### Notes The extension as returned by this function includes a period to make it possible to distinguish the file that ends with a period (function returns `"."`) from a file with no extension (function returns `""`). On a non-POSIX system, it is possible that `p.stem()+p.extension() != p.filename()` even though generic-format versions are the same. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { std::cout << fs::path("/foo/bar.txt").extension() << '\n' << fs::path("/foo/bar.").extension() << '\n' << fs::path("/foo/bar").extension() << '\n' << fs::path("/foo/bar.txt/bar.cc").extension() << '\n' << fs::path("/foo/bar.txt/bar.").extension() << '\n' << fs::path("/foo/bar.txt/bar").extension() << '\n' << fs::path("/foo/.").extension() << '\n' << fs::path("/foo/..").extension() << '\n' << fs::path("/foo/.hidden").extension() << '\n' << fs::path("/foo/..bar").extension() << '\n'; } ``` Output: ``` ".txt" "." "" ".cc" "." "" "" "" "" ".bar" ``` ### See also | | | | --- | --- | | [filename](filename "cpp/filesystem/path/filename") | returns the filename path component (public member function) | | [stem](stem "cpp/filesystem/path/stem") | returns the stem path component (filename without the final extension) (public member function) | | [replace\_extension](replace_extension "cpp/filesystem/path/replace extension") | replaces the extension (public member function) | | [has\_extension](has_path "cpp/filesystem/path/has path") | checks if the corresponding path element is not empty (public member function) | cpp std::filesystem::path::parent_path std::filesystem::path::parent\_path =================================== | | | | | --- | --- | --- | | ``` path parent_path() const; ``` | | (since C++17) | Returns the path to the parent directory. If `has_relative_path()` returns false, the result is a copy of `*this`. Otherwise, the result is a path whose generic format pathname is the longest prefix of the generic format pathname of `*this` that produces one fewer element in its iteration. ### Parameters (none). ### Return value The path to the parent directory, or a copy of `*this` if not `has_relative_path()`. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { for(fs::path p : {"/var/tmp/example.txt", "/", "/var/tmp/."}) std::cout << "The parent path of " << p << " is " << p.parent_path() << '\n'; } ``` Possible output: ``` The parent path of "/var/tmp/example.txt" is "/var/tmp" The parent path of "/" is "/" The parent path of "/var/tmp/." is "/var/tmp" ``` ### See also | | | | --- | --- | | [root\_name](root_name "cpp/filesystem/path/root name") | returns the root-name of the path, if present (public member function) | | [root\_directory](root_directory "cpp/filesystem/path/root directory") | returns the root directory of the path, if present (public member function) | | [root\_path](root_path "cpp/filesystem/path/root path") | returns the root path of the path, if present (public member function) | cpp std::filesystem::path::generic_string, std::filesystem::path::generic_wstring, std::filesystem::path::generic_u8string, std::filesystem::path::generic_u16string, std::filesystem::path::generic_u32string std::filesystem::path::generic\_string, std::filesystem::path::generic\_wstring, std::filesystem::path::generic\_u8string, std::filesystem::path::generic\_u16string, std::filesystem::path::generic\_u32string =============================================================================================================================================================================================================== | | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT>, class Alloc = std::allocator<CharT> > std::basic_string<CharT,Traits,Alloc> generic_string( const Alloc& a = Alloc() ) const; ``` | (1) | (since C++17) | | | (2) | (since C++17) | | ``` std::string generic_string() const; ``` | | | ``` std::wstring generic_wstring() const; ``` | | | ``` std::u16string generic_u16string() const; ``` | | | ``` std::u32string generic_u32string() const; ``` | | | | (3) | | | ``` std::string generic_u8string() const; ``` | (since C++17) (until C++20) | | ``` std::u8string generic_u8string() const; ``` | (since C++20) | Returns the internal pathname in generic pathname format, converted to specific string type. Conversion, if any, is specified as follows: * If `path::value_type` is `char`, conversion, if any, is system-dependent. This is the case on typical POSIX systems (such as Linux), where native encoding is UTF-8 and `string()` performs no conversion. * Otherwise, if `path::value_type` is `wchar_t`, conversion, if any, is unspecified. This is the case on Windows, where wchar\_t is 16 bit and the native encoding is UTF-16. * Otherwise, if `path::value_type` is `char16_t`, native encoding is UTF-16 and the conversion method is unspecified. * Otherwise, if `path::value_type` is `char32_t`, native encoding is UTF-32 and the conversion method is unspecified. * Otherwise, if `path::value_type` is `char8_t`, native encoding is UTF-8 and the conversion method is unspecified. The `/` character is used as the directory separator. 1) All memory allocations are performed by `a`. 3) The result encoding in the case of `u8string()` is always UTF-8. ### Parameters | | | | | --- | --- | --- | | a | - | allocator to construct the string with | | Type requirements | | -`CharT` must be one of the encoded character types (`char`, `wchar_t`, `char8_t` (since C++20), `char16_t` and `char32_t`) | ### Return value The internal pathname in generic pathname format, converted to specified string type. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <cstddef> #include <filesystem> #include <iomanip> #include <iostream> #include <span> #include <string_view> void print(std::string_view rem, auto const& str) { std::cout << rem << std::hex << std::uppercase << std::setfill('0'); for (const auto b : std::as_bytes(std::span{str})) { std::cout << std::setw(2) << std::to_integer<unsigned>(b) << ' '; } std::cout << '\n'; } int main() { std::filesystem::path p{"/家/屋"}; std::cout << p << '\n'; print("string : ", p.generic_string ()); print("u8string : ", p.generic_u8string ()); print("u16string : ", p.generic_u16string()); print("u32string : ", p.generic_u32string()); // print("wstring : ", p.generic_wstring ()); // gcc-11.0.0 2020.12.30 still fails, clang-10 - ok } ``` Possible output: ``` "/家/屋" string : 2F E5 AE B6 2F E5 B1 8B u8string : 2F E5 AE B6 2F E5 B1 8B u16string : 2F 00 B6 5B 2F 00 4B 5C u32string : 2F 00 00 00 B6 5B 00 00 2F 00 00 00 4B 5C 00 00 ``` ### See also | | | | --- | --- | | [stringwstringu8stringu16stringu32string](string "cpp/filesystem/path/string") | returns the path in native pathname format converted to a string (public member function) | cpp std::filesystem::hash_value std::filesystem::hash\_value ============================ | Defined in header `[<filesystem>](../../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` std::size_t hash_value( const std::filesystem::path& p ) noexcept; ``` | | (since C++17) | ### Parameters | | | | | --- | --- | --- | | p | - | a `[std::filesystem::path](../path "cpp/filesystem/path")` object | ### Return value A hash value such that if for two paths, `p1 == p2` then `hash_value(p1) == hash_value(p2)`. The return value is consistent with [`std::hash`](hash "cpp/filesystem/path/hash"). ### Notes Equality of two paths is determined by comparing each component separately, so, for example `"a//b"` equals `"a/b"` and has the same `hash_value`. `hash_value` originates from the [Boost.filesystem](https://www.boost.org/doc/libs/release/libs/filesystem/doc/index.htm) library where it was used for interoperability with boost.hash (which calls `hash_value` found by [argument-dependent lookup](../../language/adl "cpp/language/adl") or [`boost::hash_value`](https://www.boost.org/doc/libs/1_76_0/doc/html/hash/reference.html#id-1_3_11_11_2_2_27-bb) where available). ### Example ``` #include <cassert> #include <cstddef> #include <iomanip> #include <iostream> #include <filesystem> #include <unordered_set> namespace fs = std::filesystem; void show_hash(fs::path const& p) { std::cout << std::hex << std::uppercase << std::setw(16) << fs::hash_value(p) << " : " << p << '\n'; } int main() { auto tmp1 = fs::path{"/tmp"}; auto tmp2 = fs::path{"/tmp/../tmp"}; assert( ! (tmp1 == tmp2) ); assert( fs::equivalent(tmp1, tmp2) ); show_hash( tmp1 ); show_hash( tmp2 ); for (auto s : {"/a///b", "/a//b", "/a/c", "...", "..", ".", ""}) show_hash(s); // A hash function object to work with unordered_* containers: struct PathHash { std::size_t operator()(fs::path const& p) const noexcept { return fs::hash_value(p); } }; std::unordered_set<fs::path, PathHash> dirs { "/bin", "/bin", "/lib", "/lib", "/opt", "/opt", "/tmp", "/tmp/../tmp" }; for (fs::path const& p: dirs) { std::cout << p << ' '; } } ``` Possible output: ``` 6050C47ADB62DFE5 : "/tmp" 62795A58B69AD90A : "/tmp/../tmp" FF302110C9991974 : "/a///b" FF302110C9991974 : "/a//b" FD6167277915D464 : "/a/c" C42040F82CD8B542 : "..." D2D30154E0B78BBC : ".." D18C722215ED0530 : "." 0 : "" "/tmp/../tmp" "/opt" "/lib" "/tmp" "/bin" ``` ### See also | | | | --- | --- | | [compare](compare "cpp/filesystem/path/compare") | compares the lexical representations of two paths lexicographically (public member function) | | [operator==operator!=operator<operator<=operator>operator>=operator<=>](operator_cmp "cpp/filesystem/path/operator cmp") (until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20) | lexicographically compares two paths (function) | | [equivalent](../equivalent "cpp/filesystem/equivalent") (C++17) | checks whether two paths refer to the same file system object (function) | | [hash](../../utility/hash "cpp/utility/hash") (C++11) | hash function object (class template) | | [std::hash<std::filesystem::path>](hash "cpp/filesystem/path/hash") (C++17) | hash support for `[std::filesystem::path](../path "cpp/filesystem/path")` (class template specialization) | cpp std::filesystem::path::root_name std::filesystem::path::root\_name ================================= | | | | | --- | --- | --- | | ``` path root_name() const; ``` | | (since C++17) | Returns the root name of the generic-format path. If the path (in generic format) does not include root name, returns `path()`. ### Parameters (none). ### Return value The root name of the path. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { std::cout << "Current root name is: " << fs::current_path().root_name() << '\n'; } ``` Possible output: ``` Current root name is: "C:" ``` ### See also | | | | --- | --- | | [root\_directory](root_directory "cpp/filesystem/path/root directory") | returns the root directory of the path, if present (public member function) | | [root\_path](root_path "cpp/filesystem/path/root path") | returns the root path of the path, if present (public member function) | cpp std::filesystem::path::stem std::filesystem::path::stem =========================== | | | | | --- | --- | --- | | ``` path stem() const; ``` | | (since C++17) | Returns the filename identified by the generic-format path stripped of its extension. Returns the substring from the beginning of [`filename()`](filename "cpp/filesystem/path/filename") up to and not including the last period (`.`) character, with the following exceptions: * If the first character in the filename is a period, that period is ignored (a filename like ".profile" is not treated as an extension). + If the filename is one of the special filesystem components dot or dot-dot, or if it has no periods, the function returns the entire [`filename()`](filename "cpp/filesystem/path/filename"). ### Parameters (none). ### Return value The stem of the filename identified by the path (i.e. the filename without the final extension). ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { for (const fs::path p : {"/foo/bar.txt", "/foo/.bar", "foo.bar.baz.tar"}) std::cout << "path: " << p << ", stem: " << p.stem() << '\n'; std::cout << '\n'; for (fs::path p = "foo.bar.baz.tar"; !p.extension().empty(); p = p.stem()) std::cout << "path: " << p << ", extension: " << p.extension() << '\n'; } ``` Output: ``` path: "/foo/bar.txt", stem: "bar" path: "/foo/.bar", stem: ".bar" path: "foo.bar.baz.tar", stem: "foo.bar.baz" path: "foo.bar.baz.tar", extension: ".tar" path: "foo.bar.baz", extension: ".baz" path: "foo.bar", extension: ".bar" ``` ### See also | | | | --- | --- | | [filename](filename "cpp/filesystem/path/filename") | returns the filename path component (public member function) | | [extension](extension "cpp/filesystem/path/extension") | returns the file extension path component (public member function) | cpp std::filesystem::path::~path std::filesystem::path::~path ============================ | | | | | --- | --- | --- | | ``` ~path(); ``` | | (since C++17) | Destroys the path object. cpp std::filesystem::path::swap std::filesystem::path::swap =========================== | | | | | --- | --- | --- | | ``` void swap( path& other ) noexcept; ``` | (1) | (since C++17) | Swaps the contents (both native and generic format) of `*this` and `other`. ### Parameters | | | | | --- | --- | --- | | other | - | another path to exchange the contents with | ### Return value (none). ### Complexity Constant. ### See also | | | | --- | --- | | [swap(std::filesystem::path)](swap2 "cpp/filesystem/path/swap2") (C++17) | swaps two paths (function) | cpp std::filesystem::path::append, std::filesystem::path::operator/= std::filesystem::path::append, std::filesystem::path::operator/= ================================================================ | | | | | --- | --- | --- | | ``` path& operator/=( const path& p ); ``` | (1) | (since C++17) | | ``` template< class Source > path& operator/=( const Source& source ); ``` | (2) | (since C++17) | | ``` template< class Source > path& append( const Source& source ); ``` | (3) | (since C++17) | | ``` template< class InputIt > path& append( InputIt first, InputIt last ); ``` | (4) | (since C++17) | 1) If `p.is_absolute() || (p.has_root_name() && p.root_name() != root_name())`, then replaces the current path with p as if by `operator=(p)` and finishes. \* Otherwise, if `p.has_root_directory()`, then removes any root directory and the entire relative path from the generic format pathname of `*this` \* Otherwise, if `has_filename() || (!has_root_directory() && is_absolute())`, then appends `path::preferred_separator` to the generic format of `*this` \* Either way, then appends the native format pathname of `p`, omitting any root-name from its generic format, to the native format of `*this`. ``` // where "//host" is a root-name path("//host") / "foo" // the result is "//host/foo" (appends with separator) path("//host/") / "foo" // the result is also "//host/foo" (appends without separator) // On POSIX, path("foo") / "" // the result is "foo/" (appends) path("foo") / "/bar"; // the result is "/bar" (replaces) // On Windows, path("foo") / "C:/bar"; // the result is "C:/bar" (replaces) path("foo") / "C:"; // the result is "C:" (replaces) path("C:") / ""; // the result is "C:" (appends, without separator) path("C:foo") / "/bar"; // yields "C:/bar" (removes relative path, then appends) path("C:foo") / "C:bar"; // yields "C:foo/bar" (appends, omitting p's root-name) ``` 2,3) Same as (1), but accepts any `[std::basic\_string](../../string/basic_string "cpp/string/basic string")`, `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")`, null-terminated multicharacter string, or an input iterator pointing to a null-terminated multicharacter sequence. Equivalent to `return operator/=(path(source));`. 4) Same as (1), but accepts any iterator pair that designates a multicharacter string. Equivalent to `return operator/=(path(first, last));` (2) and (3) participate in overload resolution only if `Source` and `path` are not the same type, and either: * `Source` is a specialization of `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` or `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")`, or * `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<Source>>::value_type` is valid and denotes a possibly const-qualified encoding character type (`char`, `char8_t`, (since C++20)`char16_t`, `char32_t`, or `wchar_t`). ### Parameters | | | | | --- | --- | --- | | p | - | pathname to append | | source | - | `[std::basic\_string](../../string/basic_string "cpp/string/basic string")`, `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")`, null-terminated multicharacter string, or an input iterator pointing to a null-terminated multicharacter sequence, which represents a path name (either in portable or in native format) | | first, last | - | pair of [LegacyInputIterators](../../named_req/inputiterator "cpp/named req/InputIterator") that specify a multicharacter sequence that represents a path name | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | | -The value type of `InputIt` must be one of the encoded character types (`char`, `wchar_t`, `char16_t` and `char32_t`) | ### Return value `*this`. ### Exceptions May throw `[std::bad\_alloc](http://en.cppreference.com/w/cpp/memory/new/bad_alloc)` if memory allocation fails. ### Notes These functions effectively yield an approximation of the meaning of the argument path `p` in an environment where `*this` is the starting directory. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::path p1 = "C:"; p1 /= "Users"; // does not insert a separator std::cout << "\"C:\" / \"Users\" == " << p1 << '\n'; p1 /= "batman"; // inserts fs::path::preferred_separator, '\' on Windows std::cout << "\"C:\" / \"Users\" / \"batman\" == " << p1 << '\n'; } ``` Possible output: ``` "C:" / "Users" == "C:Users" "C:" / "Users" / "batman" == "C:Users\\batman" ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3244](https://cplusplus.github.io/LWG/issue3244) | C++17 | constraint that `Source` cannot be `path` was missing | added | ### See also | | | | --- | --- | | [concatoperator+=](concat "cpp/filesystem/path/concat") | concatenates two paths without introducing a directory separator (public member function) | | [operator/](operator_slash "cpp/filesystem/path/operator slash") | concatenates two paths with a directory separator (function) |
programming_docs
cpp std::filesystem::path::assign std::filesystem::path::assign ============================= | | | | | --- | --- | --- | | ``` path& assign( string_type&& source ); ``` | (1) | (since C++17) | | ``` template< class Source > path& assign( const Source& source ); ``` | (2) | (since C++17) | | ``` template< class InputIt > path& assign( InputIt first, InputIt last ); ``` | (3) | (since C++17) | Replaces the contents to the `path` object by a new pathname constructed from the given character sequence. 1) Assigns the pathname identified by the detected-format string `source`, which is left in valid, but unspecified state. 2) Assigns the pathname identified by the detected-format character range `source`. 3) Assigns the pathname identified by detected-format character range `[first, last)`. (2) participates in overload resolution only if `Source` and `path` are not the same type, and either: * `Source` is a specialization of `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` or `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")`, or * `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<Source>>::value_type` is valid and denotes a possibly const-qualified encoding character type (`char`, `char8_t`, (since C++20)`char16_t`, `char32_t`, or `wchar_t`). ### Parameters | | | | | --- | --- | --- | | source | - | a character range to use, represented as `[std::string](../../string/basic_string "cpp/string/basic string")`, `[std::string\_view](../../string/basic_string_view "cpp/string/basic string view")`, pointer to a null-terminated multibyte string, or as an input iterator with char value type that points to a null-terminated multibyte string | | first, last | - | a character range to use | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | | -The value type of `InputIt` must be one of the encoded character types (`char`, `wchar_t`, `char16_t` and `char32_t`) | ### Return value `*this`. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3244](https://cplusplus.github.io/LWG/issue3244) | C++17 | constraint that `Source` cannot be `path` was missing | added | ### See also | | | | --- | --- | | [operator=](operator= "cpp/filesystem/path/operator=") | assigns another path (public member function) | cpp std::filesystem::path::is_absolute,is_relative std::filesystem::path::is\_absolute,is\_relative ================================================ | | | | | --- | --- | --- | | ``` bool is_absolute() const; ``` | (1) | (since C++17) | | ``` bool is_relative() const; ``` | (2) | (since C++17) | Checks whether the path is absolute or relative. An absolute path is a path that unambiguously identifies the location of a file without reference to an additional starting location. The first version returns `true` if the path, in native format, is absolute, `false` otherwise; the second version the other way round. ### Parameters (none). ### Return value 1) `true` if the path is absolute, `false` otherwise. 2) `false` if the path is absolute, `true` otherwise. ### Exceptions May throw implementation-defined exceptions. ### Notes The path `"/"` is absolute on a POSIX OS, but is relative on Windows. ### See also | | | | --- | --- | | [absolute](../absolute "cpp/filesystem/absolute") (C++17) | composes an absolute path (function) | cpp std::filesystem::path::relative_path std::filesystem::path::relative\_path ===================================== | | | | | --- | --- | --- | | ``` path relative_path() const; ``` | | (since C++17) | Returns path relative to root-path, that is, a pathname composed of every generic-format component of `*this` after root-path. If `*this` is an empty path, returns an empty path. ### Parameters (none). ### Return value Path relative to the [root path](root_path "cpp/filesystem/path/root path"). ### Exceptions May throw implementation-defined exceptions. ### Examples ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::path p = fs::current_path(); std::cout << "The current path " << p << " decomposes into:\n" << "root-path " << p.root_path() << '\n' << "relative path " << p.relative_path() << '\n'; } ``` Possible output: ``` The current path "C:\Users\abcdef\Local Settings\temp" decomposes into: root-path "C:\" relative path "Users\abcdef\Local Settings\temp" ``` ### See also | | | | --- | --- | | [root\_name](root_name "cpp/filesystem/path/root name") | returns the root-name of the path, if present (public member function) | | [root\_directory](root_directory "cpp/filesystem/path/root directory") | returns the root directory of the path, if present (public member function) | | [root\_path](root_path "cpp/filesystem/path/root path") | returns the root path of the path, if present (public member function) | cpp std::filesystem::path::root_directory std::filesystem::path::root\_directory ====================================== | | | | | --- | --- | --- | | ``` path root_directory() const; ``` | | (since C++17) | Returns the root directory of the generic-format path. If the path (in generic format) does not include root directory, returns `path()`. ### Parameters (none). ### Return value The root directory of the path. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::path p = fs::current_path(); std::cout << "The current path " << p << " decomposes into:\n" << "root name " << p.root_name() << '\n' << "root directory " << p.root_directory() << '\n' << "relative path " << p.relative_path() << '\n'; } ``` Possible output: ``` The current path "C:\Users\abcdef\Local Settings\temp" decomposes into: root name "C:" root directory "\" relative path "Users\abcdef\Local Settings\temp" ``` ### See also | | | | --- | --- | | [root\_name](root_name "cpp/filesystem/path/root name") | returns the root-name of the path, if present (public member function) | | [root\_path](root_path "cpp/filesystem/path/root path") | returns the root path of the path, if present (public member function) | cpp std::filesystem::path::root_path std::filesystem::path::root\_path ================================= | | | | | --- | --- | --- | | ``` path root_path() const; ``` | | (since C++17) | Returns the root path of the path. If the path does not include root path, returns `path()`. Effectively returns `root_name() / root_directory()`. ### Parameters (none). ### Return value The root path of the path. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { std::cout << "Current root path is: " << fs::current_path().root_path() << '\n'; } ``` Possible output: ``` Current root path is: "C:\" ``` ### See also | | | | --- | --- | | [root\_name](root_name "cpp/filesystem/path/root name") | returns the root-name of the path, if present (public member function) | | [root\_directory](root_directory "cpp/filesystem/path/root directory") | returns the root directory of the path, if present (public member function) | cpp std::filesystem::path::string, std::filesystem::path::wstring, std::filesystem::path::u8string, std::filesystem::path::u16string, std::filesystem::path::u32string std::filesystem::path::string, std::filesystem::path::wstring, std::filesystem::path::u8string, std::filesystem::path::u16string, std::filesystem::path::u32string ================================================================================================================================================================== | | | | | --- | --- | --- | | ``` template< class CharT, class Traits = std::char_traits<CharT>, class Alloc = std::allocator<CharT> > std::basic_string<CharT,Traits,Alloc> string( const Alloc& a = Alloc() ) const; ``` | (1) | (since C++17) | | | (2) | (since C++17) | | ``` std::string string() const; ``` | | | ``` std::wstring wstring() const; ``` | | | ``` std::u16string u16string() const; ``` | | | ``` std::u32string u32string() const; ``` | | | | (3) | | | ``` std::string u8string() const; ``` | (since C++17) (until C++20) | | ``` std::u8string u8string() const; ``` | (since C++20) | Returns the internal pathname in native pathname format, converted to specific string type. Conversion, if any, is performed as follows: * If `path::value_type` is `char`, conversion, if any, is system-dependent. This is the case on typical POSIX systems (such as Linux), where native encoding is UTF-8 and `string()` performs no conversion. * Otherwise, if `path::value_type` is `wchar_t`, conversion, if any, is unspecified. This is the case on Windows, where wchar\_t is 16 bit and the native encoding is UTF-16. * Otherwise, if `path::value_type` is `char16_t`, native encoding is UTF-16 and the conversion method is unspecified. * Otherwise, if `path::value_type` is `char32_t`, native encoding is UTF-32 and the conversion method is unspecified. * Otherwise, if `path::value_type` is `char8_t`, native encoding is UTF-8 and the conversion method is unspecified. 1) All memory allocations are performed by `a`. 3) The result encoding in the case of `u8string()` is always UTF-8. ### Parameters (none). ### Return value The internal pathname in native pathname format, converted to specified string type. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <cstdio> #include <clocale> #include <filesystem> #include <fstream> #include <iostream> #include <locale> int main() { const char* const localeName = "ja_JP.utf-8"; std::setlocale(LC_ALL, localeName); std::locale::global(std::locale(localeName)); const std::filesystem::path p(u8"要らない.txt"); std::ofstream(p) << "File contents"; // native string representation can be used with OS APIs if (std::FILE* const f = std::fopen(p.string().c_str(), "r")) { int ch; while ((ch = fgetc(f)) != EOF) putchar(ch); std::fclose(f); } // multibyte and wide representation can be used for output std::cout << "\nFile name in narrow multibyte encoding: " << p.string() << '\n'; // wstring() will throw in stdlibc++, see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102839 std::wcout << "File name in wide encoding: " << p.wstring() << '\n'; std::filesystem::remove(p); } ``` Possible output: ``` File contents File name in narrow multibyte encoding: 要らない.txt File name in wide encoding: 要らない.txt ``` ### See also | | | | --- | --- | | [generic\_stringgeneric\_wstringgeneric\_u8stringgeneric\_u16stringgeneric\_u32string](generic_string "cpp/filesystem/path/generic string") | returns the path in generic pathname format converted to a string (public member function) | cpp std::filesystem::path::c_str, std::filesystem::path::native, std::filesystem::path::operator string_type() std::filesystem::path::c\_str, std::filesystem::path::native, std::filesystem::path::operator string\_type() ============================================================================================================ | | | | | --- | --- | --- | | ``` const value_type* c_str() const noexcept; ``` | (1) | (since C++17) | | ``` const string_type& native() const noexcept; ``` | (2) | (since C++17) | | ``` operator string_type() const; ``` | (3) | (since C++17) | Accesses the native path name as a character string. 1) Equivalent to `native().c_str()`. 2) Returns the native-format representation of the pathname by reference. 3) Returns the native-format representation of the pathname by value. ### Parameters (none). ### Return value The native string representation of the pathname, using native syntax, native character type, and native character encoding. This string is suitable for use with OS APIs. ### Notes The conversion function (3) is provided so that APIs that accept `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` file names can use pathnames with no changes to code. ### Example ``` #include <cstdio> #ifdef _MSC_VER #include <io.h> #include <fcntl.h> #else #include <locale> #include <clocale> #endif #include <fstream> #include <filesystem> int main() { #ifdef _MSC_VER _setmode(_fileno(stderr), _O_WTEXT); #else std::setlocale(LC_ALL, ""); std::locale::global(std::locale("")); #endif std::filesystem::path p(u8"要らない.txt"); std::ofstream(p) << "File contents"; // Prior to LWG2676 uses operator string_type() // on MSVC, where string_type is wstring, only // works due to non-standard extension. // Post-LWG2676 uses new fstream constructors // native string representation can be used with OS APIs if (std::FILE* f = #ifdef _MSC_VER _wfopen(p.c_str(), L"r") #else std::fopen(p.c_str(), "r") #endif ) { int ch; while((ch=fgetc(f)) != EOF) putchar(ch); std::fclose(f); } std::filesystem::remove(p); } ``` Possible output: ``` File contents ``` ### See also | | | | --- | --- | | [stringwstringu8stringu16stringu32string](string "cpp/filesystem/path/string") | returns the path in native pathname format converted to a string (public member function) | | [generic\_stringgeneric\_wstringgeneric\_u8stringgeneric\_u16stringgeneric\_u32string](generic_string "cpp/filesystem/path/generic string") | returns the path in generic pathname format converted to a string (public member function) | cpp std::filesystem::swap(std::filesystem::path) std::filesystem::swap(std::filesystem::path) ============================================ | Defined in header `[<filesystem>](../../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` void swap( std::filesystem::path& lhs, std::filesystem::path& rhs ) noexcept; ``` | | (since C++17) | Exchanges the state of `lhs` with that of `rhs`. Effectively calls `lhs.swap(rhs)`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | paths whose states to swap | ### Return value (none). ### See also | | | | --- | --- | | [swap](swap "cpp/filesystem/path/swap") | swaps two paths (public member function) | cpp std::filesystem::path::has_root_path, std::filesystem::path::has_root_name, std::filesystem::path::has_root_directory, std::filesystem::path::has_relative_path, std::filesystem::path::has_parent_path, std::filesystem::path::has_filename, std::filesystem::path::has_stem, std::filesystem::path::has_extension std::filesystem::path::has\_root\_path, std::filesystem::path::has\_root\_name, std::filesystem::path::has\_root\_directory, std::filesystem::path::has\_relative\_path, std::filesystem::path::has\_parent\_path, std::filesystem::path::has\_filename, std::filesystem::path::has\_stem, std::filesystem::path::has\_extension ================================================================================================================================================================================================================================================================================================================================ | | | | | --- | --- | --- | | ``` bool has_root_path() const; ``` | (1) | (since C++17) | | ``` bool has_root_name() const; ``` | (2) | (since C++17) | | ``` bool has_root_directory() const; ``` | (3) | (since C++17) | | ``` bool has_relative_path() const; ``` | (4) | (since C++17) | | ``` bool has_parent_path() const; ``` | (5) | (since C++17) | | ``` bool has_filename() const; ``` | (6) | (since C++17) | | ``` bool has_stem() const; ``` | (7) | (since C++17) | | ``` bool has_extension() const; ``` | (8) | (since C++17) | Checks whether the path contains the corresponding path element. 1) Checks whether [`root_path()`](root_path "cpp/filesystem/path/root path") is empty. 2) Checks whether [`root_name()`](root_name "cpp/filesystem/path/root name") is empty. 3) Checks whether [`root_directory()`](root_directory "cpp/filesystem/path/root directory") is empty. 4) Checks whether [`relative_path()`](relative_path "cpp/filesystem/path/relative path") is empty. 5) Checks whether [`parent_path()`](parent_path "cpp/filesystem/path/parent path") is empty. 6) Checks whether [`filename()`](filename "cpp/filesystem/path/filename") is empty. 7) Checks whether [`stem()`](stem "cpp/filesystem/path/stem") is empty. 8) Checks whether [`extension()`](extension "cpp/filesystem/path/extension") is empty. ### Parameters (none). ### Return value `true` if the corresponding path component is not empty, `false` otherwise. ### Exceptions May throw implementation-defined exceptions. ### Example ### See also | | | | --- | --- | | [empty](empty "cpp/filesystem/path/empty") | checks if the path is empty (public member function) | cpp std::filesystem::path::operator= std::filesystem::path::operator= ================================ | | | | | --- | --- | --- | | ``` path& operator=( const path& p ); ``` | (1) | (since C++17) | | ``` path& operator=( path&& p ) noexcept; ``` | (2) | (since C++17) | | ``` path& operator=( string_type&& source ); ``` | (3) | (since C++17) | | ``` template< class Source > path& operator=( const Source& source ); ``` | (4) | (since C++17) | 1) Replaces the contents of `*this` with a pathname whose both native and generic format representations equal those of `p`. 2) Replaces the contents of `*this` with a pathname whose both native and generic format representations equal those of `p`, possibly using move semantics: `p` is left in a valid, but unspecified state. 3) Replaces the contents of `*this` with a new path value constructed from detected-format `source`, which is left in valid, but unspecified state. Equivalent to `assign(std::move(source))`. 4) Replaces the contents of `*this` with a new path value constructed from detected-format `source` as if by overload (4) of the [path constructor](path "cpp/filesystem/path/path"). Equivalent to `assign(source)`. (4) participates in overload resolution only if `Source` and `path` are not the same type, and either: * `Source` is a specialization of `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` or `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")`, or * `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<Source>>::value_type` is valid and denotes a possibly const-qualified encoding character type (`char`, `char8_t`, (since C++20)`char16_t`, `char32_t`, or `wchar_t`). ### Parameters | | | | | --- | --- | --- | | p | - | a path to assign | | source | - | a `[std::basic\_string](../../string/basic_string "cpp/string/basic string")`, `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")`, pointer to a null-terminated character/wide character string, or an input iterator that points to a null-terminated character/wide character sequence. The character type must be one of `char`, `char8_t`, (since C++20)`char16_t`, `char32_t`, `wchar_t` | ### Return value `*this`. ### Example ``` #include <filesystem> namespace fs = std::filesystem; int main() { fs::path p = "C:/users/abcdef/AppData/Local"; p = p / "Temp"; // move assignment const wchar_t* wstr = L"D:/猫.txt"; p = wstr; // assignment from a source } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3244](https://cplusplus.github.io/LWG/issue3244) | C++17 | constraint that `Source` cannot be `path` was missing | added | ### See also | | | | --- | --- | | [assign](assign "cpp/filesystem/path/assign") | assigns contents (public member function) | | [(constructor)](path "cpp/filesystem/path/path") | constructs a `path` (public member function) |
programming_docs
cpp std::filesystem::path::clear std::filesystem::path::clear ============================ | | | | | --- | --- | --- | | ``` void clear() noexcept; ``` | | (since C++17) | Clears the stored pathname. [`empty()`](empty "cpp/filesystem/path/empty") is `true` after the call. ### Parameters (none). ### Return value (none). cpp std::filesystem::path::replace_filename std::filesystem::path::replace\_filename ======================================== | | | | | --- | --- | --- | | ``` path& replace_filename( const path& replacement ); ``` | | (since C++17) | Replaces a single filename component with `replacement`. Equivalent to: `remove_filename(); return operator/=(replacement);`. ### Parameters | | | | | --- | --- | --- | | replacement | - | `path` used for replacing the filename component | ### Return value `*this`. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { std::cout << fs::path("/foo").replace_filename("bar") << '\n' << fs::path("/").replace_filename("bar") << '\n' << fs::path("").replace_filename("pub") << '\n'; } ``` Output: ``` "/bar" "/bar" "pub" ``` ### See also | | | | --- | --- | | [replace\_extension](replace_extension "cpp/filesystem/path/replace extension") | replaces the extension (public member function) | | [filename](filename "cpp/filesystem/path/filename") | returns the filename path component (public member function) | | [remove\_filename](remove_filename "cpp/filesystem/path/remove filename") | removes filename path component (public member function) | | [has\_filename](has_path "cpp/filesystem/path/has path") | checks if the corresponding path element is not empty (public member function) | cpp std::filesystem::u8path std::filesystem::u8path ======================= | Defined in header `[<filesystem>](../../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` template< class Source > std::filesystem::path u8path( const Source& source ); ``` | (1) | (since C++17) (deprecated in C++20) | | ``` template< class InputIt > std::filesystem::path u8path( InputIt first, InputIt last ); ``` | (2) | (since C++17) (deprecated in C++20) | Constructs a path `p` from a UTF-8 encoded sequence of `char`s or `char8_t`s (since C++20), supplied either as an `[std::string](../../string/basic_string "cpp/string/basic string")`, or as `[std::string\_view](../../string/basic_string_view "cpp/string/basic string view")`, or as a null-terminated multibyte string, or as a [first, last) iterator pair. * If `path::value_type` is `char` and native encoding is UTF-8, constructs a path directly as if by `path(source)` or `path(first, last)`. Note: this is the typical situation of a POSIX system that uses Unicode, such as Linux. * Otherwise, if `path::value_type` is `wchar_t` and native encoding is UTF-16 (this is the situation on Windows), or if `path::value_type` is `char16_t` (native encoding guaranteed UTF-16) or `char32_t` (native encoding guaranteed UTF-32), then first converts the UTF-8 character sequence to a temporary string `tmp` of type `path::string_type` and then the new path is constructed as if by `path(tmp)` * Otherwise (for non-UTF-8 narrow character encodings and for non-UTF-16 `wchar_t`), first converts the UTF-8 character sequence to a temporary UTF-32-encoded string `tmp` of type `[std::u32string](http://en.cppreference.com/w/cpp/string/basic_string)`, and then the new path is constructed as if by `path(tmp)` (this path is taken on a POSIX system with a non-Unicode multibyte or single-byte encoded filesystem) ### Parameters | | | | | --- | --- | --- | | source | - | a UTF-8 encoded `[std::string](../../string/basic_string "cpp/string/basic string")`, `[std::string\_view](../../string/basic_string_view "cpp/string/basic string view")`, a pointer to a null-terminated multibyte string, or an input iterator with char value type that points to a null-terminated multibyte string | | first, last | - | pair of [LegacyInputIterators](../../named_req/inputiterator "cpp/named req/InputIterator") that specify a UTF-8 encoded character sequence | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | | -The value type of `Source` or `InputIt` must be `char` or `char8_t` (since C++20) | ### Return value The path constructed from the input string after conversion from UTF-8 to the filesystem's native character encoding. ### Exceptions May throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes On systems where native path format differs from the generic path format (neither Windows nor POSIX systems are examples of such OSes), if the argument to this function is using generic format, it will be converted to native. ### Example ``` #include <cstdio> #ifdef _MSC_VER #include <io.h> #include <fcntl.h> #else #include <locale> #include <clocale> #endif #include <fstream> #include <filesystem> int main() { #ifdef _MSC_VER _setmode(_fileno(stderr), _O_WTEXT); #else std::setlocale(LC_ALL, ""); std::locale::global(std::locale("")); #endif std::filesystem::path p(u8"要らない.txt"); std::ofstream(p) << "File contents"; // Prior to LWG2676 uses operator string_type() // on MSVC, where string_type is wstring, only // works due to non-standard extension. // Post-LWG2676 uses new fstream constructors // native string representation can be used with OS APIs if (std::FILE* f = #ifdef _MSC_VER _wfopen(p.c_str(), L"r") #else std::fopen(p.c_str(), "r") #endif ) { int ch; while((ch=fgetc(f)) != EOF) putchar(ch); std::fclose(f); } std::filesystem::remove(p); } ``` Possible output: ``` File contents ``` ### See also | | | | --- | --- | | [path](../path "cpp/filesystem/path") (C++17) | represents a path (class) | cpp std::filesystem::path::lexically_normal, std::filesystem::path::lexically_relative, std::filesystem::path::lexically_proximate std::filesystem::path::lexically\_normal, std::filesystem::path::lexically\_relative, std::filesystem::path::lexically\_proximate ================================================================================================================================= | | | | | --- | --- | --- | | ``` path lexically_normal() const; ``` | (1) | (since C++17) | | ``` path lexically_relative(const path& base) const; ``` | (2) | (since C++17) | | ``` path lexically_proximate(const path& base) const; ``` | (3) | (since C++17) | 1) Returns `*this` converted to [normal form](../path "cpp/filesystem/path") in its generic format 2) Returns `*this` made relative to `base`. * First, if `root_name() != base.root_name()` is `true` or `is_absolute() != base.is_absolute()` is `true` or `(!has_root_directory() && base.has_root_directory())` is `true` or any filename in `relative_path()` or `base.relative_path()` can be interpreted as a root-name, returns a default-constructed path. * Otherwise, first determines the first mismatched element of `*this` and `base` as if by `auto [a, b] = mismatch(begin(), end(), base.begin(), base.end())`, then * if `a == end()` and `b == base.end()`, returns `path(".")`; * otherwise, define N as the number of nonempty filename elements that are neither dot nor dot-dot in `[b, base.end())`, minus the number of dot-dot filename elements, If N < 0, returns a default-constructed path. * otherwise, if N = 0 and `a == end() || a->empty()`, returns `path(".")`. * otherwise returns an object composed from + a default-constructed `path()` followed by + N applications of `operator/=(path(".."))`, followed by + one application of `operator/=` for each element in the half-open range `[a, end())` 3) If the value of `lexically_relative(base)` is not an empty path, return it. Otherwise return `*this`. ### Parameters (none). ### Return value 1) The normal form of the path 2) The relative form of the path 3) The proximate form of the path ### Exceptions May throw implementation-defined exceptions. ### Notes These conversions are purely lexical. They do not check that the paths exist, do not follow symlinks, and do not access the filesystem at all. For symlink-following counterparts of `lexically_relative` and `lexically_proximate`, see [`relative`](../relative "cpp/filesystem/relative") and [`proximate`](../relative "cpp/filesystem/relative"). On Windows, the returned `path` has backslashes (the preferred separators). On POSIX, no filename in a relative path is acceptable as a root-name. ### Example ``` #include <iostream> #include <filesystem> #include <cassert> namespace fs = std::filesystem; int main() { assert(fs::path("a/./b/..").lexically_normal() == "a/"); assert(fs::path("a/.///b/../").lexically_normal() == "a/"); assert(fs::path("/a/d").lexically_relative("/a/b/c") == "../../d"); assert(fs::path("/a/b/c").lexically_relative("/a/d") == "../b/c"); assert(fs::path("a/b/c").lexically_relative("a") == "b/c"); assert(fs::path("a/b/c").lexically_relative("a/b/c/x/y") == "../.."); assert(fs::path("a/b/c").lexically_relative("a/b/c") == "."); assert(fs::path("a/b").lexically_relative("c/d") == "../../a/b"); assert(fs::path("a/b").lexically_relative("/a/b") == ""); assert(fs::path("a/b").lexically_proximate("/a/b") == "a/b"); } ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3070](https://cplusplus.github.io/LWG/issue3070) | C++17 | a filename that can also be a root-name may cause surprising result | treated as error case | | [LWG 3096](https://cplusplus.github.io/LWG/issue3096) | C++17 | trailing "/" and "/." are handled incorrectly | corrected | ### See also | | | | --- | --- | | [relativeproximate](../relative "cpp/filesystem/relative") (C++17) | composes a relative path (function) | cpp std::filesystem::path::concat, std::filesystem::path::operator+= std::filesystem::path::concat, std::filesystem::path::operator+= ================================================================ | | | | | --- | --- | --- | | ``` path& operator+=( const path& p ); ``` | (1) | (since C++17) | | ``` path& operator+=( const string_type& str ); path& operator+=( std::basic_string_view<value_type> str ); ``` | (2) | (since C++17) | | ``` path& operator+=( const value_type* ptr ); ``` | (3) | (since C++17) | | ``` path& operator+=( value_type x ); ``` | (4) | (since C++17) | | ``` template< class CharT > path& operator+=( CharT x ); ``` | (5) | (since C++17) | | ``` template< class Source > path& operator+=( const Source& source ); ``` | (6) | (since C++17) | | ``` template< class Source > path& concat( const Source& source ); ``` | (7) | (since C++17) | | ``` template< class InputIt > path& concat( InputIt first, InputIt last ); ``` | (8) | (since C++17) | Concatenates the current path and the argument. 1-3,6-7) Appends `path(p).native()` to the pathname stored in `*this` in the native format. This directly manipulates the value of `native()` and may not be portable between operating systems. 4-5) Same as `return \*this += [std::basic\_string\_view](http://en.cppreference.com/w/cpp/string/basic_string_view)(&x, 1);` 8) Same as `return *this += path(first, last);` (6) and (7) participate in overload resolution only if `Source` and `path` are not the same type, and either: * `Source` is a specialization of `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` or `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")`, or * `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<Source>>::value_type` is valid and denotes a possibly const-qualified encoding character type (`char`, `char8_t`, (since C++20)`char16_t`, `char32_t`, or `wchar_t`). ### Parameters | | | | | --- | --- | --- | | p | - | path to append | | str | - | string or string view to append | | ptr | - | pointer to the beginning of a null-terminated string to append | | x | - | single character to append | | source | - | `[std::basic\_string](../../string/basic_string "cpp/string/basic string")`, `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")`, null-terminated multicharacter string, or an input iterator pointing to a null-terminated multicharacter sequence, which represents a path name (either in portable or in native format) | | first, last | - | pair of [LegacyInputIterators](../../named_req/inputiterator "cpp/named req/InputIterator") that specify a multicharacter sequence that represents a path name | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | | -The value type of `InputIt` must be one of the encoded character types (`char`, `wchar_t`, `char16_t` and `char32_t`) | | -`CharT` must be one of the encoded character types (`char`, `wchar_t`, `char16_t` and `char32_t`) | ### Return value `*this`. ### Exceptions May throw `[std::bad\_alloc](http://en.cppreference.com/w/cpp/memory/new/bad_alloc)` if memory allocation fails. ### Notes Unlike with `[append()](append "cpp/filesystem/path/append")` or `[operator/=](append "cpp/filesystem/path/append")`, additional directory separators are never introduced. ### Example ``` #include <iostream> #include <filesystem> #include <string> int main() { std::filesystem::path p1; // an empty path p1 += "var"; // does not insert a separator std::cout << R"("" + "var" --> )" << p1 << '\n'; p1 += "lib"; // does not insert a separator std::cout << R"("var" + "lib" --> )" << p1 << '\n'; auto str = std::string{"1234567"}; p1.concat(std::begin(str)+3, std::end(str)-1); std::cout << "p1.concat --> " << p1 << '\n'; } ``` Output: ``` "" + "var" --> "var" "var" + "lib" --> "varlib" p1.concat --> "varlib456" ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3055](https://cplusplus.github.io/LWG/issue3055) | C++17 | the specification of concatenating a single character was ill-formed | made well-formed | | [LWG 3244](https://cplusplus.github.io/LWG/issue3244) | C++17 | constraint that `Source` cannot be `path` was missing | added | ### See also | | | | --- | --- | | [appendoperator/=](append "cpp/filesystem/path/append") | appends elements to the path with a directory separator (public member function) | | [operator/](operator_slash "cpp/filesystem/path/operator slash") | concatenates two paths with a directory separator (function) | cpp std::filesystem::operator/(std::filesystem::path) std::filesystem::operator/(std::filesystem::path) ================================================= | | | | | --- | --- | --- | | ``` friend path operator/( const path& lhs, const path& rhs ); ``` | | (since C++17) | Concatenates two path components using the preferred directory separator if appropriate (see [`operator/=`](append "cpp/filesystem/path/append") for details). Effectively returns `path(lhs) /= rhs`. This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::filesystem::path` is an associated class of the arguments. This prevents undesirable conversions in the presence of a `using namespace std::filesystem;` *using-directive*. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | paths to concatenate | ### Return value The result of path concatenation. ### Example ``` #include <iostream> #include <filesystem> int main() { # if defined(_WIN32) // see e.g. stackoverflow.com/questions/142508 std::filesystem::path p = "C:"; std::cout << "\"C:\" / \"Users\" / \"batman\" == " << p / "Users" / "batman" << '\n'; # else // __linux__ etc std::filesystem::path p = "/home"; std::cout << "\"/home\" / \"tux\" / \".fonts\" == " << p / "tux" / ".fonts" << '\n'; # endif } ``` Possible output: ``` Windows specific output: "C:" / "Users" / "batman" == "C:Users\\batman" Linux etc specific output: "/home" / "tux" / ".fonts" == "/home/tux/.fonts" ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3065](https://cplusplus.github.io/LWG/issue3065) | C++17 | allowed concatenating everything convertible to `path` in the presence of a *using-directive* | made hidden friend | ### See also | | | | --- | --- | | [appendoperator/=](append "cpp/filesystem/path/append") | appends elements to the path with a directory separator (public member function) | cpp operator==,!=,<,<=,>,>=,<=>(std::filesystem::path) operator==,!=,<,<=,>,>=,<=>(std::filesystem::path) ================================================== | | | | | --- | --- | --- | | ``` friend bool operator==( const path& lhs, const path& rhs ) noexcept; ``` | (1) | (since C++17) | | ``` friend bool operator!=( const path& lhs, const path& rhs ) noexcept; ``` | (2) | (since C++17) (until C++20) | | ``` friend bool operator<( const path& lhs, const path& rhs ) noexcept; ``` | (3) | (since C++17) (until C++20) | | ``` friend bool operator<=( const path& lhs, const path& rhs ) noexcept; ``` | (4) | (since C++17) (until C++20) | | ``` friend bool operator>( const path& lhs, const path& rhs ) noexcept; ``` | (5) | (since C++17) (until C++20) | | ``` friend bool operator>=( const path& lhs, const path& rhs ) noexcept; ``` | (6) | (since C++17) (until C++20) | | ``` friend std::strong_ordering operator<=>( const path& lhs, const path& rhs ) noexcept; ``` | (7) | (since C++20) | Compares two paths lexicographically. 1) Checks whether `lhs` and `rhs` are equal. Equivalent to `!(lhs < rhs) && !(rhs < lhs)`. 2) Checks whether `lhs` and `rhs` are not equal. Equivalent to `!(lhs == rhs)`. 3) Checks whether `lhs` is less than `rhs`. Equivalent to `lhs.compare(rhs) < 0`. 4) Checks whether `lhs` is less than or equal to `rhs`. Equivalent to `!(rhs < lhs)`. 5) Checks whether `lhs` is greater than `rhs`. Equivalent to `rhs < lhs`. 6) Checks whether `lhs` is greater than or equal to `rhs`. Equivalent to `!(lhs < rhs)`. 7) Obtains the three-way comparison result of `lhs` and `rhs`. Equivalent to `lhs.compare(rhs) <=> 0`. These functions are not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::filesystem::path` is an associated class of the arguments. This prevents undesirable conversions in the presence of a `using namespace std::filesystem;` *using-directive*. | | | | --- | --- | | The `<`, `<=`, `>`, `>=`, and `!=` operators are [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator<=>` and `operator==` respectively. | (since C++20) | ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | the paths to compare | ### Return value 1-6) `true` if the corresponding comparison yields, `false` otherwise. 7) `std::strong_ordering::less` if `lhs` is less than `rhs`, otherwise `std::strong_ordering::greater` if `rhs` is less than `lhs`, otherwise `std::strong_ordering::equal`. ### Notes Path equality and equivalence have different semantics. In the case of equality, as determined by `operator==`, only lexical representations are compared. Therefore, `path("a") == path("b")` is never `true`. In the case of equivalence, as determined by `[std::filesystem::equivalent()](../equivalent "cpp/filesystem/equivalent")`, it is checked whether two paths *resolve* to the same file system object. Thus `equivalent("a", "b")` will return `true` if the paths resolve to the same file. ### Example ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3065](https://cplusplus.github.io/LWG/issue3065) | C++17 | allowed comparison of everything convertible to `path` in the presence of a *using-directive* | made hidden friend | ### See also | | | | --- | --- | | [compare](compare "cpp/filesystem/path/compare") | compares the lexical representations of two paths lexicographically (public member function) | | [equivalent](../equivalent "cpp/filesystem/equivalent") (C++17) | checks whether two paths refer to the same file system object (function) |
programming_docs
cpp std::filesystem::path::empty std::filesystem::path::empty ============================ | | | | | --- | --- | --- | | ``` bool empty() const noexcept; ``` | | (since C++17) (until C++20) | | ``` [[nodiscard]] bool empty() const noexcept; ``` | | (since C++20) | Checks if the path in generic format is empty. ### Parameters (none). ### Return value `true` if the path is empty, `false` otherwise. ### Notes An empty path can be obtained by calling [`clear`](clear "cpp/filesystem/path/clear") and by default-constructing a `path`. It can also be returned by a path decomposition function (such as [`extension`](extension "cpp/filesystem/path/extension")) if the corresponding component is not present in the path. An empty path is classified as a relative path. ### See also | | | | --- | --- | | [(constructor)](path "cpp/filesystem/path/path") | constructs a `path` (public member function) | cpp std::filesystem::path::begin, std::filesystem::path::end std::filesystem::path::begin, std::filesystem::path::end ======================================================== | | | | | --- | --- | --- | | ``` iterator begin() const; ``` | (1) | (since C++17) | | ``` iterator end() const; ``` | (2) | (since C++17) | 1) Returns an iterator to the first element of the path. If the path is empty, the returned iterator is equal to `end()`. 2) Returns an iterator one past the last element of the path. Dereferencing this iterator is undefined behavior. The sequence denoted by this pair of iterators consists of the following: 1. root-name (if any) 2. root-directory (if any) 3. sequence of file-names, omitting any directory separators 4. If there is a directory separator after the last file-name in the path, the last element before the end iterator is an empty element. ### Parameters (none). ### Return value 1) Iterator to the first element of the path. 2) Iterator one past the end of the path ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { const fs::path p = # ifdef _WIN32 "C:\\users\\abcdef\\AppData\\Local\\Temp\\"; # else "/home/user/.config/Cppcheck/Cppcheck-GUI.conf"; # endif std::cout << "Examining the path " << p << " through iterators gives\n"; for (auto it = p.begin(); it != p.end(); ++it) std::cout << *it << " │ "; std::cout << '\n'; } ``` Possible output: ``` --- Windows --- Examining the path "C:\users\abcdef\AppData\Local\Temp\" through iterators gives "C:" │ "/" │ "users" │ "abcdef" │ "AppData" │ "Local" │ "Temp" │ "" │ --- UNIX --- Examining the path "/home/user/.config/Cppcheck/Cppcheck-GUI.conf" through iterators gives "/" │ "home" │ "user" │ ".config" │ "Cppcheck" │ "Cppcheck-GUI.conf" │ ``` cpp std::filesystem::path::make_preferred std::filesystem::path::make\_preferred ====================================== | | | | | --- | --- | --- | | ``` path& make_preferred(); ``` | | (since C++17) | Converts all directory separators in the generic-format view of the path to the preferred directory separator. For example, on Windows, where `\` is the preferred separator, the path `foo/bar` will be converted to `foo\bar`. ### Parameters (none). ### Return value `*this`. ### Exceptions May throw implementation-defined exceptions. ### Example Windows can use `/` as a separator, but prefers `\`, so `make_preferred` converts the forward slashes to backslashes. On the other hand, POSIX does not use `\` as a separator, because backslashes are valid filename characters — the Windows path on POSIX actually refers to a file with the name `"a\\b\\c"`. For this reason the "separators" are not converted. ``` #include <filesystem> #include <iostream> #include <iomanip> int main() { std::filesystem::path windows_path{"a\\b\\c"}; std::filesystem::path posix_path{"a/b/c"}; std::cout << "Windows path: " << std::quoted(windows_path.string()) << " -> " << std::quoted(windows_path.make_preferred().string()) << '\n' << "POSIX path: " << std::quoted(posix_path.string()) << " -> " << std::quoted(posix_path.make_preferred().string()) << '\n'; } ``` Output: ``` # on Windows Windows path: "a\\b\\c" -> "a\\b\\c" POSIX path: "a/b/c" -> "a\\b\\c" # on POSIX Windows path: "a\\b\\c" -> "a\\b\\c" POSIX path: "a/b/c" -> "a/b/c" ``` ### See also | | | | --- | --- | | constexpr value\_type preferred\_separator [static] | alternative directory separator which may be used in addition to the portable `/`. On Windows, this is the backslash character `\`. On POSIX, this is the same forward slash `/` as the portable separator (public static member constant) | cpp std::filesystem::path::filename std::filesystem::path::filename =============================== | | | | | --- | --- | --- | | ``` path filename() const; ``` | | (since C++17) | Returns the generic-format filename component of the path. Equivalent to `relative_path().empty() ? path() : *--end()`. ### Parameters (none). ### Return value The filename identified by the path. ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { std::cout << fs::path( "/foo/bar.txt" ).filename() << '\n' << fs::path( "/foo/.bar" ).filename() << '\n' << fs::path( "/foo/bar/" ).filename() << '\n' << fs::path( "/foo/." ).filename() << '\n' << fs::path( "/foo/.." ).filename() << '\n' << fs::path( "." ).filename() << '\n' << fs::path( ".." ).filename() << '\n' << fs::path( "/" ).filename() << '\n' << fs::path( "//host" ).filename() << '\n'; } ``` Output: ``` "bar.txt" ".bar" "" "." ".." "." ".." "" "host" ``` ### See also | | | | --- | --- | | [extension](extension "cpp/filesystem/path/extension") | returns the file extension path component (public member function) | | [stem](stem "cpp/filesystem/path/stem") | returns the stem path component (filename without the final extension) (public member function) | | [replace\_filename](replace_filename "cpp/filesystem/path/replace filename") | replaces the last path component with another path (public member function) | | [has\_filename](has_path "cpp/filesystem/path/has path") | checks if the corresponding path element is not empty (public member function) | cpp std::filesystem::path::path std::filesystem::path::path =========================== | | | | | --- | --- | --- | | ``` path() noexcept; ``` | (1) | (since C++17) | | ``` path( const path& p ); ``` | (2) | (since C++17) | | ``` path( path&& p ) noexcept; ``` | (3) | (since C++17) | | ``` path( string_type&& source, format fmt = auto_format ); ``` | (4) | (since C++17) | | ``` template< class Source > path( const Source& source, format fmt = auto_format ); ``` | (5) | (since C++17) | | ``` template< class InputIt > path( InputIt first, InputIt last, format fmt = auto_format ); ``` | (6) | (since C++17) | | ``` template< class Source > path( const Source& source, const std::locale& loc, format fmt = auto_format ); ``` | (7) | (since C++17) | | ``` template< class InputIt > path( InputIt first, InputIt last, const std::locale& loc, format fmt = auto_format ); ``` | (8) | (since C++17) | Constructs a new `path` object. 1) Constructs an empty path. 2) Copy constructor. Constructs a path whose pathname, in both native and generic formats, is the same as that of `p` 3) Move constructor. Constructs a path whose pathname, in both native and generic formats, is the same as that of `p`, `p` is left in valid but unspecified state. 4-6) Constructs the path from a character sequence (format interpreted as specified by `fmt`) provided by `source` (4,5), which is a pointer or an input iterator to a null-terminated character/wide character sequence, an `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` or an `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")`, or represented as a pair of input iterators [`first`, `last`) (6). Any of the character types `char`, `char8_t`, (since C++20)`char16_t`, `char32_t`, `wchar_t` is allowed, and the method of conversion to the native character set depends on the character type used by `source` * If the source character type is `char`, the encoding of the source is assumed to be the native narrow encoding (so no conversion takes place on POSIX systems) | | | | --- | --- | | * If the source character type is `char8_t`, conversion from UTF-8 to native filesystem encoding is used. | (since C++20) | * If the source character type is `char16_t`, conversion from UTF-16 to native filesystem encoding is used. * If the source character type is `char32_t`, conversion from UTF-32 to native filesystem encoding is used. * If the source character type is `wchar_t`, the input is assumed to be the native wide encoding (so no conversion takes places on Windows) 7-8) Constructs the path from a character sequence (format interpreted as specified by `fmt`) provided by `source` (7), which is a pointer or an input iterator to a null-terminated character sequence, an `[std::string](../../string/basic_string "cpp/string/basic string")`, an `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")`, or represented as a pair of input iterators [`first`, `last`) (8). The only character type allowed is `char`. Uses `loc` to perform the character encoding conversion. If `value_type` is `wchar_t`, converts from to wide using the `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<wchar\_t, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` facet of `loc`. Otherwise, first converts to wide using the `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<wchar\_t, char, [std::mbstate\_t](http://en.cppreference.com/w/cpp/string/multibyte/mbstate_t)>` facet and then converts to filesystem native character type using `[std::codecvt](http://en.cppreference.com/w/cpp/locale/codecvt)<wchar\_t,value_type>` facet of `loc`. (5) and (7) participate in overload resolution only if `Source` and `path` are not the same type, and either: * `Source` is a specialization of `[std::basic\_string](../../string/basic_string "cpp/string/basic string")` or `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")`, or * `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<Source>>::value_type` is valid and denotes a possibly const-qualified encoding character type (`char`, `char8_t`, (since C++20)`char16_t`, `char32_t`, or `wchar_t`). ### Parameters | | | | | --- | --- | --- | | p | - | a path to copy | | source | - | `[std::basic\_string](../../string/basic_string "cpp/string/basic string")`, `[std::basic\_string\_view](../../string/basic_string_view "cpp/string/basic string view")`, pointer to a null-terminated character string, or input iterator with a character value type that points to a null-terminated character sequence (the character type must be `char` for overload (7)) | | first, last | - | pair of [LegacyInputIterators](../../named_req/inputiterator "cpp/named req/InputIterator") that specify a character sequence | | fmt | - | enumerator of type [`path::format`](format "cpp/filesystem/path/format") which specifies how pathname format is to be interpreted | | loc | - | locale that defines encoding conversion to use | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../../named_req/inputiterator "cpp/named req/InputIterator"). | | -The value type of `InputIt` must be one of the character types `char`, `wchar_t`, `char8_t`, (since C++20)`char16_t` and `char32_t` to use the overload (6) | | -The value type of `InputIt` must be `char` to use the overload (8) | ### Exceptions 2, 4-8) May throw implementation-defined exceptions. ### Notes | | | | --- | --- | | For portable pathname generation from Unicode strings, see [`u8path`](u8path "cpp/filesystem/path/u8path"). | (until C++20) | | `path` constructor supports creation from UTF-8 string when the source is a sequence of `char8_t`. | (since C++20) | ### Example ``` #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::path p1 = "/usr/lib/sendmail.cf"; // portable format fs::path p2 = "C:\\users\\abcdef\\AppData\\Local\\Temp\\"; // native format fs::path p3 = U"D:/猫.txt"; // UTF-32 string fs::path p4 = u8"~/狗.txt"; // UTF-8 string std::cout << "p1 = " << p1 << '\n' << "p2 = " << p2 << '\n' << "p3 = " << p3 << '\n' << "p4 = " << p4 << '\n'; } ``` Output: ``` p1 = "/usr/lib/sendmail.cf" p2 = "C:\\users\\abcdef\\AppData\\Local\\Temp\\" p3 = "D:/猫.txt" p4 = "~/狗.txt" ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3244](https://cplusplus.github.io/LWG/issue3244) | C++17 | constraint that `Source` cannot be `path` was missing | added | ### See also | | | | --- | --- | | [u8path](u8path "cpp/filesystem/path/u8path") (C++17)(deprecated in C++20) | creates a `path` from a UTF-8 encoded source (function) | cpp std::filesystem::filesystem_error::filesystem_error std::filesystem::filesystem\_error::filesystem\_error ===================================================== | | | | | --- | --- | --- | | ``` filesystem_error( const std::string& what_arg, std::error_code ec ); ``` | (1) | (since C++17) | | ``` filesystem_error( const std::string& what_arg, const std::filesystem::path& p1, std::error_code ec ); ``` | (2) | (since C++17) | | ``` filesystem_error( const std::string& what_arg, const std::filesystem::path& p1, const std::filesystem::path& p2, std::error_code ec ); ``` | (3) | (since C++17) | | ``` filesystem_error( const filesystem_error& other ) noexcept; ``` | (4) | (since C++17) | Constructs a new `filesystem_error` object. 1-3) The error code is set to `ec` and optionally, the paths that were involved in the operation that resulted in the error, are set to `p1` and `p2`. `what()` after construction returns a string that contains `what_arg` (assuming that it does not contain an embedded null character ). If either or both `path` arguments are not provided, a null `path` is used instead. 4) Copy constructor. Initialize the contents with those of `other`. If `*this` and `other` both have dynamic type `std::filesystem_error::filesystem_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0`. ### Parameters | | | | | --- | --- | --- | | what\_arg | - | explanatory string | | ec | - | error code for the specific operating system dependent error | | p1, p2 | - | paths involved in the operation raising system error | | other | - | another `filesystem_error` object to copy | ### Notes Because copying `std::filesystem::filesystem_error` is not permitted to throw exceptions, the explanatory string is typically stored internally in a separately-allocated reference-counted storage. This is also why there is no constructor taking `std::string&&`: it would have to copy the content anyway. Typical implementations also store `path` objects referenced by `[path1()](path "cpp/filesystem/filesystem error/path")` and `[path2()](path "cpp/filesystem/filesystem error/path")` in the reference-counted storage. ### Example cpp std::filesystem::filesystem_error::operator= std::filesystem::filesystem\_error::operator= ============================================= | | | | | --- | --- | --- | | ``` filesystem_error& operator=( const filesystem_error& other ) noexcept; ``` | | (since C++17) | Assigns the contents with those of `other`. If `*this` and `other` both have dynamic type `std::filesystem::filesystem_error` then `[std::strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp)(what(), other.what()) == 0` after assignment. ### Parameters | | | | | --- | --- | --- | | other | - | another `filesystem_error` object to assign with | ### Return value `*this`. ### Notes Typical implementations store `path` objects referenced by `path1()` and `path2()` in a reference-counted storage. As a result, `*this` and `other` usually share their `path` objects after assignment. ### Example cpp std::filesystem::filesystem_error::what std::filesystem::filesystem\_error::what ======================================== | | | | | --- | --- | --- | | ``` const char* what() const noexcept override; ``` | | (since C++17) | Returns an explanatory byte string. This explanatory string contains the explanatory string passed at the time of construction. Implementations are encouraged to include the pathnames of `[path1()](path "cpp/filesystem/filesystem error/path")` and `[path2()](path "cpp/filesystem/filesystem error/path")` in native format and the `[std::system\_error::what()](../../error/system_error/what "cpp/error/system error/what")` string inside the returned string as well. ### Parameters (none). ### Return value A C-stye explanatory byte string that contains the explanatory string passed at the time of construction. ### Example ``` #include <cstdio> #include <filesystem> #include <iostream> #include <string_view> namespace fs = std::filesystem; void explain(std::string_view note, fs::filesystem_error const& ex) { std::cout << note << " exception:\n" << "what(): " << ex.what() << '\n' << "path1(): " << ex.path1() << ", path2(): " << ex.path2() << "\n\n"; } int main() { try { std::filesystem::rename("/dev", "/null"); } catch(fs::filesystem_error const& ex) { explain("fs::rename()", ex); } for (auto const path : {"/bool", "/bin/cat", "/bin/mouse"}) try { std::filesystem::create_directory(path); } catch(fs::filesystem_error const& ex) { explain("fs::create_directory()", ex); } } ``` Possible output: ``` fs::rename() exception: what(): filesystem error: cannot rename: Permission denied [/dev] [/null] path1(): "/dev", path2(): "/null" fs::create_directory() exception: what(): filesystem error: cannot create directory: Permission denied [/bool] path1(): "/bool", path2(): "" fs::create_directory() exception: what(): filesystem error: cannot create directory: File exists [/bin/cat] path1(): "/bin/cat", path2(): "" fs::create_directory() exception: what(): filesystem error: cannot create directory: Read-only file system [/bin/mouse] path1(): "/bin/mouse", path2(): "" ``` cpp std::filesystem::filesystem_error::path1, std::filesystem::filesystem_error::path2 std::filesystem::filesystem\_error::path1, std::filesystem::filesystem\_error::path2 ==================================================================================== | | | | | --- | --- | --- | | ``` const std::filesystem::path& path1() const noexcept; ``` | | (since C++17) | | ``` const std::filesystem::path& path2() const noexcept; ``` | | (since C++17) | Returns the paths that were stored in the exception object. ### Parameters (none). ### Return value References to the copy of the `path` parameters stored by the constructor. ### Example ``` #include <cstdio> #include <filesystem> #include <iostream> int main() { const std::filesystem::path old_p{std::tmpnam(nullptr)}, new_p{std::tmpnam(nullptr)}; try { std::filesystem::rename(old_p, new_p); // throws since old_p does not exist } catch(std::filesystem::filesystem_error const& ex) { std::cout << "what(): " << ex.what() << '\n' << "path1(): " << ex.path1() << '\n' << "path2(): " << ex.path2() << '\n'; } } ``` Possible output: ``` what(): filesystem error: cannot rename: No such file or directory [/tmp/fileIzzRLB] [/tmp/fileiUDWlV] path1(): "/tmp/fileIzzRLB" path2(): "/tmp/fileiUDWlV" ```
programming_docs
cpp std::filesystem::file_status::type std::filesystem::file\_status::type =================================== | | | | | --- | --- | --- | | ``` std::filesystem::file_type type() const noexcept; ``` | (1) | (since C++17) | | ``` void type( std::filesystem::file_type type ) noexcept; ``` | (2) | (since C++17) | Accesses the file type information. 1) Returns file type information. 2) Sets file type to `type`. ### Parameters | | | | | --- | --- | --- | | type | - | file type to set to | ### Return value 1) File type information. 2) (none) ### Example cpp operator==(std::filesystem::file_status) operator==(std::filesystem::file\_status) ========================================= | | | | | --- | --- | --- | | ``` friend bool operator==( const file_status& lhs, const file_status& rhs ) noexcept; ``` | | (since C++20) | Checks if two `file_status` values are equal, i.e. types and permissions represented by them are same respectively. This function is not visible to ordinary [unqualified](../../language/unqualified_lookup "cpp/language/unqualified lookup") or [qualified lookup](../../language/qualified_lookup "cpp/language/qualified lookup"), and can only be found by [argument-dependent lookup](../../language/adl "cpp/language/adl") when `std::filesystem::file_status` is an associated class of the arguments. The `!=` operator is [synthesized](../../language/operators#Relational_operators "cpp/language/operators") from `operator==`. ### Parameters | | | | | --- | --- | --- | | lhs, rhs | - | `file_status` values to compare | ### Return value `lhs.type() == rhs.type() && lhs.permissions() == rhs.permissions()`. ### See also | | | | --- | --- | | [type](type "cpp/filesystem/file status/type") | gets or sets the type of the file (public member function) | | [permissions](permissions "cpp/filesystem/file status/permissions") | gets or sets the permissions of the file (public member function) | cpp std::filesystem::file_status::operator= std::filesystem::file\_status::operator= ======================================== | | | | | --- | --- | --- | | ``` file_status& operator=( const file_status& other ) noexcept = default; ``` | (1) | (since C++17) | | ``` file_status& operator=( file_status&& other ) noexcept = default; ``` | (2) | (since C++17) | Copy- or move-assigns another file status object. ### Parameters | | | | | --- | --- | --- | | other | - | another file\_status object to assign | ### Return value `*this`. ### Example cpp std::filesystem::file_status::file_status std::filesystem::file\_status::file\_status =========================================== | | | | | --- | --- | --- | | ``` file_status() noexcept : file_status(std::filesystem::file_type::none) { } ``` | (1) | (since C++17) | | ``` file_status( const file_status& ) noexcept = default; ``` | (2) | (since C++17) | | ``` file_status( file_status&& ) noexcept = default; ``` | (3) | (since C++17) | | ``` explicit file_status( std::filesystem::file_type type, std::filesystem::perms permissions = std::filesystem::perms::unknown) noexcept; ``` | (4) | (since C++17) | Constructs a new `file_status` object. 1) Default constructor that calls (4) with `[std::filesystem::file\_type::none](../file_type "cpp/filesystem/file type")`. 2-3) Copy and move constructors are defaulted. 4) Initializes the file status object with `type` as type and `permissions` as permissions. ### Parameters | | | | | --- | --- | --- | | type | - | type of the file status | | permissions | - | permissions of the file status | ### Example cpp std::filesystem::file_status::permissions std::filesystem::file\_status::permissions ========================================== | | | | | --- | --- | --- | | ``` std::filesystem::perms permissions() const noexcept; ``` | (1) | (since C++17) | | ``` void permissions( std::filesystem::perms perm ) noexcept; ``` | (2) | (since C++17) | Accesses the file permissions information. 1) Returns file permissions information. 2) Sets file permissions to `perm`. ### Parameters | | | | | --- | --- | --- | | perm | - | file permissions to set to | ### Return value 1) File permissions information. 2) (none) ### Example cpp std::filesystem::recursive_directory_iterator::pop std::filesystem::recursive\_directory\_iterator::pop ==================================================== | | | | | --- | --- | --- | | ``` void pop(); ``` | (1) | (since C++17) | | ``` void pop(std::error_code& ec); ``` | (2) | (since C++17) | Moves the iterator one level up in the directory hierarchy. Invalidates all copies of the previous value of `*this`. If the parent directory is outside directory hierarchy that is iterated on (i.e. `depth() == 0`), sets `*this` to an end directory iterator. ### Parameters | | | | | --- | --- | --- | | ec | - | error code to store the error status to | ### Return value (none). ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. cpp std::filesystem::recursive_directory_iterator::depth std::filesystem::recursive\_directory\_iterator::depth ====================================================== | | | | | --- | --- | --- | | ``` int depth() const; ``` | | (since C++17) | Returns the number of directories from the starting directory to the currently iterated directory, i.e. the current depth of the directory hierarchy. The starting directory has depth of 0, its subdirectories have depth 1, etc. The behavior is undefined if `*this` is the end iterator. ### Parameters (none). ### Return value Current depth of the directory hierarchy. ### Exceptions Throws nothing. ### Example this example uses iteration depth to calculate the indentation of a directory tree printout. ``` #include <fstream> #include <iostream> #include <string> #include <filesystem> namespace fs = std::filesystem; int main() { fs::current_path(fs::temp_directory_path()); fs::create_directories("sandbox/a/b/c"); fs::create_directories("sandbox/a/b/d/e"); std::ofstream("sandbox/a/b/file1.txt"); fs::create_symlink("a", "sandbox/syma"); for(auto i = fs::recursive_directory_iterator("sandbox"); i != fs::recursive_directory_iterator(); ++i ) { std::cout << std::string(i.depth(), ' ') << *i; if(fs::is_symlink(i->symlink_status())) std::cout << " -> " << fs::read_symlink(*i); std::cout << '\n'; } fs::remove_all("sandbox"); } ``` Output: ``` "sandbox/a" "sandbox/a/b" "sandbox/a/b/c" "sandbox/a/b/d" "sandbox/a/b/d/e" "sandbox/a/b/file1.txt" "sandbox/syma" -> "a" ``` cpp std::filesystem::recursive_directory_iterator::operator*, std::filesystem::recursive_directory_iterator::operator-> std::filesystem::recursive\_directory\_iterator::operator\*, std::filesystem::recursive\_directory\_iterator::operator-> ======================================================================================================================== | | | | | --- | --- | --- | | ``` const std::filesystem::directory_entry& operator*() const; ``` | (1) | (since C++17) | | ``` const std::filesystem::directory_entry* operator->() const; ``` | (2) | (since C++17) | Accesses the pointed-to [`directory_entry`](../directory_entry "cpp/filesystem/directory entry"). The result of `operator*` or `operator->` on the end iterator is undefined behavior. ### Parameters (none). ### Return value 1) Value of the [`directory_entry`](../directory_entry "cpp/filesystem/directory entry") referred to by this iterator 2) Pointer to the [`directory_entry`](../directory_entry "cpp/filesystem/directory entry") referred to by this iterator ### Exceptions May throw implementation-defined exceptions. ### See also | | | | --- | --- | | [operator\*operator->](../directory_iterator/operator* "cpp/filesystem/directory iterator/operator*") | accesses the pointed-to entry (public member function of `std::filesystem::directory_iterator`) | cpp std::filesystem::recursive_directory_iterator::recursive_directory_iterator std::filesystem::recursive\_directory\_iterator::recursive\_directory\_iterator =============================================================================== | | | | | --- | --- | --- | | ``` recursive_directory_iterator() noexcept; ``` | (1) | (since C++17) | | ``` recursive_directory_iterator( const recursive_directory_iterator& rhs ); ``` | (2) | (since C++17) | | ``` recursive_directory_iterator( recursive_directory_iterator&& rhs ) noexcept; ``` | (3) | (since C++17) | | ``` explicit recursive_directory_iterator( const std::filesystem::path& p ); ``` | (4) | (since C++17) | | ``` recursive_directory_iterator( const std::filesystem::path& p, std::filesystem::directory_options options ); ``` | (4) | (since C++17) | | ``` recursive_directory_iterator( const std::filesystem::path& p, std::filesystem::directory_options options, std::error_code& ec ); ``` | (5) | (since C++17) | | ``` recursive_directory_iterator( const std::filesystem::path& p, std::error_code& ec ); ``` | (6) | (since C++17) | Contructs new recursive directory iterator. 1) Default constructor. Constructs an end iterator. 2) Copy constructor. 3) Move constructor. 4-6) Constructs a iterator that refers to the first entry in the directory that `p` resolves to. ### Parameters ### Exceptions The overload that does not take a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter throws [`filesystem::filesystem_error`](../filesystem_error "cpp/filesystem/filesystem error") on underlying OS API errors, constructed with `p` as the first path argument and the OS error code as the error code argument. The overload taking a `[std::error\_code](http://en.cppreference.com/w/cpp/error/error_code)&` parameter sets it to the OS API error code if an OS API call fails, and executes `ec.clear()` if no errors occur. Any overload not marked `noexcept` may throw `[std::bad\_alloc](../../memory/new/bad_alloc "cpp/memory/new/bad alloc")` if memory allocation fails. ### Notes Recursive directory iterators do not follow directory symlinks by default. To enable this behavior, specify `directory_options::follow_directory_symlink` among the `options` option set. ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3013](https://cplusplus.github.io/LWG/issue3013) | C++17 | `error_code` overload marked noexcept but can allocate memory | noexcept removed | cpp std::filesystem::recursive_directory_iterator::recursion_pending std::filesystem::recursive\_directory\_iterator::recursion\_pending =================================================================== | | | | | --- | --- | --- | | ``` bool recursion_pending() const; ``` | | (since C++17) | Returns `true` if the next increment will cause the directory currently referred to by `*this` to be iterated into. This function returns `true` immediately after construction or an increment. Recursion can be disabled via `[disable\_recursion\_pending()](disable_recursion_pending "cpp/filesystem/recursive directory iterator/disable recursion pending")`. ### Parameters (none). ### Return value `true` if the next increment will iterate into the currently referred directory, `false` otherwise. ### Exceptions Throws nothing. ### Example cpp std::filesystem::recursive_directory_iterator::disable_recursion_pending std::filesystem::recursive\_directory\_iterator::disable\_recursion\_pending ============================================================================ | | | | | --- | --- | --- | | ``` void disable_recursion_pending(); ``` | | (since C++17) | Disables recursion to the currently referred subdirectory, if any. The call modifies the pending recursion flag on the iterator in such a way that the next time [`increment`](increment "cpp/filesystem/recursive directory iterator/increment") is called, the iterator will advance within the current directory even if it is currently referring to a subdirectory that hasn't been visited. The status of the pending recursion flag can be queried with [`recursion_pending()`](recursion_pending "cpp/filesystem/recursive directory iterator/recursion pending"), which is `false` after this call. It is reset back to `true` after [`increment`](increment "cpp/filesystem/recursive directory iterator/increment"), and its initial value is also `true`. The behavior is undefined if `*this` is the end iterator. ### Parameters (none). ### Return value (none). ### Exceptions May throw implementation-defined exceptions. ### Example ``` #include <cstdlib> #include <fstream> #include <iostream> #include <string> #include <filesystem> namespace fs = std::filesystem; int main() { fs::current_path(fs::temp_directory_path()); fs::create_directories("sandbox/a/b/c"); fs::create_directories("sandbox/a/b/d/e"); std::ofstream("sandbox/a/b/file1.txt"); fs::create_symlink("a", "sandbox/syma"); std::system("tree sandbox"); for(auto i = fs::recursive_directory_iterator("sandbox"); i != fs::recursive_directory_iterator(); ++i ) { std::cout << std::string(i.depth()*2, ' ') << *i; if(fs::is_symlink(i->symlink_status())) std::cout << " -> " << fs::read_symlink(*i); std::cout << '\n'; // do not descend into "b" if(i->path().filename() == "b") i.disable_recursion_pending(); } fs::remove_all("sandbox"); } ``` Possible output: ``` sandbox ├── a │ └── b │ ├── c │ ├── d │ │ └── e │ └── file1.txt └── syma -> a "sandbox/a" "sandbox/a/b" "sandbox/syma" -> "a" ``` ### See also | | | | --- | --- | | [recursion\_pending](recursion_pending "cpp/filesystem/recursive directory iterator/recursion pending") | checks whether the recursion is disabled for the current directory (public member function) | | [incrementoperator++](increment "cpp/filesystem/recursive directory iterator/increment") | advances to the next entry (public member function) | cpp std::filesystem::recursive_directory_iterator::operator= std::filesystem::recursive\_directory\_iterator::operator= ========================================================== | | | | | --- | --- | --- | | ``` recursive_directory_iterator& operator=( const recursive_directory_iterator& other ) = default; ``` | | (since C++17) | | ``` recursive_directory_iterator& operator=( recursive_directory_iterator&& other ) = default; ``` | | (since C++17) | Assigns a recursive directory iterator. ### Parameters | | | | | --- | --- | --- | | other | - | another directory iterator to assign | ### Return value `*this`. ### Exceptions May throw implementation-defined exceptions. cpp std::filesystem::recursive_directory_iterator::options std::filesystem::recursive\_directory\_iterator::options ======================================================== | | | | | --- | --- | --- | | ``` std::filesystem::directory_options options() const; ``` | | (since C++17) | Returns the options that affect the directory iteration. The options can only be supplied when constructing the directory iterator. If the options argument was not supplied, returns `[std::filesystem::directory\_options::none](../directory_options "cpp/filesystem/directory options")`. ### Parameters (none). ### Return value The effective options that affect the directory iteration. ### Exceptions Throws nothing. cpp std::filesystem::begin(recursive_directory_iterator), std::filesystem::end(recursive_directory_iterator) std::filesystem::begin(recursive\_directory\_iterator), std::filesystem::end(recursive\_directory\_iterator) ============================================================================================================ | Defined in header `[<filesystem>](../../header/filesystem "cpp/header/filesystem")` | | | | --- | --- | --- | | ``` recursive_directory_iterator begin( recursive_directory_iterator iter ) noexcept; ``` | (1) | (since C++17) | | ``` recursive_directory_iterator end( recursive_directory_iterator ) noexcept; ``` | (2) | (since C++17) | 1) Returns `iter` unchanged. 2) Returns a default-constructed [`recursive_directory_iterator`](../recursive_directory_iterator "cpp/filesystem/recursive directory iterator"), which serves as the end iterator. The argument is ignored. These non-member functions enable the use of `recursive_directory_iterator`s with range-based for loops and make `recursive_directory_iterator` a [`range`](../../ranges/range "cpp/ranges/range") type (since C++20). ### Parameters | | | | | --- | --- | --- | | iter | - | a `recursive_directory_iterator` | ### Return value 1) `iter` unchanged. 2) End iterator (default-constructed `recursive_directory_iterator`). ### Example ``` #include <cstdlib> #include <filesystem> #include <fstream> #include <iostream> namespace fs = std::filesystem; int main() { fs::current_path(fs::temp_directory_path()); fs::create_directories("sandbox/a/b"); std::ofstream("sandbox/file1.txt"); fs::create_symlink("a", "sandbox/syma"); std::cout << "Print dir structure using OS specific command 'tree':\n"; std::system("tree --noreport sandbox"); std::cout << "\nPrint dir structure using directory iterator:\n"; for(auto& p: fs::recursive_directory_iterator("sandbox")) std::cout << p << '\n'; fs::remove_all("sandbox"); } ``` Possible output: ``` Print dir structure using OS specific command 'tree': sandbox ├── a │ └── b ├── file1.txt └── syma -> a Print dir structure using directory iterator: "sandbox/syma" "sandbox/file1.txt" "sandbox/a" "sandbox/a/b" ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3480](https://cplusplus.github.io/LWG/issue3480) | C++17 | `end` took the argument by reference | takes the argument by value | ### See also | | | | --- | --- | | [begin(std::filesystem::directory\_iterator)end(std::filesystem::directory\_iterator)](../directory_iterator/begin "cpp/filesystem/directory iterator/begin") (C++17) | range-based for loop support (function) | cpp std::for_each std::for\_each ============== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class UnaryFunction > UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f ); ``` | (until C++20) | | ``` template< class InputIt, class UnaryFunction > constexpr UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class UnaryFunction2 > void for_each( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryFunction2 f ); ``` | (2) | (since C++17) | 1) Applies the given function object `f` to the result of dereferencing every iterator in the range `[first, last)`, in order. 2) Applies the given function object `f` to the result of dereferencing every iterator in the range `[first, last)` (not necessarily in order). The algorithm is executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. For both overloads, if the iterator type is mutable, `f` may modify the elements of the range through the dereferenced iterator. If `f` returns a result, the result is ignored. Unlike the rest of the parallel algorithms, `for_each` is not allowed to make copies of the elements in the sequence even if they are trivially copyable. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range to apply the function to | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | f | - | function object, to be applied to the result of dereferencing every iterator in the range `[first, last)` The signature of the function should be equivalent to the following: `void fun(const Type &a);` The signature does not need to have `const &`. The type `Type` must be such that an object of type `InputIt` can be dereferenced and then implicitly converted to `Type`. ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`UnaryFunction` must meet the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). Does not have to be [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") | | -`UnaryFunction2` must meet the requirements of [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"). | ### Return value 1) `f` (until C++11) `std::move(f)` (since C++11) 2) (none) ### Complexity Exactly `last` - `first` applications of `f`. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L3858), [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L880) and [MSVC stdlib](https://github.com/microsoft/STL/blob/ff83542af4b683fb2f2dea1423fd6c50fe3e13b0/stl/inc/algorithm#L229). | | | --- | | ``` template<class InputIt, class UnaryFunction> constexpr UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f) { for (; first != last; ++first) { f(*first); } return f; // implicit move since C++11 } ``` | ### Example The following example uses a [lambda function](../language/lambda "cpp/language/lambda") to increment all of the elements of a vector and then uses an overloaded `operator()` in a functor to compute their sum. Note that to compute the sum, it is recommended to use the dedicated algorithm `[std::accumulate](accumulate "cpp/algorithm/accumulate")`. ``` #include <vector> #include <algorithm> #include <iostream> struct Sum { void operator()(int n) { sum += n; } int sum{0}; }; int main() { std::vector<int> nums{3, 4, 2, 8, 15, 267}; auto print = [](const int& n) { std::cout << " " << n; }; std::cout << "before:"; std::for_each(nums.cbegin(), nums.cend(), print); std::cout << '\n'; std::for_each(nums.begin(), nums.end(), [](int &n){ n++; }); // calls Sum::operator() for each number Sum s = std::for_each(nums.begin(), nums.end(), Sum()); std::cout << "after: "; std::for_each(nums.cbegin(), nums.cend(), print); std::cout << '\n'; std::cout << "sum: " << s.sum << '\n'; } ``` Output: ``` before: 3 4 2 8 15 267 after: 4 5 3 9 16 268 sum: 305 ``` ### See also | | | | --- | --- | | [transform](transform "cpp/algorithm/transform") | applies a function to a range of elements, storing results in a destination range (function template) | | [for\_each\_n](for_each_n "cpp/algorithm/for each n") (C++17) | applies a function object to the first n elements of a sequence (function template) | | [ranges::for\_each](ranges/for_each "cpp/algorithm/ranges/for each") (C++20) | applies a function to a range of elements (niebloid) | | [ranges::for\_each\_n](ranges/for_each_n "cpp/algorithm/ranges/for each n") (C++20) | applies a function object to the first n elements of a sequence (niebloid) | | [range-`for` loop](../language/range-for "cpp/language/range-for")(C++11) | executes loop over range |
programming_docs
cpp std::sort std::sort ========= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class RandomIt > void sort( RandomIt first, RandomIt last ); ``` | (until C++20) | | ``` template< class RandomIt > constexpr void sort( RandomIt first, RandomIt last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class RandomIt > void sort( ExecutionPolicy&& policy, RandomIt first, RandomIt last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class RandomIt, class Compare > void sort( RandomIt first, RandomIt last, Compare comp ); ``` | (until C++20) | | ``` template< class RandomIt, class Compare > constexpr void sort( RandomIt first, RandomIt last, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class RandomIt, class Compare > void sort( ExecutionPolicy&& policy, RandomIt first, RandomIt last, Compare comp ); ``` | (4) | (since C++17) | Sorts the elements in the range `[first, last)` in non-descending order. The order of equal elements is not guaranteed to be preserved. A sequence is sorted with respect to a comparator `comp` if for any iterator `it` pointing to the sequence and any non-negative integer `n` such that `it + n` is a valid iterator pointing to an element of the sequence, `comp(*(it + n), *it)` (or `*(it + n) < *it`) evaluates to `false`. 1) Elements are compared using `operator<`. 3) Elements are compared using the given binary comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to sort | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `RandomIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`RandomIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). | | -The type of dereferenced `RandomIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). | | -`Compare` must meet the requirements of [Compare](../named_req/compare "cpp/named req/Compare"). | ### Return value (none). ### Complexity | | | | --- | --- | | O(N·log(N)), where `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` comparisons on average. | (until C++11) | | O(N·log(N)), where `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` comparisons. | (since C++11) | ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L1950) and [libc++](https://github.com/llvm/llvm-project/blob/e7fc254875ca9e82b899d5354fae9b5b779ff485/libcxx/include/__algorithm/sort.h#L264). ### Example ``` #include <algorithm> #include <functional> #include <array> #include <iostream> #include <string_view> int main() { std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; auto print = [&s](std::string_view const rem) { for (auto a : s) { std::cout << a << ' '; } std::cout << ": " << rem << '\n'; }; std::sort(s.begin(), s.end()); print("sorted with the default operator<"); std::sort(s.begin(), s.end(), std::greater<int>()); print("sorted with the standard library compare function object"); struct { bool operator()(int a, int b) const { return a < b; } } customLess; std::sort(s.begin(), s.end(), customLess); print("sorted with a custom function object"); std::sort(s.begin(), s.end(), [](int a, int b) { return a > b; }); print("sorted with a lambda expression"); } ``` Output: ``` 0 1 2 3 4 5 6 7 8 9 : sorted with the default operator< 9 8 7 6 5 4 3 2 1 0 : sorted with the standard library compare function object 0 1 2 3 4 5 6 7 8 9 : sorted with a custom function object 9 8 7 6 5 4 3 2 1 0 : sorted with a lambda expression ``` ### See also | | | | --- | --- | | [partial\_sort](partial_sort "cpp/algorithm/partial sort") | sorts the first N elements of a range (function template) | | [stable\_sort](stable_sort "cpp/algorithm/stable sort") | sorts a range of elements while preserving order between equal elements (function template) | | [ranges::sort](ranges/sort "cpp/algorithm/ranges/sort") (C++20) | sorts a range into ascending order (niebloid) | cpp std::copy_backward std::copy\_backward =================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template< class BidirIt1, class BidirIt2 > BidirIt2 copy_backward( BidirIt1 first, BidirIt1 last, BidirIt2 d_last ); ``` | | (until C++20) | | ``` template< class BidirIt1, class BidirIt2 > constexpr BidirIt2 copy_backward( BidirIt1 first, BidirIt1 last, BidirIt2 d_last ); ``` | | (since C++20) | Copies the elements from the range, defined by `[first, last)`, to another range ending at `d_last`. The elements are copied in reverse order (the last element is copied first), but their relative order is preserved. The behavior is undefined if `d_last` is within `(first, last]`. `[std::copy](copy "cpp/algorithm/copy")` must be used instead of `std::copy_backward` in that case. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of the elements to copy from | | d\_last | - | the end of the destination range | | Type requirements | | -`BidirIt` must meet the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | ### Return value iterator to the last element copied. ### Complexity Exactly `last - first` assignments. ### Notes When copying overlapping ranges, `std::copy` is appropriate when copying to the left (beginning of the destination range is outside the source range) while `std::copy_backward` is appropriate when copying to the right (end of the destination range is outside the source range). ### Possible implementation | | | --- | | ``` template< class BidirIt1, class BidirIt2 > BidirIt2 copy_backward(BidirIt1 first, BidirIt1 last, BidirIt2 d_last) { while (first != last) { *(--d_last) = *(--last); } return d_last; } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> from_vector; for (int i = 0; i < 10; i++) { from_vector.push_back(i); } std::vector<int> to_vector(15); std::copy_backward(from_vector.begin(), from_vector.end(), to_vector.end()); std::cout << "to_vector contains: "; for (auto i: to_vector) { std::cout << i << " "; } } ``` Output: ``` to_vector contains: 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 ``` ### See also | | | | --- | --- | | [copycopy\_if](copy "cpp/algorithm/copy") (C++11) | copies a range of elements to a new location (function template) | | [ranges::copy\_backward](ranges/copy_backward "cpp/algorithm/ranges/copy backward") (C++20) | copies a range of elements in backwards order (niebloid) | cpp std::fill_n std::fill\_n ============ | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class OutputIt, class Size, class T > void fill_n( OutputIt first, Size count, const T& value ); ``` | (until C++11) | | ``` template< class OutputIt, class Size, class T > OutputIt fill_n( OutputIt first, Size count, const T& value ); ``` | (since C++11) (until C++20) | | ``` template< class OutputIt, class Size, class T > constexpr OutputIt fill_n( OutputIt first, Size count, const T& value ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class Size, class T > ForwardIt fill_n( ExecutionPolicy&& policy, ForwardIt first, Size count, const T& value ); ``` | (2) | (since C++17) | 1) Assigns the given `value` to the first `count` elements in the range beginning at `first` if `count > 0`. Does nothing otherwise. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the range of elements to modify | | count | - | number of elements to modify | | value | - | the value to be assigned | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | Type requirements | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value | | | | --- | --- | | (none) | (until C++11) | | Iterator one past the last element assigned if `count > 0`, `first` otherwise. | (since C++11) | ### Complexity Exactly `count` assignments, for `count > 0`. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | | | --- | | ``` template<class OutputIt, class Size, class T> OutputIt fill_n(OutputIt first, Size count, const T& value) { for (Size i = 0; i < count; i++) { *first++ = value; } return first; } ``` | ### Example The following code uses `fill_n()` to assign -1 to the first half of a vector of integers: ``` #include <algorithm> #include <vector> #include <iostream> #include <iterator> int main() { std::vector<int> v1{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::fill_n(v1.begin(), 5, -1); std::copy(begin(v1), end(v1), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; } ``` Output: ``` -1 -1 -1 -1 -1 5 6 7 8 9 ``` ### See also | | | | --- | --- | | [fill](fill "cpp/algorithm/fill") | copy-assigns the given value to every element in a range (function template) | | [ranges::fill\_n](ranges/fill_n "cpp/algorithm/ranges/fill n") (C++20) | assigns a value to a number of elements (niebloid) | cpp std::partition_point std::partition\_point ===================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template< class ForwardIt, class UnaryPredicate > ForwardIt partition_point( ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | | (since C++11) (until C++20) | | ``` template< class ForwardIt, class UnaryPredicate > constexpr ForwardIt partition_point( ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | | (since C++20) | Examines the partitioned (as if by `[std::partition](partition "cpp/algorithm/partition")`) range `[first, last)` and locates the end of the first partition, that is, the first element that does not satisfy `p` or `last` if all elements satisfy `p`. ### Parameters | | | | | --- | --- | --- | | first, last | - | the partitioned range of elements to examine | | p | - | unary predicate which returns ​`true` for the elements found in the beginning of the range. The expression `p(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `VT`, where `VT` is the value type of `ForwardIt`, regardless of [value category](../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `VT&`is not allowed, nor is `VT` unless for `VT` a move is equivalent to a copy (since C++11). ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`UnaryPredicate` must meet the requirements of [Predicate](../named_req/predicate "cpp/named req/Predicate"). | ### Return value The iterator past the end of the first partition within `[first, last)` or `last` if all elements satisfy `p`. ### Complexity Given `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`, performs O(log N) applications of the predicate `p`. However, for non-[LegacyRandomAccessIterators](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), the number of iterator increments is O(N). ### Notes This algorithm is a more general form of `[std::lower\_bound](lower_bound "cpp/algorithm/lower bound")`, which can be expressed in terms of `std::partition_point` with the predicate `[&](auto const& e) { return e < value; });`. ### Example ``` #include <algorithm> #include <array> #include <iostream> #include <iterator> auto print_seq = [](auto rem, auto first, auto last) { for (std::cout << rem; first != last; std::cout << *first++ << ' ') {} std::cout << '\n'; }; int main() { std::array v = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto is_even = [](int i){ return i % 2 == 0; }; std::partition(v.begin(), v.end(), is_even); print_seq("After partitioning, v: ", v.cbegin(), v.cend()); const auto pp = std::partition_point(v.cbegin(), v.cend(), is_even); const auto i = std::distance(v.cbegin(), pp); std::cout << "Partition point is at " << i << "; v[" << i << "] = " << *pp << '\n'; print_seq("First partition (all even elements): ", v.cbegin(), pp); print_seq("Second partition (all odd elements): ", pp, v.cend()); } ``` Possible output: ``` After partitioning, v: 8 2 6 4 5 3 7 1 9 Partition point is at 4; v[4] = 5 First partition (all even elements): 8 2 6 4 Second partition (all odd elements): 5 3 7 1 9 ``` ### See also | | | | --- | --- | | [findfind\_iffind\_if\_not](find "cpp/algorithm/find") (C++11) | finds the first element satisfying specific criteria (function template) | | [is\_sorted](is_sorted "cpp/algorithm/is sorted") (C++11) | checks whether a range is sorted into ascending order (function template) | | [lower\_bound](lower_bound "cpp/algorithm/lower bound") | returns an iterator to the first element *not less* than the given value (function template) | | [ranges::partition\_point](ranges/partition_point "cpp/algorithm/ranges/partition point") (C++20) | locates the partition point of a partitioned range (niebloid) | cpp std::copy_n std::copy\_n ============ | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class Size, class OutputIt > OutputIt copy_n( InputIt first, Size count, OutputIt result ); ``` | (since C++11) (until C++20) | | ``` template< class InputIt, class Size, class OutputIt > constexpr OutputIt copy_n( InputIt first, Size count, OutputIt result ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class Size, class ForwardIt2 > ForwardIt2 copy_n( ExecutionPolicy&& policy, ForwardIt1 first, Size count, ForwardIt2 result ); ``` | (2) | (since C++17) | 1) Copies exactly `count` values from the range beginning at `first` to the range beginning at `result`. Formally, for each integer `0 ≤ i < count`, performs `*(result + i) = *(first + i)`. Overlap of ranges is formally permitted, but leads to unpredictable ordering of the results. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the range of elements to copy from | | count | - | number of the elements to copy | | result | - | the beginning of the destination range | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value Iterator in the destination range, pointing past the last element copied if `count>0` or `result` otherwise. ### Complexity Zero assignments if `count < 0`; `count` assignments otherwise. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | | | --- | | ``` template< class InputIt, class Size, class OutputIt> OutputIt copy_n(InputIt first, Size count, OutputIt result) { if (count > 0) { *result++ = *first; for (Size i = 1; i < count; ++i) { *result++ = *++first; } } return result; } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <string> #include <vector> int main() { std::string in = "1234567890"; std::string out; std::copy_n(in.begin(), 4, std::back_inserter(out)); std::cout << out << '\n'; std::vector<int> v_in(128); std::iota(v_in.begin(), v_in.end(), 1); std::vector<int> v_out(v_in.size()); std::copy_n(v_in.cbegin(), 100, v_out.begin()); std::cout << std::accumulate(v_out.begin(), v_out.end(), 0) << '\n'; } ``` Output: ``` 1234 5050 ``` ### See also | | | | --- | --- | | [copycopy\_if](copy "cpp/algorithm/copy") (C++11) | copies a range of elements to a new location (function template) | | [ranges::copy\_n](ranges/copy_n "cpp/algorithm/ranges/copy n") (C++20) | copies a number of elements to a new location (niebloid) |
programming_docs
cpp std::nth_element std::nth\_element ================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class RandomIt > void nth_element( RandomIt first, RandomIt nth, RandomIt last ); ``` | (until C++20) | | ``` template< class RandomIt > constexpr void nth_element( RandomIt first, RandomIt nth, RandomIt last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class RandomIt > void nth_element( ExecutionPolicy&& policy, RandomIt first, RandomIt nth, RandomIt last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class RandomIt, class Compare > void nth_element( RandomIt first, RandomIt nth, RandomIt last, Compare comp ); ``` | (until C++20) | | ``` template< class RandomIt, class Compare > constexpr void nth_element( RandomIt first, RandomIt nth, RandomIt last, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class RandomIt, class Compare > void nth_element( ExecutionPolicy&& policy, RandomIt first, RandomIt nth, RandomIt last, Compare comp ); ``` | (4) | (since C++17) | `nth_element` is a partial sorting algorithm that rearranges elements in `[first, last)` such that: * The element pointed at by `nth` is changed to whatever element would occur in that position if `[first, last)` were sorted. * All of the elements before this new `nth` element are less than or equal to the elements after the new `nth` element. More formally, `nth_element` partially sorts the range `[first, last)` in ascending order so that the condition `!(*j < *i)` (for (1-2), or `comp(*j, *i) == false` for (3-4)) is met for any `i` in the range `[first, nth)` and for any `j` in the range `[nth, last)`. The element placed in the `nth` position is exactly the element that would occur in this position if the range was fully sorted. `nth` may be the end iterator, in this case the function has no effect. 1) Elements are compared using `operator<`. 3) Elements are compared using the given binary comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | random access iterators defining the range sort | | nth | - | random access iterator defining the sort partition point | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `RandomIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`RandomIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). | | -The type of dereferenced `RandomIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). | ### Return value (none). ### Complexity 1,3) Linear in `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` on average. 2,4) O(N) applications of the predicate, and O(N log N) swaps, where N = last - first. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes The algorithm used is typically [introselect](https://en.wikipedia.org/wiki/Introselect "enwiki:Introselect") although other [selection algorithms](https://en.wikipedia.org/wiki/Selection_algorithm "enwiki:Selection algorithm") with suitable average-case complexity are allowed. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L4718) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L5109). ### Example ``` #include <vector> #include <cassert> #include <numeric> #include <iostream> #include <algorithm> #include <functional> void printVec(const std::vector<int> &vec) { std::cout << "v= {"; for (int i : vec) std::cout << i << ", "; std::cout << "}\n"; } int main() { std::vector<int> v{5, 10, 6, 4, 3, 2, 6, 7, 9, 3}; printVec(v); auto m = v.begin() + v.size()/2; std::nth_element(v.begin(), m, v.end()); std::cout << "\nThe median is " << v[v.size()/2] << '\n'; // The consequence of the inequality of elements before/after the Nth one: assert(std::accumulate(v.begin(), m, 0) < std::accumulate(m, v.end(), 0)); printVec(v); // Note: comp function changed std::nth_element(v.begin(), v.begin()+1, v.end(), std::greater{}); std::cout << "\nThe second largest element is " << v[1] << '\n'; std::cout << "The largest element is " << v[0] << '\n'; printVec(v); } ``` Possible output: ``` v= {5, 10, 6, 4, 3, 2, 6, 7, 9, 3, } The median is 6 v= {3, 2, 3, 4, 5, 6, 10, 7, 9, 6, } The second largest element is 9 The largest element is 10 v= {10, 9, 6, 7, 6, 3, 5, 4, 3, 2, } ``` ### See also | | | | --- | --- | | [max\_element](max_element "cpp/algorithm/max element") | returns the largest element in a range (function template) | | [min\_element](min_element "cpp/algorithm/min element") | returns the smallest element in a range (function template) | | [partial\_sort\_copy](partial_sort_copy "cpp/algorithm/partial sort copy") | copies and partially sorts a range of elements (function template) | | [stable\_sort](stable_sort "cpp/algorithm/stable sort") | sorts a range of elements while preserving order between equal elements (function template) | | [sort](sort "cpp/algorithm/sort") | sorts a range into ascending order (function template) | | [ranges::nth\_element](ranges/nth_element "cpp/algorithm/ranges/nth element") (C++20) | partially sorts the given range making sure that it is partitioned by the given element (niebloid) | cpp std::fill std::fill ========= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt, class T > void fill( ForwardIt first, ForwardIt last, const T& value ); ``` | (until C++20) | | ``` template< class ForwardIt, class T > constexpr void fill( ForwardIt first, ForwardIt last, const T& value ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class T > void fill( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, const T& value ); ``` | (2) | (since C++17) | 1) Assigns the given `value` to the elements in the range `[first, last)`. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to modify | | value | - | the value to be assigned | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value (none). ### Complexity Exactly `last - first` assignments. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | | | --- | | ``` template< class ForwardIt, class T > void fill(ForwardIt first, ForwardIt last, const T& value) { for (; first != last; ++first) { *first = value; } } ``` | ### Example The following code uses `fill()` to set all of the elements of a `vector` of `int`s to -1: ``` #include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::fill(v.begin(), v.end(), -1); for (auto elem : v) { std::cout << elem << " "; } std::cout << "\n"; } ``` Output: ``` -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 ``` ### See also | | | | --- | --- | | [fill\_n](fill_n "cpp/algorithm/fill n") | copy-assigns the given value to N elements in a range (function template) | | [copycopy\_if](copy "cpp/algorithm/copy") (C++11) | copies a range of elements to a new location (function template) | | [generate](generate "cpp/algorithm/generate") | assigns the results of successive function calls to every element in a range (function template) | | [transform](transform "cpp/algorithm/transform") | applies a function to a range of elements, storing results in a destination range (function template) | | [ranges::fill](ranges/fill "cpp/algorithm/ranges/fill") (C++20) | assigns a range of elements a certain value (niebloid) | cpp std::swap_ranges std::swap\_ranges ================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt1, class ForwardIt2 > ForwardIt2 swap_ranges( ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2 ); ``` | (until C++20) | | ``` template< class ForwardIt1, class ForwardIt2 > constexpr ForwardIt2 swap_ranges( ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2 ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > ForwardIt2 swap_ranges( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2 ); ``` | (2) | (since C++17) | 1) Exchanges elements between range `[first1, last1)` and another range starting at `first2`. *Precondition*: the two ranges `[first1, last1)` and `[first2, last2)` do not overlap, where `last2 = [std::next](http://en.cppreference.com/w/cpp/iterator/next)(first2, [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1))`. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first range of elements to swap | | first2 | - | beginning of the second range of elements to swap | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | Type requirements | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -The types of dereferenced `ForwardIt1` and `ForwardIt2` must meet the requirements of [Swappable](../named_req/swappable "cpp/named req/Swappable") | ### Return value Iterator to the element past the last element exchanged in the range beginning with `first2`. ### Complexity linear in the distance between `first1` and `last1`. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes Implementations (e.g. [MSVC STL](https://github.com/microsoft/STL/blob/main/stl/src/vector_algorithms.cpp)) may enable vectorization when the iterator type satisfies [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") and swapping its value type calls neither non-trivial special member function nor [ADL](../language/adl "cpp/language/adl")-found `swap`. ### Possible implementation | | | --- | | ``` template<class ForwardIt1, class ForwardIt2> constexpr ForwardIt2 swap_ranges(ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2) { while (first1 != last1) { std::iter_swap(first1++, first2++); } return first2; } ``` | ### Example Demonstrates swapping of subranges from different containers. ``` #include <list> #include <vector> #include <iostream> #include <algorithm> auto print = [](auto comment, auto const& seq) { std::cout << comment; for (const auto& e : seq) { std::cout << e << ' '; } std::cout << '\n'; }; int main() { std::vector<char> v = {'a', 'b', 'c', 'd', 'e'}; std::list<char> l = {'1', '2', '3', '4', '5'}; print("Before swap_ranges:\n" "v: ", v); print("l: ", l); std::swap_ranges(v.begin(), v.begin()+3, l.begin()); print("After swap_ranges:\n" "v: ", v); print("l: ", l); } ``` Output: ``` Before swap_ranges: v: a b c d e l: 1 2 3 4 5 After swap_ranges: v: 1 2 3 d e l: a b c 4 5 ``` ### See also | | | | --- | --- | | [iter\_swap](iter_swap "cpp/algorithm/iter swap") | swaps the elements pointed to by two iterators (function template) | | [swap](swap "cpp/algorithm/swap") | swaps the values of two objects (function template) | | [ranges::swap\_ranges](ranges/swap_ranges "cpp/algorithm/ranges/swap ranges") (C++20) | swaps two ranges of elements (niebloid) | cpp std::mismatch std::mismatch ============= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt1, class InputIt2 > std::pair<InputIt1,InputIt2> mismatch( InputIt1 first1, InputIt1 last1, InputIt2 first2 ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2 > constexpr std::pair<InputIt1,InputIt2> mismatch( InputIt1 first1, InputIt1 last1, InputIt2 first2 ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > std::pair<ForwardIt1,ForwardIt2> mismatch( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2 ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt1, class InputIt2, class BinaryPredicate > std::pair<InputIt1,InputIt2> mismatch( InputIt1 first1, InputIt1 last1, InputIt2 first2, BinaryPredicate p ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class BinaryPredicate > constexpr std::pair<InputIt1,InputIt2> mismatch( InputIt1 first1, InputIt1 last1, InputIt2 first2, BinaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryPredicate > std::pair<ForwardIt1,ForwardIt2> mismatch( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, BinaryPredicate p ); ``` | (4) | (since C++17) | | | (5) | | | ``` template< class InputIt1, class InputIt2 > std::pair<InputIt1,InputIt2> mismatch( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2 ); ``` | (since C++14) (until C++20) | | ``` template< class InputIt1, class InputIt2 > constexpr std::pair<InputIt1,InputIt2> mismatch( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2 ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > std::pair<ForwardIt1,ForwardIt2> mismatch( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2 ); ``` | (6) | (since C++17) | | | (7) | | | ``` template< class InputIt1, class InputIt2, class BinaryPredicate > std::pair<InputIt1,InputIt2> mismatch( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, BinaryPredicate p ); ``` | (since C++14) (until C++20) | | ``` template< class InputIt1, class InputIt2, class BinaryPredicate > constexpr std::pair<InputIt1,InputIt2> mismatch( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, BinaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryPredicate > std::pair<ForwardIt1,ForwardIt2> mismatch( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, BinaryPredicate p ); ``` | (8) | (since C++17) | Returns the first mismatching pair of elements from two ranges: one defined by `[first1, last1)` and another defined by `[first2,last2)`. If `last2` is not provided (overloads (1-4)), it denotes `first2 + (last1 - first1)`. 1,5) Elements are compared using `operator==`. 3,7) Elements are compared using the given binary predicate `p`. 2,4,6,8) Same as (1,3,5,7), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first range of the elements | | first2, last2 | - | the second range of the elements | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | binary predicate which returns ​`true` if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that objects of types `InputIt1` and `InputIt2` can be dereferenced and then implicitly converted to `Type1` and `Type2` respectively. ​ | | Type requirements | | -`InputIt1` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`InputIt2` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt1` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`BinaryPredicate` must meet the requirements of [BinaryPredicate](../named_req/binarypredicate "cpp/named req/BinaryPredicate"). | ### Return value `[std::pair](../utility/pair "cpp/utility/pair")` with iterators to the first two non-equal elements. | | | | --- | --- | | If no mismatches are found when the comparison reaches `last1`, the pair holds `last1` and the corresponding iterator from the second range. The behavior is undefined if the second range is shorter than the first range. | (until C++14) | | If no mismatches are found when the comparison reaches `last1` or `last2`, whichever happens first, the pair holds the end iterator and the corresponding iterator from the other range. | (since C++14) | ### Complexity 1-4) At most `last1` - `first1` applications of `operator==` or the predicate `p` 5-8) At most min(`last1` - `first1`, `last2` - `first2`) applications of `operator==` or the predicate `p`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class InputIt1, class InputIt2> std::pair<InputIt1, InputIt2> mismatch(InputIt1 first1, InputIt1 last1, InputIt2 first2) { while (first1 != last1 && *first1 == *first2) { ++first1, ++first2; } return std::make_pair(first1, first2); } ``` | | Second version | | ``` template<class InputIt1, class InputIt2, class BinaryPredicate> std::pair<InputIt1, InputIt2> mismatch(InputIt1 first1, InputIt1 last1, InputIt2 first2, BinaryPredicate p) { while (first1 != last1 && p(*first1, *first2)) { ++first1, ++first2; } return std::make_pair(first1, first2); } ``` | | Third version | | ``` template<class InputIt1, class InputIt2> std::pair<InputIt1, InputIt2> mismatch(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2) { while (first1 != last1 && first2 != last2 && *first1 == *first2) { ++first1, ++first2; } return std::make_pair(first1, first2); } ``` | | Fourth version | | ``` template<class InputIt1, class InputIt2, class BinaryPredicate> std::pair<InputIt1, InputIt2> mismatch(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, BinaryPredicate p) { while (first1 != last1 && first2 != last2 && p(*first1, *first2)) { ++first1, ++first2; } return std::make_pair(first1, first2); } ``` | ### Example This program determines the longest substring that is simultaneously found at the very beginning of the given string and at the very end of it, in reverse order (possibly overlapping). ``` #include <iostream> #include <string> #include <algorithm> std::string mirror_ends(const std::string& in) { return std::string(in.begin(), std::mismatch(in.begin(), in.end(), in.rbegin()).first); } int main() { std::cout << mirror_ends("abXYZba") << '\n' << mirror_ends("abca") << '\n' << mirror_ends("aba") << '\n'; } ``` Output: ``` ab a aba ``` ### See also | | | | --- | --- | | [equal](equal "cpp/algorithm/equal") | determines if two sets of elements are the same (function template) | | [findfind\_iffind\_if\_not](find "cpp/algorithm/find") (C++11) | finds the first element satisfying specific criteria (function template) | | [lexicographical\_compare](lexicographical_compare "cpp/algorithm/lexicographical compare") | returns true if one range is lexicographically less than another (function template) | | [search](search "cpp/algorithm/search") | searches for a range of elements (function template) | | [ranges::mismatch](ranges/mismatch "cpp/algorithm/ranges/mismatch") (C++20) | finds the first position where two ranges differ (niebloid) |
programming_docs
cpp std::inplace_merge std::inplace\_merge =================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template< class BidirIt > void inplace_merge( BidirIt first, BidirIt middle, BidirIt last ); ``` | (1) | | | ``` template< class ExecutionPolicy, class BidirIt > void inplace_merge( ExecutionPolicy&& policy, BidirIt first, BidirIt middle, BidirIt last ); ``` | (2) | (since C++17) | | ``` template< class BidirIt, class Compare> void inplace_merge( BidirIt first, BidirIt middle, BidirIt last, Compare comp ); ``` | (3) | | | ``` template< class ExecutionPolicy, class BidirIt, class Compare> void inplace_merge( ExecutionPolicy&& policy, BidirIt first, BidirIt middle, BidirIt last, Compare comp ); ``` | (4) | (since C++17) | Merges two consecutive *sorted* ranges `[first, middle)` and `[middle, last)` into one *sorted* range `[first, last)`. A sequence `[first, last)` is said to be *sorted* with respect to a comparator `comp` if for any iterator `it` pointing to the sequence and any non-negative integer `n` such that `it + n` is a valid iterator pointing to an element of the sequence, `comp(*(it + n), *it)` evaluates to `false`. This merge is *stable*, which means that for equivalent elements in the original two ranges, the elements from the first range (preserving their original order) precede the elements from the second range (preserving their original order). 1) Elements are compared using `operator<` and the ranges must be sorted with respect to the same. 3) Elements are compared using the given binary comparison function `comp` and the ranges must be sorted with respect to the same. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the first sorted range | | middle | - | the end of the first sorted range and the beginning of the second | | last | - | the end of the second sorted range | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `BidirIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`BidirIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | | -The type of dereferenced `BidirIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). | ### Return value (none). ### Complexity Given `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`}, 1,3) Exactly `N-1` comparisons if enough additional memory is available. If the memory is insufficient, `O(N log N)` comparisons. 2,4) `O(N log N)` comparisons. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes This function attempts to allocate a temporary buffer. If the allocation fails, the less efficient algorithm is chosen. ### Possible implementation See the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L2508) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L4452). ### Example The following code is an implementation of merge sort. ``` #include <vector> #include <iostream> #include <algorithm> template<class Iter> void merge_sort(Iter first, Iter last) { if (last - first > 1) { Iter middle = first + (last - first) / 2; merge_sort(first, middle); merge_sort(middle, last); std::inplace_merge(first, middle, last); } } int main() { std::vector<int> v{8, 2, -2, 0, 11, 11, 1, 7, 3}; merge_sort(v.begin(), v.end()); for(auto n : v) { std::cout << n << ' '; } std::cout << '\n'; } ``` Output: ``` -2 0 1 2 3 7 8 11 11 ``` ### See also | | | | --- | --- | | [merge](merge "cpp/algorithm/merge") | merges two sorted ranges (function template) | | [sort](sort "cpp/algorithm/sort") | sorts a range into ascending order (function template) | | [stable\_sort](stable_sort "cpp/algorithm/stable sort") | sorts a range of elements while preserving order between equal elements (function template) | | [ranges::inplace\_merge](ranges/inplace_merge "cpp/algorithm/ranges/inplace merge") (C++20) | merges two ordered ranges in-place (niebloid) | cpp std::move_backward std::move\_backward =================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template< class BidirIt1, class BidirIt2 > BidirIt2 move_backward( BidirIt1 first, BidirIt1 last, BidirIt2 d_last ); ``` | | (since C++11) (until C++20) | | ``` template< class BidirIt1, class BidirIt2 > constexpr BidirIt2 move_backward( BidirIt1 first, BidirIt1 last, BidirIt2 d_last ); ``` | | (since C++20) | Moves the elements from the range `[first, last)`, to another range ending at `d_last`. The elements are moved in reverse order (the last element is moved first), but their relative order is preserved. The behavior is undefined if `d_last` is within `(first, last]`. [std::move](move "cpp/algorithm/move") must be used instead of `std::move_backward` in that case. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of the elements to move | | d\_last | - | end of the destination range | | Type requirements | | -`BidirIt1, BidirIt2` must meet the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | ### Return value Iterator in the destination range, pointing at the last element moved. ### Complexity Exactly `last - first` move assignments. ### Possible implementation | | | --- | | ``` template< class BidirIt1, class BidirIt2 > BidirIt2 move_backward(BidirIt1 first, BidirIt1 last, BidirIt2 d_last) { while (first != last) { *(--d_last) = std::move(*(--last)); } return d_last; } ``` | ### Notes When moving overlapping ranges, `std::move` is appropriate when moving to the left (beginning of the destination range is outside the source range) while `std::move_backward` is appropriate when moving to the right (end of the destination range is outside the source range). ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <string> #include <string_view> #include <vector> using container = std::vector<std::string>; void print(std::string_view comment, const container& src, const container& dst = {}) { auto prn = [](std::string_view name, const container& cont) { std::cout << name; for (const auto &s: cont) { std::cout << (s.empty() ? "∙" : s.data()) << ' '; } std::cout << '\n'; }; std::cout << comment << '\n'; prn("src: ", src); if (dst.empty()) return; prn("dst: ", dst); } int main() { container src{"foo", "bar", "baz"}; container dst{"qux", "quux", "quuz", "corge"}; print("Non-overlapping case; before move_backward:", src, dst); std::move_backward(src.begin(), src.end(), dst.end()); print("After:", src, dst); src = {"snap", "crackle", "pop", "lock", "drop"}; print("Overlapping case; before move_backward:", src); std::move_backward(src.begin(), std::next(src.begin(), 3), src.end()); print("After:", src); } ``` Output: ``` Non-overlapping case; before move_backward: src: foo bar baz dst: qux quux quuz corge After: src: ∙ ∙ ∙ dst: qux foo bar baz Overlapping case; before move_backward: src: snap crackle pop lock drop After: src: ∙ ∙ snap crackle pop ``` ### See also | | | | --- | --- | | [move](move "cpp/algorithm/move") (C++11) | moves a range of elements to a new location (function template) | | [ranges::move\_backward](ranges/move_backward "cpp/algorithm/ranges/move backward") (C++20) | moves a range of elements to a new location in backwards order (niebloid) | cpp std::execution::seq, std::execution::par, std::execution::par_unseq, std::execution::unseq std::execution::seq, std::execution::par, std::execution::par\_unseq, std::execution::unseq =========================================================================================== | Defined in header `[<execution>](../header/execution "cpp/header/execution")` | | | | --- | --- | --- | | ``` inline constexpr std::execution::sequenced_policy seq { /* unspecified */ }; ``` | | (since C++17) | | ``` inline constexpr std::execution::parallel_policy par { /* unspecified */ }; ``` | | (since C++17) | | ``` inline constexpr std::execution::parallel_unsequenced_policy par_unseq { /* unspecified */ }; ``` | | (since C++17) | | ``` inline constexpr std::execution::unsequenced_policy unseq { /* unspecified */ }; ``` | | (since C++20) | `std::execution::seq`, `std::execution::par`, `std::execution::par_unseq`, and `std::execution::unseq` are instances of the execution policy types `[std::execution::sequenced\_policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t")`, `[std::execution::parallel\_policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t")`, `[std::execution::parallel\_unsequenced\_policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t")`, and `[std::execution::unsequenced\_policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t")` respectively. They are used to specify the execution policy of parallel algorithms - i.e., the kinds of parallelism allowed. Additional execution policies may be provided by a standard library implementation (possible future additions may include `std::parallel::cuda` and `std::parallel::opencl`). ### See also | | | | --- | --- | | [sequenced\_policyparallel\_policyparallel\_unsequenced\_policyunsequenced\_policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") (C++17)(C++17)(C++17)(C++20) | execution policy types (class) | cpp std::pop_heap std::pop\_heap ============== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class RandomIt > void pop_heap( RandomIt first, RandomIt last ); ``` | (until C++20) | | ``` template< class RandomIt > constexpr void pop_heap( RandomIt first, RandomIt last ); ``` | (since C++20) | | | (2) | | | ``` template< class RandomIt, class Compare > void pop_heap( RandomIt first, RandomIt last, Compare comp ); ``` | (until C++20) | | ``` template< class RandomIt, class Compare > constexpr void pop_heap( RandomIt first, RandomIt last, Compare comp ); ``` | (since C++20) | Swaps the value in the position `first` and the value in the position `last-1` and makes the subrange `[first, last-1)` into a *heap*. This has the effect of removing the first element from the heap defined by the range `[first, last)`. The first version of the function uses `operator<` to compare the elements, which makes the heap a [*max heap*](https://en.wikipedia.org/wiki/Binary_heap "enwiki:Binary heap"). The second uses the given comparison function `comp`. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements defining the valid nonempty heap to modify | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `RandomIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`RandomIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). | | -The type of dereferenced `RandomIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). | ### Return value (none). ### Complexity At most *2×log(N)* comparisons where `N=[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`. ### Notes A *max heap* is a range of elements `[f,l)` that has the following properties: * With `N = l-f`, for all `0 < i < N`, `f[(i-1)/2]` does not compare less than `f[i]`. * A new element can be added using `[std::push\_heap](push_heap "cpp/algorithm/push heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. * The first element can be removed using `std::pop_heap`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. ### Example ``` #include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> v { 3, 1, 4, 1, 5, 9 }; std::make_heap(v.begin(), v.end()); std::cout << "v: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; std::pop_heap(v.begin(), v.end()); // moves the largest to the end std::cout << "after pop_heap: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; int largest = v.back(); v.pop_back(); // actually removes the largest element std::cout << "largest element: " << largest << '\n'; std::cout << "heap without largest: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; } ``` Output: ``` v: 9 5 4 1 1 3 after pop_heap: 5 3 4 1 1 9 largest element: 9 heap without largest: 5 3 4 1 1 ``` ### See also | | | | --- | --- | | [push\_heap](push_heap "cpp/algorithm/push heap") | adds an element to a max heap (function template) | | [is\_heap](is_heap "cpp/algorithm/is heap") (C++11) | checks if the given range is a max heap (function template) | | [is\_heap\_until](is_heap_until "cpp/algorithm/is heap until") (C++11) | finds the largest subrange that is a max heap (function template) | | [make\_heap](make_heap "cpp/algorithm/make heap") | creates a max heap out of a range of elements (function template) | | [sort\_heap](sort_heap "cpp/algorithm/sort heap") | turns a max heap into a range of elements sorted in ascending order (function template) | | [ranges::pop\_heap](ranges/pop_heap "cpp/algorithm/ranges/pop heap") (C++20) | removes the largest element from a max heap (niebloid) | cpp std::merge std::merge ========== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt1, class InputIt2, class OutputIt > OutputIt merge( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class OutputIt > constexpr OutputIt merge( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class ForwardIt3 > ForwardIt3 merge( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, ForwardIt3 d_first ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt1, class InputIt2, class OutputIt, class Compare > OutputIt merge( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class OutputIt, class Compare > constexpr OutputIt merge( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class ForwardIt3, class Compare> ForwardIt3 merge( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, ForwardIt3 d_first, Compare comp ); ``` | (4) | (since C++17) | Merges two *sorted* ranges `[first1, last1)` and `[first2, last2)` into one *sorted* range beginning at `d_first`. A sequence is said to be *sorted* with respect to a comparator `comp` if for any iterator `it` pointing to the sequence and any non-negative integer `n` such that `it + n` is a valid iterator pointing to an element of the sequence, `comp(*(it + n), *it)` evaluates to `false`. 1) Elements are compared using `operator<`. 3) Elements are compared using the given binary comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. This merge function is *stable*, which means that for equivalent elements in the original two ranges, the elements from the first range (preserving their original order) precede the elements from the second range (preserving their original order). The behavior is undefined if the destination range overlaps either of the input ranges (the input ranges may overlap each other). ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first range of elements to merge | | first2, last2 | - | the second range of elements to merge | | d\_first | - | the beginning of the destination range | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that objects of types `InputIt1` and `InputIt2` can be dereferenced and then implicitly converted to both `Type1` and `Type2`. ​ | | Type requirements | | -`InputIt1, InputIt2` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt1, ForwardIt2, ForwardIt3` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | ### Return value An output iterator to element past the last element copied. ### Complexity 1,3) At most `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1) + [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first2, last2) - 1` comparisons. 2,4) `O([std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1) + [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first2, last2))` ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes This algorithm performs a similar task as `[std::set\_union](http://en.cppreference.com/w/cpp/algorithm/set_union)` does. Both consume two sorted input ranges and produce a sorted output with elements from both inputs. The difference between these two algorithms is with handling values from both input ranges which compare equivalent (see notes on [LessThanComparable](../named_req/lessthancomparable "cpp/named req/LessThanComparable")). If any equivalent values appeared `n` times in the first range and `m` times in the second, `std::merge` would output all `n+m` occurrences whereas `std::set_union` would output `[std::max](http://en.cppreference.com/w/cpp/algorithm/max)(n, m)` ones only. So `std::merge` outputs exactly `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1) + [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first2, last2)` values and `std::set_union` may produce fewer. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L4856) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L4348). | First version | | --- | | ``` template<class InputIt1, class InputIt2, class OutputIt> OutputIt merge(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first) { for (; first1 != last1; ++d_first) { if (first2 == last2) { return std::copy(first1, last1, d_first); } if (*first2 < *first1) { *d_first = *first2; ++first2; } else { *d_first = *first1; ++first1; } } return std::copy(first2, last2, d_first); } ``` | | Second version | | ``` template<class InputIt1, class InputIt2, class OutputIt, class Compare> OutputIt merge(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp) { for (; first1 != last1; ++d_first) { if (first2 == last2) { return std::copy(first1, last1, d_first); } if (comp(*first2, *first1)) { *d_first = *first2; ++first2; } else { *d_first = *first1; ++first1; } } return std::copy(first2, last2, d_first); } ``` | ### Example ``` #include <iostream> #include <iterator> #include <algorithm> #include <vector> #include <random> #include <functional> auto print = [](auto const rem, auto const& v) { std::cout << rem; std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; }; int main() { // fill the vectors with random numbers std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<> dis(0, 9); std::vector<int> v1(10), v2(10); std::generate(v1.begin(), v1.end(), std::bind(dis, std::ref(mt))); std::generate(v2.begin(), v2.end(), std::bind(dis, std::ref(mt))); print("Originally:\nv1: ", v1); print("v2: ", v2); std::sort(v1.begin(), v1.end()); std::sort(v2.begin(), v2.end()); print("After sorting:\nv1: ", v1); print("v2: ", v2); // merge std::vector<int> dst; std::merge(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(dst)); print("After merging:\ndst: ", dst); } ``` Possible output: ``` Originally: v1: 2 6 5 7 4 2 2 6 7 0 v2: 8 3 2 5 0 1 9 6 5 0 After sorting: v1: 0 2 2 2 4 5 6 6 7 7 v2: 0 0 1 2 3 5 5 6 8 9 After merging: dst: 0 0 0 1 2 2 2 2 3 4 5 5 5 6 6 6 7 7 8 9 ``` ### See also | | | | --- | --- | | [inplace\_merge](inplace_merge "cpp/algorithm/inplace merge") | merges two ordered ranges in-place (function template) | | [is\_sorted](is_sorted "cpp/algorithm/is sorted") (C++11) | checks whether a range is sorted into ascending order (function template) | | [set\_union](set_union "cpp/algorithm/set union") | computes the union of two sets (function template) | | [sort](sort "cpp/algorithm/sort") | sorts a range into ascending order (function template) | | [stable\_sort](stable_sort "cpp/algorithm/stable sort") | sorts a range of elements while preserving order between equal elements (function template) | | [ranges::merge](ranges/merge "cpp/algorithm/ranges/merge") (C++20) | merges two sorted ranges (niebloid) |
programming_docs
cpp std::lower_bound std::lower\_bound ================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt, class T > ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value ); ``` | (until C++20) | | ``` template< class ForwardIt, class T > constexpr ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value ); ``` | (since C++20) | | | (2) | | | ``` template< class ForwardIt, class T, class Compare > ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value, Compare comp ); ``` | (until C++20) | | ``` template< class ForwardIt, class T, class Compare > constexpr ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value, Compare comp ); ``` | (since C++20) | Returns an iterator pointing to the first element in the range `[first, last)` that does not satisfy `element < value` (or `comp(element, value)`), (i.e. greater or equal to), or `last` if no such element is found. The range `[first, last)` must be partitioned with respect to the expression `element < value` (or `comp(element, value)`), i.e., all elements for which the expression is `true` must precede all elements for which the expression is `false`. A fully-sorted range meets this criterion. The first version uses `operator<` to compare the elements, the second version uses the given comparison function `comp`. ### Parameters | | | | | --- | --- | --- | | first, last | - | iterators defining the partially-ordered range to examine | | value | - | value to compare the elements to | | comp | - | binary predicate which returns ​`true` if the first argument is *less* than (i.e. is ordered before) the second. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The type `Type1` must be such that an object of type `ForwardIt` can be dereferenced and then implicitly converted to `Type1`. The type `Type2` must be such that an object of type `T` can be implicitly converted to `Type2`. ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`Compare` must meet the requirements of [BinaryPredicate](../named_req/binarypredicate "cpp/named req/BinaryPredicate"). it is not required to satisfy [Compare](../named_req/compare "cpp/named req/Compare") | ### Return value Iterator pointing to the first element in the range `[first, last)` such that `element < value` (or `comp(element, value)`) is false, or `last` if no such element is found. ### Complexity The number of comparisons performed is logarithmic in the distance between `first` and `last` (At most log 2(last - first) + O(1) comparisons). However, for non-[LegacyRandomAccessIterators](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), the number of iterator increments is linear. Notably, `[std::set](../container/set "cpp/container/set")` and `[std::multiset](../container/multiset "cpp/container/multiset")` iterators are not random access, and so their member functions `[std::set::lower\_bound](../container/set/lower_bound "cpp/container/set/lower bound")` (resp. `[std::multiset::lower\_bound](../container/multiset/lower_bound "cpp/container/multiset/lower bound")`) should be preferred. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algobase.h#L1023) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L4175). | First version | | --- | | ``` template<class ForwardIt, class T> ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value) { ForwardIt it; typename std::iterator_traits<ForwardIt>::difference_type count, step; count = std::distance(first, last); while (count > 0) { it = first; step = count / 2; std::advance(it, step); if (*it < value) { first = ++it; count -= step + 1; } else count = step; } return first; } ``` | | Second version | | ``` template<class ForwardIt, class T, class Compare> ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value, Compare comp) { ForwardIt it; typename std::iterator_traits<ForwardIt>::difference_type count, step; count = std::distance(first, last); while (count > 0) { it = first; step = count / 2; std::advance(it, step); if (comp(*it, value)) { first = ++it; count -= step + 1; } else count = step; } return first; } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> struct PriceInfo { double price; }; int main() { const std::vector<int> data = { 1, 2, 4, 5, 5, 6 }; for (int i = 0; i < 8; ++i) { // Search for first element x such that i ≤ x auto lower = std::lower_bound(data.begin(), data.end(), i); std::cout << i << " ≤ "; lower != data.end() ? std::cout << *lower << " at index " << std::distance(data.begin(), lower) : std::cout << "not found"; std::cout << '\n'; } std::vector<PriceInfo> prices = { {100.0}, {101.5}, {102.5}, {102.5}, {107.3} }; for(double to_find: {102.5, 110.2}) { auto prc_info = std::lower_bound(prices.begin(), prices.end(), to_find, [](const PriceInfo& info, double value){ return info.price < value; }); prc_info != prices.end() ? std::cout << prc_info->price << " at index " << prc_info - prices.begin() : std::cout << to_find << " not found"; std::cout << '\n'; } } ``` Output: ``` 0 ≤ 1 at index 0 1 ≤ 1 at index 0 2 ≤ 2 at index 1 3 ≤ 4 at index 2 4 ≤ 4 at index 2 5 ≤ 5 at index 3 6 ≤ 6 at index 5 7 ≤ not found 102.5 at index 2 110.2 not found ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 270](https://cplusplus.github.io/LWG/issue270) | C++98 | Compare was required to be a strict weak ordering | only a partitioning is needed; heterogeneous comparisons permitted | ### See also | | | | --- | --- | | [equal\_range](equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) | | [partition](partition "cpp/algorithm/partition") | divides a range of elements into two groups (function template) | | [partition\_point](partition_point "cpp/algorithm/partition point") (C++11) | locates the partition point of a partitioned range (function template) | | [upper\_bound](upper_bound "cpp/algorithm/upper bound") | returns an iterator to the first element *greater* than a certain value (function template) | | [lower\_bound](../container/set/lower_bound "cpp/container/set/lower bound") | returns an iterator to the first element *not less* than the given key (public member function of `std::set<Key,Compare,Allocator>`) | | [lower\_bound](../container/multiset/lower_bound "cpp/container/multiset/lower bound") | returns an iterator to the first element *not less* than the given key (public member function of `std::multiset<Key,Compare,Allocator>`) | | [ranges::lower\_bound](ranges/lower_bound "cpp/algorithm/ranges/lower bound") (C++20) | returns an iterator to the first element *not less* than the given value (niebloid) | cpp std::push_heap std::push\_heap =============== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class RandomIt > void push_heap( RandomIt first, RandomIt last ); ``` | (until C++20) | | ``` template< class RandomIt > constexpr void push_heap( RandomIt first, RandomIt last ); ``` | (since C++20) | | | (2) | | | ``` template< class RandomIt, class Compare > void push_heap( RandomIt first, RandomIt last, Compare comp ); ``` | (until C++20) | | ``` template< class RandomIt, class Compare > constexpr void push_heap( RandomIt first, RandomIt last, Compare comp ); ``` | (since C++20) | Inserts the element at the position `last-1` into the [*max heap*](https://en.wikipedia.org/wiki/Binary_heap "enwiki:Binary heap") defined by the range `[first, last-1)`. The first version of the function uses `operator<` to compare the elements, the second uses the given comparison function `comp`. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements defining the heap to modify | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `RandomIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`RandomIt` must meet the requirements of [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). | | -The type of dereferenced `RandomIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). | ### Return value (none). ### Complexity At most *log(N)* comparisons where `N=[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`. ### Notes A *max heap* is a range of elements `[f,l)` that has the following properties: * With `N = l-f`, for all `0 < i < N`, `f[(i-1)/2]` does not compare less than `f[i]`. * A new element can be added using `std::push_heap`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. * The first element can be removed using `[std::pop\_heap](pop_heap "cpp/algorithm/pop heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. ### Example ``` #include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> v { 3, 1, 4, 1, 5, 9 }; std::make_heap(v.begin(), v.end()); std::cout << "v: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; v.push_back(6); std::cout << "before push_heap: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; std::push_heap(v.begin(), v.end()); std::cout << "after push_heap: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; } ``` Output: ``` v: 9 5 4 1 1 3 before push_heap: 9 5 4 1 1 3 6 after push_heap: 9 5 6 1 1 3 4 ``` ### See also | | | | --- | --- | | [is\_heap](is_heap "cpp/algorithm/is heap") (C++11) | checks if the given range is a max heap (function template) | | [is\_heap\_until](is_heap_until "cpp/algorithm/is heap until") (C++11) | finds the largest subrange that is a max heap (function template) | | [make\_heap](make_heap "cpp/algorithm/make heap") | creates a max heap out of a range of elements (function template) | | [pop\_heap](pop_heap "cpp/algorithm/pop heap") | removes the largest element from a max heap (function template) | | [sort\_heap](sort_heap "cpp/algorithm/sort heap") | turns a max heap into a range of elements sorted in ascending order (function template) | | [ranges::push\_heap](ranges/push_heap "cpp/algorithm/ranges/push heap") (C++20) | adds an element to a max heap (niebloid) | cpp std::reverse_copy std::reverse\_copy ================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class BidirIt, class OutputIt > OutputIt reverse_copy( BidirIt first, BidirIt last, OutputIt d_first ); ``` | (until C++20) | | ``` template< class BidirIt, class OutputIt > constexpr OutputIt reverse_copy( BidirIt first, BidirIt last, OutputIt d_first ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class BidirIt, class ForwardIt > ForwardIt reverse_copy( ExecutionPolicy&& policy, BidirIt first, BidirIt last, ForwardIt d_first ); ``` | (2) | (since C++17) | 1) Copies the elements from the range `[first, last)` to another range beginning at `d_first` in such a way that the elements in the new range are in reverse order. Behaves as if by executing the assignment `*(d_first + (last - first) - 1 - i) = *(first + i)` once for each non-negative `i < (last - first)`. If the source and destination ranges (that is, `[first, last)` and `[d_first, d_first+(last-first))`, respectively) overlap, the behavior is undefined. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to copy | | d\_first | - | the beginning of the destination range | | Type requirements | | -`BidirIt` must meet the requirements of [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value Output iterator to the element past the last element copied. ### Complexity Exactly `last - first` assignments. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes Implementations (e.g. [MSVC STL](https://github.com/microsoft/STL/blob/main/stl/src/vector_algorithms.cpp)) may enable vectorization when the both iterator types satisfy [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") and have the same value type, and the value type is [TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable"). ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/14d8a5ae472ca5743016f37da2dd4770d83dea21/libstdc%2B%2B-v3/include/bits/stl_algo.h#L1170-L1190), [libc++](https://github.com/llvm/llvm-project/tree/134723edd5bf06ff6ec8aca7b87c56e5bd70ccae/libcxx/include/__algorithm/reverse_copy.h), and [MSVC STL](https://github.com/microsoft/STL/blob/472161105d596192194d4715ccad307c6c163b4a/stl/inc/algorithm#L4184-L4229). | | | --- | | ``` template<class BidirIt, class OutputIt> constexpr // since C++20 OutputIt reverse_copy(BidirIt first, BidirIt last, OutputIt d_first) { while (first != last) { *(d_first++) = *(--last); } return d_first; } ``` | ### Example ``` #include <vector> #include <iostream> #include <algorithm> int main() { auto print = [](std::vector<int> const& v) { for (const auto& value : v) std::cout << value << ' '; std::cout << '\t'; }; std::vector<int> v({1,2,3}); print(v); std::vector<int> destination(3); std::reverse_copy(std::begin(v), std::end(v), std::begin(destination)); print(destination); std::reverse_copy(std::rbegin(v), std::rend(v), std::begin(destination)); print(destination); } ``` Output: ``` 1 2 3 3 2 1 1 2 3 ``` ### See also | | | | --- | --- | | [reverse](reverse "cpp/algorithm/reverse") | reverses the order of elements in a range (function template) | | [ranges::reverse\_copy](ranges/reverse_copy "cpp/algorithm/ranges/reverse copy") (C++20) | creates a copy of a range that is reversed (niebloid) | cpp std::execution::sequenced_policy, std::execution::parallel_policy, std::execution::parallel_unsequenced_policy, std::execution::unsequenced_policy std::execution::sequenced\_policy, std::execution::parallel\_policy, std::execution::parallel\_unsequenced\_policy, std::execution::unsequenced\_policy ======================================================================================================================================================= | Defined in header `[<execution>](../header/execution "cpp/header/execution")` | | | | --- | --- | --- | | ``` class sequenced_policy { /* unspecified */ }; ``` | (1) | (since C++17) | | ``` class parallel_policy { /* unspecified */ }; ``` | (2) | (since C++17) | | ``` class parallel_unsequenced_policy { /* unspecified */ }; ``` | (3) | (since C++17) | | ``` class unsequenced_policy { /* unspecified */ }; ``` | (4) | (since C++20) | 1) The execution policy type used as a unique type to disambiguate parallel algorithm overloading and require that a parallel algorithm's execution may not be parallelized. The invocations of element access functions in parallel algorithms invoked with this policy (usually specified as `[std::execution::seq](execution_policy_tag "cpp/algorithm/execution policy tag")`) are indeterminately sequenced in the calling thread. 2) The execution policy type used as a unique type to disambiguate parallel algorithm overloading and indicate that a parallel algorithm's execution may be parallelized. The invocations of element access functions in parallel algorithms invoked with this policy (usually specified as `[std::execution::par](execution_policy_tag "cpp/algorithm/execution policy tag")`) are permitted to execute in either the invoking thread or in a thread implicitly created by the library to support parallel algorithm execution. Any such invocations executing in the same thread are indeterminately sequenced with respect to each other. 3) The execution policy type used as a unique type to disambiguate parallel algorithm overloading and indicate that a parallel algorithm's execution may be parallelized, vectorized, or migrated across threads (such as by a parent-stealing scheduler). The invocations of element access functions in parallel algorithms invoked with this policy are permitted to execute in an unordered fashion in unspecified threads, and unsequenced with respect to one another within each thread. 4) The execution policy type used as a unique type to disambiguate parallel algorithm overloading and indicate that a parallel algorithm's execution may be vectorized, e.g., executed on a single thread using instructions that operate on multiple data items. During the execution of a parallel algorithm with any of these execution policies, if the invocation of an element access function exits via an uncaught exception, `[std::terminate](../error/terminate "cpp/error/terminate")` is called, but the implementations may define additional execution policies that handle exceptions differently. ### Notes When using parallel execution policy, it is the programmer's responsibility to avoid data races and deadlocks: ``` int a[] = {0,1}; std::vector<int> v; std::for_each(std::execution::par, std::begin(a), std::end(a), [&](int i) { v.push_back(i*2+1); // Error: data race }); ``` ``` std::atomic<int> x{0}; int a[] = {1,2}; std::for_each(std::execution::par, std::begin(a), std::end(a), [&](int) { x.fetch_add(1, std::memory_order_relaxed); while (x.load(std::memory_order_relaxed) == 1) { } // Error: assumes execution order }); ``` ``` int x = 0; std::mutex m; int a[] = {1,2}; std::for_each(std::execution::par, std::begin(a), std::end(a), [&](int) { std::lock_guard<std::mutex> guard(m); ++x; // correct }); ``` Unsequenced execution policies are the only case where function calls are *unsequenced* with respect to each other, meaning they can be interleaved. In all other situations in C++, they are [indeterminately-sequenced](../language/eval_order "cpp/language/eval order") (cannot interleave). Because of that, users are not allowed to allocate or deallocate memory, acquire mutexes, use non-lockfree `[std::atomic](../atomic/atomic "cpp/atomic/atomic")` specializations, or, in general, perform any *vectorization-unsafe* operations when using these policies (vectorization-unsafe functions are the ones that synchronize-with another function, e.g. `[std::mutex::unlock](../thread/mutex/unlock "cpp/thread/mutex/unlock")` synchronizes-with the next `[std::mutex::lock](../thread/mutex/lock "cpp/thread/mutex/lock")`). ``` int x = 0; std::mutex m; int a[] = {1,2}; std::for_each(std::execution::par_unseq, std::begin(a), std::end(a), [&](int) { std::lock_guard<std::mutex> guard(m); // Error: lock_guard constructor calls m.lock() ++x; }); ``` If the implementation cannot parallelize or vectorize (e.g. due to lack of resources), all standard execution policies can fall back to sequential execution. ### See also | | | | --- | --- | | [seqparpar\_unsequnseq](execution_policy_tag "cpp/algorithm/execution policy tag") (C++17)(C++17)(C++17)(C++20) | global execution policy objects (constant) |
programming_docs
cpp std::transform std::transform ============== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class OutputIt, class UnaryOperation > OutputIt transform( InputIt first1, InputIt last1, OutputIt d_first, UnaryOperation unary_op ); ``` | (until C++20) | | ``` template< class InputIt, class OutputIt, class UnaryOperation > constexpr OutputIt transform( InputIt first1, InputIt last1, OutputIt d_first, UnaryOperation unary_op ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class UnaryOperation > ForwardIt2 transform( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 d_first, UnaryOperation unary_op ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt1, class InputIt2, class OutputIt, class BinaryOperation > OutputIt transform( InputIt1 first1, InputIt1 last1, InputIt2 first2, OutputIt d_first, BinaryOperation binary_op ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class OutputIt, class BinaryOperation > constexpr OutputIt transform( InputIt1 first1, InputIt1 last1, InputIt2 first2, OutputIt d_first, BinaryOperation binary_op ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class ForwardIt3, class BinaryOperation > ForwardIt3 transform( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt3 d_first, BinaryOperation binary_op ); ``` | (4) | (since C++17) | `std::transform` applies the given function to a range and stores the result in another range, keeping the original elements order and beginning at `d_first`. 1) The unary operation `unary_op` is applied to the range defined by `[first1, last1)`. 3) The binary operation `binary_op` is applied to pairs of elements from two ranges: one defined by `[first1, last1)` and the other beginning at `first2`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. | | | | --- | --- | | `unary_op` and `binary_op` must not have side effects. | (until C++11) | | `unary_op` and `binary_op` must not invalidate any iterators, including the end iterators, or modify any elements of the ranges involved. | (since C++11) | ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first range of elements to transform | | first2 | - | the beginning of the second range of elements to transform | | d\_first | - | the beginning of the destination range, may be equal to `first1` or `first2` | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | unary\_op | - | unary operation function object that will be applied. The signature of the function should be equivalent to the following: `Ret fun(const Type &a);` The signature does not need to have `const &`. The type `Type` must be such that an object of type `InputIt` can be dereferenced and then implicitly converted to `Type`. The type `Ret` must be such that an object of type `OutputIt` can be dereferenced and assigned a value of type `Ret`. ​ | | binary\_op | - | binary operation function object that will be applied. The signature of the function should be equivalent to the following: `Ret fun(const Type1 &a, const Type2 &b);` The signature does not need to have `const &`. The types `Type1` and `Type2` must be such that objects of types `InputIt1` and `InputIt2` can be dereferenced and then implicitly converted to `Type1` and `Type2` respectively. The type `Ret` must be such that an object of type `OutputIt` can be dereferenced and assigned a value of type `Ret`. ​ | | Type requirements | | -`InputIt, InputIt1, InputIt2` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1, ForwardIt2, ForwardIt3` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value Output iterator to the element past the last element transformed. ### Complexity 1-2) Exactly `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1)` applications of `unary_op` 3-4) Exactly `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1)` applications of `binary_op` ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template< class InputIt, class OutputIt, class UnaryOperation > OutputIt transform( InputIt first1, InputIt last1, OutputIt d_first, UnaryOperation unary_op ) { while (first1 != last1) { *d_first++ = unary_op(*first1++); } return d_first; } ``` | | Second version | | ``` template< class InputIt1, class InputIt2, class OutputIt, class BinaryOperation > OutputIt transform( InputIt1 first1, InputIt1 last1, InputIt2 first2, OutputIt d_first, BinaryOperation binary_op ) { while (first1 != last1) { *d_first++ = binary_op(*first1++, *first2++); } return d_first; } ``` | ### Notes `std::transform` does not guarantee in-order application of `unary_op` or `binary_op`. To apply a function to a sequence in-order or to apply a function that modifies the elements of a sequence, use `[std::for\_each](for_each "cpp/algorithm/for each")`. ### Example The following code uses `transform` to convert a string in place to uppercase using the `std::toupper` function and then transforms each `char` to its ordinal value: ``` #include <algorithm> #include <cctype> #include <iomanip> #include <iostream> #include <string> #include <vector> int main() { std::string s{"hello"}; std::transform(s.cbegin(), s.cend(), s.begin(), // write to the same location [](unsigned char c) { return std::toupper(c); }); std::cout << "s = " << quoted(s) << '\n'; // achieving the same with std::for_each (see Notes above) std::string g{"hello"}; std::for_each(g.begin(), g.end(), [](char& c) { // modify in-place c = std::toupper(static_cast<unsigned char>(c)); }); std::cout << "g = " << quoted(g) << '\n'; std::vector<std::size_t> ordinals; std::transform(s.cbegin(), s.cend(), std::back_inserter(ordinals), [](unsigned char c) { return c; }); std::cout << "ordinals: "; for (auto ord : ordinals) { std::cout << ord << ' '; } std::transform(ordinals.cbegin(), ordinals.cend(), ordinals.cbegin(), ordinals.begin(), std::plus<>{}); std::cout << "\nordinals: "; for (auto ord : ordinals) { std::cout << ord << ' '; } std::cout << '\n'; } ``` Output: ``` s = "HELLO" g = "HELLO" ordinals: 72 69 76 76 79 ordinals: 144 138 152 152 158 ``` ### See also | | | | --- | --- | | [for\_each](for_each "cpp/algorithm/for each") | applies a function to a range of elements (function template) | | [ranges::transform](ranges/transform "cpp/algorithm/ranges/transform") (C++20) | applies a function to a range of elements (niebloid) | cpp std::accumulate std::accumulate =============== | Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class T > T accumulate( InputIt first, InputIt last, T init ); ``` | (until C++20) | | ``` template< class InputIt, class T > constexpr T accumulate( InputIt first, InputIt last, T init ); ``` | (since C++20) | | | (2) | | | ``` template< class InputIt, class T, class BinaryOperation > T accumulate( InputIt first, InputIt last, T init, BinaryOperation op ); ``` | (until C++20) | | ``` template< class InputIt, class T, class BinaryOperation > constexpr T accumulate( InputIt first, InputIt last, T init, BinaryOperation op ); ``` | (since C++20) | Computes the sum of the given value `init` and the elements in the range `[first, last)`. The first version uses `operator+` to sum up the elements, the second version uses the given binary function `op`, both applying [`std::move`](../utility/move "cpp/utility/move") to their operands on the left hand side (since C++20). | | | | --- | --- | | `op` must not have side effects. | (until C++11) | | `op` must not invalidate any iterators, including the end iterators, nor modify any elements of the range involved, nor \*last. | (since C++11) | ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to sum | | init | - | initial value of the sum | | op | - | binary operation function object that will be applied. The binary operator takes the current accumulation value `a` (initialized to `init`) and the value of the current element `b`. The signature of the function should be equivalent to the following: `Ret fun(const Type1 &a, const Type2 &b);` The signature does not need to have `const &`. The type `Type1` must be such that an object of type `T` can be implicitly converted to `Type1`. The type `Type2` must be such that an object of type `InputIt` can be dereferenced and then implicitly converted to `Type2`. The type `Ret` must be such that an object of type `T` can be assigned a value of type `Ret`. ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`T` must meet the requirements of [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable") and [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"). | ### Return value 1) The sum of the given value and elements in the given range. 2) The result of [left fold](https://en.wikipedia.org/wiki/Fold_(higher-order_function) "enwiki:Fold (higher-order function)") of the given range over `op` ### Notes `std::accumulate` performs a left fold. In order to perform a right fold, one must reverse the order of the arguments to the binary operator, and use reverse iterators. #### Common mistakes If left to type inference, `op` operates on values of the same type as `init` which can result in unwanted casting of the iterator elements. For example, `std::accumulate(v.begin(), v.end(), 0)` likely does not give the result one wishes for when `v` is `[std::vector](http://en.cppreference.com/w/cpp/container/vector)<double>`. ### Possible implementation | First version | | --- | | ``` template<class InputIt, class T> constexpr // since C++20 T accumulate(InputIt first, InputIt last, T init) { for (; first != last; ++first) { init = std::move(init) + *first; // std::move since C++20 } return init; } ``` | | Second version | | ``` template<class InputIt, class T, class BinaryOperation> constexpr // since C++20 T accumulate(InputIt first, InputIt last, T init, BinaryOperation op) { for (; first != last; ++first) { init = op(std::move(init), *first); // std::move since C++20 } return init; } ``` | ### Example ``` #include <iostream> #include <vector> #include <numeric> #include <string> #include <functional> int main() { std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int sum = std::accumulate(v.begin(), v.end(), 0); int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>()); auto dash_fold = [](std::string a, int b) { return std::move(a) + '-' + std::to_string(b); }; std::string s = std::accumulate(std::next(v.begin()), v.end(), std::to_string(v[0]), // start with first element dash_fold); // Right fold using reverse iterators std::string rs = std::accumulate(std::next(v.rbegin()), v.rend(), std::to_string(v.back()), // start with last element dash_fold); std::cout << "sum: " << sum << '\n' << "product: " << product << '\n' << "dash-separated string: " << s << '\n' << "dash-separated string (right-folded): " << rs << '\n'; } ``` Output: ``` sum: 55 product: 3628800 dash-separated string: 1-2-3-4-5-6-7-8-9-10 dash-separated string (right-folded): 10-9-8-7-6-5-4-3-2-1 ``` ### See also | | | | --- | --- | | [adjacent\_difference](adjacent_difference "cpp/algorithm/adjacent difference") | computes the differences between adjacent elements in a range (function template) | | [inner\_product](inner_product "cpp/algorithm/inner product") | computes the inner product of two ranges of elements (function template) | | [partial\_sum](partial_sum "cpp/algorithm/partial sum") | computes the partial sum of a range of elements (function template) | | [reduce](reduce "cpp/algorithm/reduce") (C++17) | similar to `std::accumulate`, except out of order (function template) | cpp std::lexicographical_compare_three_way std::lexicographical\_compare\_three\_way ========================================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template< class InputIt1, class InputIt2, class Cmp > constexpr auto lexicographical_compare_three_way( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, Cmp comp ); -> decltype(comp(*first1, *first2)); ``` | (1) | (since C++20) | | ``` template< class InputIt1, class InputIt2 > constexpr auto lexicographical_compare_three_way( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2 ); ``` | (2) | (since C++20) | Lexicographically compares two ranges `[first1, last1)` and `[first2, last2)` using three-way comparison and produces a result of the strongest applicable comparison category type. 1) Returns the order between the first non-equivalent pair of elements according to `comp` in both ranges if any, otherwise (if one ranges is equivalent to the prefix of another according to `comp`), returns the order between the length of both ranges. 2) Equivalent to: ``` return std::lexicographical_compare_three_way( first1, last1, first2, last2, std::compare_three_way()); ``` ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first range of elements to examine | | first2, last2 | - | the second range of elements to examine | | comp | - | a function object type. The program is ill-formed if its return type is not one of the three comparison category types ([`std::strong_ordering`](../utility/compare/strong_ordering "cpp/utility/compare/strong ordering"), [`std::weak_ordering`](../utility/compare/weak_ordering "cpp/utility/compare/weak ordering"), or [`std::partial_ordering`](../utility/compare/partial_ordering "cpp/utility/compare/partial ordering")). | | Type requirements | | -`InputIt1, InputIt2` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | ### Return value The value of a comparison category type specified above. ### Complexity At most *N* applications of `comp`, where *N* is the smaller of length of both ranges. ### Possible implementation | | | --- | | ``` template< class I1, class I2, class Cmp > constexpr auto lexicographical_compare_three_way( I1 f1, I1 l1, I2 f2, I2 l2, Cmp comp ) -> decltype(comp(*f1, *f2)) { using ret_t = decltype(comp(*f1, *f2)); static_assert(std::disjunction_v< std::is_same<ret_t, std::strong_ordering>, std::is_same<ret_t, std::weak_ordering>, std::is_same<ret_t, std::partial_ordering>>, "The return type must be a comparison category type."); bool exhaust1 = (f1 == l1); bool exhaust2 = (f2 == l2); for (; !exhaust1 && !exhaust2; exhaust1 = (++f1 == l1), exhaust2 = (++f2 == l2)) if (auto c = comp(*f1, *f2); c != 0) return c; return !exhaust1 ? std::strong_ordering::greater : !exhaust2 ? std::strong_ordering::less : std::strong_ordering::equal; } ``` | ### Example ``` #include <algorithm> #include <cctype> #include <compare> #include <iomanip> #include <iostream> #include <string_view> #include <utility> using namespace std::literals; void show_result(std::string_view s1, std::string_view s2, std::strong_ordering o) { std::cout << quoted(s1) << " is "; (o < 0) ? std::cout << "less than " : (o > 0) ? std::cout << "greater than " : std::cout << "equal to "; std::cout << quoted(s2) << '\n'; } int main() { auto cmp_icase = [](char x, char y) { const auto ux { std::toupper(x) }; const auto uy { std::toupper(y) }; return (ux < uy) ? std::strong_ordering::less: (ux > uy) ? std::strong_ordering::greater: std::strong_ordering::equal; }; for (const auto& [s1, s2] : { std::pair{"one"sv, "ONE"sv}, {"two"sv, "four"sv}, {"three"sv, "two"sv} }) { const auto res = std::lexicographical_compare_three_way( s1.cbegin(), s1.cend(), s2.cbegin(), s2.cend(), cmp_icase); show_result(s1, s2, res); } } ``` Output: ``` "one" is equal to "ONE" "two" is greater than "four" "three" is less than "two" ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 3410](https://cplusplus.github.io/LWG/issue3410) | C++20 | extraneous comparisons between iterators were required | such requirement removed | ### See also | | | | --- | --- | | [lexicographical\_compare](lexicographical_compare "cpp/algorithm/lexicographical compare") | returns true if one range is lexicographically less than another (function template) | | [compare\_three\_way](../utility/compare/compare_three_way "cpp/utility/compare/compare three way") (C++20) | function object implementing `x <=> y` (class) | | [ranges::lexicographical\_compare](ranges/lexicographical_compare "cpp/algorithm/ranges/lexicographical compare") (C++20) | returns true if one range is lexicographically less than another (niebloid) |
programming_docs
cpp std::lexicographical_compare std::lexicographical\_compare ============================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt1, class InputIt2 > bool lexicographical_compare( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2 ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2 > constexpr bool lexicographical_compare( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2 ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > bool lexicographical_compare( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2 ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt1, class InputIt2, class Compare > bool lexicographical_compare( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, Compare comp ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class Compare > constexpr bool lexicographical_compare( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class Compare > bool lexicographical_compare( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, Compare comp ); ``` | (4) | (since C++17) | Checks if the first range `[first1, last1)` is lexicographically *less* than the second range `[first2, last2)`. 1) Elements are compared using `operator<`. 3) Elements are compared using the given binary comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. Lexicographical comparison is an operation with the following properties: * Two ranges are compared element by element. * The first mismatching element defines which range is lexicographically *less* or *greater* than the other. * If one range is a prefix of another, the shorter range is lexicographically *less* than the other. * If two ranges have equivalent elements and are of the same length, then the ranges are lexicographically *equal*. * An empty range is lexicographically *less* than any non-empty range. * Two empty ranges are lexicographically *equal*. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first range of elements to examine | | first2, last2 | - | the second range of elements to examine | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that objects of types `InputIt1` and `InputIt2` can be dereferenced and then implicitly converted to both `Type1` and `Type2`. ​ | | Type requirements | | -`InputIt1, InputIt2` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value `true` if the first range is lexicographically *less* than the second. ### Complexity At most 2·min(N1, N2) applications of the comparison operation, where `N1 = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1)` and `N2 = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first2, last2)`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class InputIt1, class InputIt2> bool lexicographical_compare(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2) { for ( ; (first1 != last1) && (first2 != last2); ++first1, (void) ++first2 ) { if (*first1 < *first2) return true; if (*first2 < *first1) return false; } return (first1 == last1) && (first2 != last2); } ``` | | Second version | | ``` template<class InputIt1, class InputIt2, class Compare> bool lexicographical_compare(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, Compare comp) { for ( ; (first1 != last1) && (first2 != last2); ++first1, (void) ++first2 ) { if (comp(*first1, *first2)) return true; if (comp(*first2, *first1)) return false; } return (first1 == last1) && (first2 != last2); } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> #include <random> int main() { std::vector<char> v1 {'a', 'b', 'c', 'd'}; std::vector<char> v2 {'a', 'b', 'c', 'd'}; std::mt19937 g{std::random_device{}()}; while (!std::lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end())) { for (auto c : v1) std::cout << c << ' '; std::cout << ">= "; for (auto c : v2) std::cout << c << ' '; std::cout << '\n'; std::shuffle(v1.begin(), v1.end(), g); std::shuffle(v2.begin(), v2.end(), g); } for (auto c : v1) std::cout << c << ' '; std::cout << "< "; for (auto c : v2) std::cout << c << ' '; std::cout << '\n'; } ``` Possible output: ``` a b c d >= a b c d d a b c >= c b d a b d a c >= a d c b a c d b < c d a b ``` ### See also | | | | --- | --- | | [equal](equal "cpp/algorithm/equal") | determines if two sets of elements are the same (function template) | | [ranges::lexicographical\_compare](ranges/lexicographical_compare "cpp/algorithm/ranges/lexicographical compare") (C++20) | returns true if one range is lexicographically less than another (niebloid) | cpp std::minmax std::minmax =========== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class T > std::pair<const T&,const T&> minmax( const T& a, const T& b ); ``` | (since C++11) (until C++14) | | ``` template< class T > constexpr std::pair<const T&,const T&> minmax( const T& a, const T& b ); ``` | (since C++14) | | | (2) | | | ``` template< class T, class Compare > std::pair<const T&,const T&> minmax( const T& a, const T& b, Compare comp ); ``` | (since C++11) (until C++14) | | ``` template< class T, class Compare > constexpr std::pair<const T&,const T&> minmax( const T& a, const T& b, Compare comp ); ``` | (since C++14) | | | (3) | | | ``` template< class T > std::pair<T,T> minmax( std::initializer_list<T> ilist); ``` | (since C++11) (until C++14) | | ``` template< class T > constexpr std::pair<T,T> minmax( std::initializer_list<T> ilist); ``` | (since C++14) | | | (4) | | | ``` template< class T, class Compare > std::pair<T,T> minmax( std::initializer_list<T> ilist, Compare comp ); ``` | (since C++11) (until C++14) | | ``` template< class T, class Compare > constexpr std::pair<T,T> minmax( std::initializer_list<T> ilist, Compare comp ); ``` | (since C++14) | Returns the lowest and the greatest of the given values. 1-2) Returns references to the smaller and the greater of `a` and `b`. 3-4) Returns the smallest and the greatest of the values in initializer list `ilist`. The (1,3) versions use `operator<` to compare the values, whereas the (2,4) versions use the given comparison function `comp`. ### Parameters | | | | | --- | --- | --- | | a, b | - | the values to compare | | ilist | - | initializer list with the values to compare | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `T` can be implicitly converted to both of them. ​ | | Type requirements | | -`T` must meet the requirements of [LessThanComparable](../named_req/lessthancomparable "cpp/named req/LessThanComparable") in order to use overloads (1,3). | | -`T` must meet the requirements of [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") in order to use overloads (3,4). | ### Return value 1-2) Returns the result of `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const T&, const T&>(a, b)` if `a<b` or if `a` is equivalent to `b`. Returns the result of `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)<const T&, const T&>(b, a)` if `b<a`. 3-4) A pair with the smallest value in `ilist` as the first element and the greatest as the second. If several elements are equivalent to the smallest, the leftmost such element is returned. If several elements are equivalent to the largest, the rightmost such element is returned. ### Complexity 1-2) Exactly one comparison 3-4) At most `ilist.size() * 3 / 2` comparisons ### Possible implementation | First version | | --- | | ``` template<class T> constexpr std::pair<const T&, const T&> minmax( const T& a, const T& b ) { return (b < a) ? std::pair<const T&, const T&>(b, a) : std::pair<const T&, const T&>(a, b); } ``` | | Second version | | ``` template<class T, class Compare> constexpr std::pair<const T&, const T&> minmax( const T& a, const T& b, Compare comp ) { return comp(b, a) ? std::pair<const T&, const T&>(b, a) : std::pair<const T&, const T&>(a, b); } ``` | | Third version | | ``` template< class T > constexpr std::pair<T, T> minmax( std::initializer_list<T> ilist ) { auto p = std::minmax_element(ilist.begin(), ilist.end()); return std::pair(*p.first, *p.second); } ``` | | Fourth version | | ``` template< class T, class Compare > constexpr std::pair<T, T> minmax( std::initializer_list<T> ilist, Compare comp ) { auto p = std::minmax_element(ilist.begin(), ilist.end(), comp); return std::pair(*p.first, *p.second); } ``` | ### Notes For overloads (1,2), if one of the parameters is a temporary, the reference returned becomes a dangling reference at the end of the full expression that contains the call to `minmax`: ``` int n = 1; auto p = std::minmax(n, n+1); int m = p.first; // ok int x = p.second; // undefined behavior // Note that structured bindings have the same issue auto [mm, xx] = std::minmax(n, n+1); xx; // undefined behavior ``` ### Example ``` #include <algorithm> #include <iostream> #include <vector> #include <cstdlib> #include <ctime> int main() { std::vector<int> v {3, 1, 4, 1, 5, 9, 2, 6}; std::srand(std::time(0)); std::pair<int, int> bounds = std::minmax(std::rand() % v.size(), std::rand() % v.size()); std::cout << "v[" << bounds.first << "," << bounds.second << "]: "; for (int i = bounds.first; i < bounds.second; ++i) { std::cout << v[i] << ' '; } std::cout << '\n'; } ``` Possible output: ``` v[2,7]: 4 1 5 9 2 ``` ### See also | | | | --- | --- | | [min](min "cpp/algorithm/min") | returns the smaller of the given values (function template) | | [max](max "cpp/algorithm/max") | returns the greater of the given values (function template) | | [minmax\_element](minmax_element "cpp/algorithm/minmax element") (C++11) | returns the smallest and the largest elements in a range (function template) | | [ranges::minmax](ranges/minmax "cpp/algorithm/ranges/minmax") (C++20) | returns the smaller and larger of two elements (niebloid) | cpp std::partition_copy std::partition\_copy ==================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class OutputIt1, class OutputIt2, class UnaryPredicate > std::pair<OutputIt1, OutputIt2> partition_copy( InputIt first, InputIt last, OutputIt1 d_first_true, OutputIt2 d_first_false, UnaryPredicate p ); ``` | (since C++11) (until C++20) | | ``` template< class InputIt, class OutputIt1, class OutputIt2, class UnaryPredicate > constexpr std::pair<OutputIt1, OutputIt2> partition_copy( InputIt first, InputIt last, OutputIt1 d_first_true, OutputIt2 d_first_false, UnaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class ForwardIt3, class UnaryPredicate > std::pair<ForwardIt2, ForwardIt3> partition_copy( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first_true, ForwardIt3 d_first_false, UnaryPredicate p ); ``` | (2) | (since C++17) | 1) Copies the elements from the range `[first, last)` to two different ranges depending on the value returned by the predicate `p`. The elements that satisfy the predicate `p` are copied to the range beginning at `d_first_true`. The rest of the elements are copied to the range beginning at `d_first_false`. The behavior is undefined if the input range overlaps either of the output ranges. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to copy from | | d\_first\_true | - | the beginning of the output range for the elements that satisfy p | | d\_first\_false | - | the beginning of the output range for the elements that do not satisfy p | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | unary predicate which returns ​`true` if the element should be placed in d\_first\_true. The expression `p(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `VT`, where `VT` is the value type of `InputIt`, regardless of [value category](../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `VT&`is not allowed, nor is `VT` unless for `VT` a move is equivalent to a copy (since C++11). ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -The type of dereferenced `InputIt` must meet the requirements of [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"). | | -`OutputIt1, OutputIt2` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1, ForwardIt2, ForwardIt3` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). ForwardIt1's value type must be CopyAssignable, writable to ForwardIt2 and ForwardIt3, and convertible to UnaryPredicate's argument type | | -`UnaryPredicate` must meet the requirements of [Predicate](../named_req/predicate "cpp/named req/Predicate"). | ### Return value A `[std::pair](http://en.cppreference.com/w/cpp/utility/pair)` constructed from the iterator to the end of the `d_first_true` range and the iterator to the end of the `d_first_false` range. ### Complexity Exactly `distance(first, last)` applications of `p`. For the overload with an ExecutionPolicy, there may be a performance cost if ForwardIt's value type is not [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"). ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | | | --- | | ``` template<class InputIt, class OutputIt1, class OutputIt2, class UnaryPredicate> std::pair<OutputIt1, OutputIt2> partition_copy(InputIt first, InputIt last, OutputIt1 d_first_true, OutputIt2 d_first_false, UnaryPredicate p) { while (first != last) { if (p(*first)) { *d_first_true = *first; ++d_first_true; } else { *d_first_false = *first; ++d_first_false; } ++first; } return std::pair<OutputIt1, OutputIt2>(d_first_true, d_first_false); } ``` | ### Example ``` #include <iostream> #include <algorithm> #include <utility> int main() { int arr [10] = {1,2,3,4,5,6,7,8,9,10}; int true_arr [5] = {0}; int false_arr [5] = {0}; std::partition_copy(std::begin(arr), std::end(arr), std::begin(true_arr),std::begin(false_arr), [] (int i) {return i > 5;}); std::cout << "true_arr: "; for (int x : true_arr) { std::cout << x << ' '; } std::cout << '\n'; std::cout << "false_arr: "; for (int x : false_arr) { std::cout << x << ' '; } std::cout << '\n'; return 0; } ``` Output: ``` true_arr: 6 7 8 9 10 false_arr: 1 2 3 4 5 ``` ### See also | | | | --- | --- | | [partition](partition "cpp/algorithm/partition") | divides a range of elements into two groups (function template) | | [stable\_partition](stable_partition "cpp/algorithm/stable partition") | divides elements into two groups while preserving their relative order (function template) | | [copycopy\_if](copy "cpp/algorithm/copy") (C++11) | copies a range of elements to a new location (function template) | | [remove\_copyremove\_copy\_if](remove_copy "cpp/algorithm/remove copy") | copies a range of elements omitting those that satisfy specific criteria (function template) | | [ranges::partition\_copy](ranges/partition_copy "cpp/algorithm/ranges/partition copy") (C++20) | copies a range dividing the elements into two groups (niebloid) |
programming_docs
cpp std::bsearch std::bsearch ============ | Defined in header `[<cstdlib>](../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` void* bsearch( const void* key, const void* ptr, std::size_t count, std::size_t size, /*compare-pred*/* comp ); void* bsearch( const void* key, const void* ptr, std::size_t count, std::size_t size, /*c-compare-pred*/* comp ); ``` | (1) | | | ``` extern "C++" using /*compare-pred*/ = int(const void*, const void*); // exposition-only extern "C" using /*c-compare-pred*/ = int(const void*, const void*); // exposition-only ``` | (2) | | Finds an element equal to element pointed to by `key` in an array pointed to by `ptr`. The array contains `count` elements of `size` bytes each and must be partitioned with respect to the object pointed to by `key`, that is, all the elements that compare less than must appear before all the elements that compare equal to, and those must appear before all the elements that compare greater than the key object. A fully sorted array satisfies these requirements. The elements are compared using function pointed to by `comp`. The behavior is undefined if the array is not already partitioned in ascending order with respect to key, according to the same criterion that `comp` uses. If the array contains several elements that `comp` would indicate as equal to the element searched for, then it is unspecified which element the function will return as the result. ### Parameters | | | | | --- | --- | --- | | key | - | pointer to the element to search for | | ptr | - | pointer to the array to examine | | count | - | number of element in the array | | size | - | size of each element in the array in bytes | | comp | - | comparison function which returns ​a negative integer value if the first argument is *less* than the second, a positive integer value if the first argument is *greater* than the second and zero if the arguments are equivalent. `key` is passed as the first argument, an element from the array as the second. The signature of the comparison function should be equivalent to the following: `int cmp(const void *a, const void *b);` The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array. ​ | ### Return value Pointer to the found element or null pointer if the element has not been found. ### Notes Despite the name, neither C nor POSIX standards require this function to be implemented using binary search or make any complexity guarantees. The two overloads provided by the C++ standard library are distinct because the types of the parameter `comp` are distinct ([language linkage](../language/language_linkage "cpp/language/language linkage") is part of its type). ### Example ``` #include <iostream> #include <cstdlib> #include <array> template <typename T> int compare(const void *a, const void *b) { const auto &arg1 = *(static_cast<const T*>(a)); const auto &arg2 = *(static_cast<const T*>(b)); const auto cmp = arg1 <=> arg2; return cmp < 0 ? -1 : cmp > 0 ? +1 : 0; } int main() { std::array arr { 1, 2, 3, 4, 5, 6, 7, 8 }; for (const int key : { 4, 8, 9 }) { const int* p = static_cast<int*>( std::bsearch(&key, arr.data(), arr.size(), sizeof(decltype(arr)::value_type), compare<int>)); std::cout << "value " << key; (p) ? std::cout << " found at position " << (p - arr.data()) << '\n' : std::cout << " not found\n"; } } ``` Output: ``` value 4 found at position 3 value 8 found at position 7 value 9 not found ``` ### See also | | | | --- | --- | | [qsort](qsort "cpp/algorithm/qsort") | sorts a range of elements with unspecified type (function) | | [equal\_range](equal_range "cpp/algorithm/equal range") | returns range of elements matching a specific key (function template) | | [C documentation](https://en.cppreference.com/w/c/algorithm/bsearch "c/algorithm/bsearch") for `bsearch` | cpp std::random_shuffle, std::shuffle std::random\_shuffle, std::shuffle ================================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template< class RandomIt > void random_shuffle( RandomIt first, RandomIt last ); ``` | (1) | (deprecated in C++14) (removed in C++17) | | | (2) | | | ``` template< class RandomIt, class RandomFunc > void random_shuffle( RandomIt first, RandomIt last, RandomFunc& r ); ``` | (until C++11) | | ``` template< class RandomIt, class RandomFunc > void random_shuffle( RandomIt first, RandomIt last, RandomFunc&& r ); ``` | (since C++11) (deprecated in C++14) (removed in C++17) | | ``` template< class RandomIt, class URBG > void shuffle( RandomIt first, RandomIt last, URBG&& g ); ``` | (3) | (since C++11) | Reorders the elements in the given range `[first, last)` such that each possible permutation of those elements has equal probability of appearance. 1) The random number generator is implementation-defined, but the function `[std::rand](../numeric/random/rand "cpp/numeric/random/rand")` is often used. 2) The random number generator is the function object `r`. 3) The random number generator is the function object `g`. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to shuffle randomly | | r | - | function object returning a randomly chosen value of type convertible to `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<RandomIt>::difference\_type` in the interval [0,n) if invoked as `r(n)` | | g | - | a [UniformRandomBitGenerator](../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator") whose result type is convertible to `[std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<RandomIt>::difference\_type` | | Type requirements | | -`RandomIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). | | -`[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<URBG>` must meet the requirements of [UniformRandomBitGenerator](../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator"). | ### Return value (none). ### Complexity Linear in the distance between `first` and `last`. ### Notes Note that the implementation is not dictated by the standard, so even if you use exactly the same `RandomFunc` or `URBG` (Uniform Random Number Generator) you may get different results with different standard library implementations. The reason for removing `std::random_shuffle` in C++17 is that the iterator-only version usually depends on `[std::rand](../numeric/random/rand "cpp/numeric/random/rand")`, which is now also discussed for deprecation. (`[std::rand](../numeric/random/rand "cpp/numeric/random/rand")` should be replaced with the classes of the [`<random>`](../header/random "cpp/header/random") header, as `[std::rand](../numeric/random/rand "cpp/numeric/random/rand")` is *considered harmful*.) In addition, the iterator-only `std::random_shuffle` version usually depends on a global state. The `std::shuffle`'s shuffle algorithm is the preferred replacement, as it uses a `URBG` as its 3rd parameter. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L4551) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L3066). | First version | | --- | | ``` template< class RandomIt > void random_shuffle( RandomIt first, RandomIt last ) { typename std::iterator_traits<RandomIt>::difference_type i, n; n = last - first; for (i = n-1; i > 0; --i) { using std::swap; swap(first[i], first[std::rand() % (i+1)]); // rand() % (i+1) isn't actually correct, because the generated number // is not uniformly distributed for most values of i. A correct implementation // will need to essentially reimplement C++11 std::uniform_int_distribution, // which is beyond the scope of this example. } } ``` | | Second version | | ``` template<class RandomIt, class RandomFunc> void random_shuffle(RandomIt first, RandomIt last, RandomFunc&& r) { typename std::iterator_traits<RandomIt>::difference_type i, n; n = last - first; for (i = n-1; i > 0; --i) { using std::swap; swap(first[i], first[r(i+1)]); } } ``` | | Third version | | ``` template<class RandomIt, class URBG> void shuffle(RandomIt first, RandomIt last, URBG&& g) { typedef typename std::iterator_traits<RandomIt>::difference_type diff_t; typedef std::uniform_int_distribution<diff_t> distr_t; typedef typename distr_t::param_type param_t; distr_t D; diff_t n = last - first; for (diff_t i = n-1; i > 0; --i) { using std::swap; swap(first[i], first[D(g, param_t(0, i))]); } } ``` | ### Example The following code randomly shuffles the integers 1..10: ``` #include <random> #include <algorithm> #include <iterator> #include <iostream> #include <vector> int main() { std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; std::random_device rd; std::mt19937 g(rd()); std::shuffle(v.begin(), v.end(), g); std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; } ``` Possible output: ``` 8 6 10 4 2 3 7 1 9 5 ``` ### See also | | | | --- | --- | | [next\_permutation](next_permutation "cpp/algorithm/next permutation") | generates the next greater lexicographic permutation of a range of elements (function template) | | [prev\_permutation](prev_permutation "cpp/algorithm/prev permutation") | generates the next smaller lexicographic permutation of a range of elements (function template) | | [ranges::shuffle](ranges/shuffle "cpp/algorithm/ranges/shuffle") (C++20) | randomly re-orders elements in a range (niebloid) | cpp std::set_symmetric_difference std::set\_symmetric\_difference =============================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt1, class InputIt2, class OutputIt > OutputIt set_symmetric_difference( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class OutputIt > constexpr OutputIt set_symmetric_difference( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class ForwardIt3 > ForwardIt3 set_symmetric_difference( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, ForwardIt3 d_first ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt1, class InputIt2, class OutputIt, class Compare > OutputIt set_symmetric_difference( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class OutputIt, class Compare > constexpr OutputIt set_symmetric_difference( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class ForwardIt3, class Compare > ForwardIt3 set_symmetric_difference( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, ForwardIt3 d_first, Compare comp ); ``` | (4) | (since C++17) | Computes symmetric difference of two sorted ranges: the elements that are found in either of the ranges, but not in both of them are copied to the range beginning at `d_first`. The resulting range is also sorted. If some element is found `m` times in `[first1, last1)` and `n` times in `[first2, last2)`, it will be copied to `d_first` exactly `std::abs(m-n)` times. If `m>n`, then the last `m-n` of those elements are copied from `[first1,last1)`, otherwise the last `n-m` elements are copied from `[first2,last2)`. The resulting range cannot overlap with either of the input ranges. 1) Elements are compared using `operator<` and the ranges must be sorted with respect to the same. 3) Elements are compared using the given binary comparison function `comp` and the ranges must be sorted with respect to the same. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first sorted range of elements | | first2, last2 | - | the second sorted range of elements | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that objects of types `InputIt1` and `InputIt2` can be dereferenced and then implicitly converted to both `Type1` and `Type2`. ​ | | Type requirements | | -`InputIt1, InputIt2` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1, ForwardIt2, ForwardIt3` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value Iterator past the end of the constructed range. ### Complexity At most \(\scriptsize 2\cdot(N\_1+N\_2)-1\)2·(N 1+N 2)-1 comparisons, where \(\scriptsize N\_1\)N 1 and \(\scriptsize N\_2\)N 2 are `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1)` and `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first2, last2)`, respectively. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class InputIt1, class InputIt2, class OutputIt> OutputIt set_symmetric_difference(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first) { while (first1 != last1) { if (first2 == last2) return std::copy(first1, last1, d_first); if (*first1 < *first2) { *d_first++ = *first1++; } else { if (*first2 < *first1) { *d_first++ = *first2; } else { ++first1; } ++first2; } } return std::copy(first2, last2, d_first); } ``` | | Second version | | ``` template<class InputIt1, class InputIt2, class OutputIt, class Compare> OutputIt set_symmetric_difference(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp) { while (first1 != last1) { if (first2 == last2) return std::copy(first1, last1, d_first); if (comp(*first1, *first2)) { *d_first++ = *first1++; } else { if (comp(*first2, *first1)) { *d_first++ = *first2; } else { ++first1; } ++first2; } } return std::copy(first2, last2, d_first); } ``` | ### Example ``` #include <iostream> #include <vector> #include <algorithm> #include <iterator> int main() { std::vector<int> v1{1,2,3,4,5,6,7,8 }; std::vector<int> v2{ 5, 7, 9,10}; std::sort(v1.begin(), v1.end()); std::sort(v2.begin(), v2.end()); std::vector<int> v_symDifference; std::set_symmetric_difference( v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v_symDifference)); for(int n : v_symDifference) std::cout << n << ' '; } ``` Output: ``` 1 2 3 4 6 8 9 10 ``` ### See also | | | | --- | --- | | [includes](includes "cpp/algorithm/includes") | returns true if one sequence is a subsequence of another (function template) | | [set\_difference](set_difference "cpp/algorithm/set difference") | computes the difference between two sets (function template) | | [set\_union](set_union "cpp/algorithm/set union") | computes the union of two sets (function template) | | [set\_intersection](set_intersection "cpp/algorithm/set intersection") | computes the intersection of two sets (function template) | | [ranges::set\_symmetric\_difference](ranges/set_symmetric_difference "cpp/algorithm/ranges/set symmetric difference") (C++20) | computes the symmetric difference between two sets (niebloid) | cpp std::find_end std::find\_end ============== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt1, class ForwardIt2 > ForwardIt1 find_end( ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last ); ``` | (until C++20) | | ``` template< class ForwardIt1, class ForwardIt2 > constexpr ForwardIt1 find_end( ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > ForwardIt1 find_end( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > ForwardIt1 find_end( ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last, BinaryPredicate p ); ``` | (until C++20) | | ``` template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > constexpr ForwardIt1 find_end( ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last, BinaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryPredicate > ForwardIt1 find_end( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last, BinaryPredicate p ); ``` | (4) | (since C++17) | Searches for the last occurrence of the sequence `[s_first, s_last)` in the range `[first, last)`. 1) Elements are compared using `operator==`. 3) Elements are compared using the given binary predicate `p`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | s\_first, s\_last | - | the range of elements to search for | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | binary predicate which returns ​`true` if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that objects of types `ForwardIt1` and `ForwardIt2` can be dereferenced and then implicitly converted to `Type1` and `Type2` respectively. ​ | | Type requirements | | -`ForwardIt1` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value Iterator to the beginning of last occurrence of the sequence `[s_first, s_last)` in range `[first, last)`. | | | | --- | --- | | If no such sequence is found, `last` is returned. | (until C++11) | | If `[s_first, s_last)` is empty or if no such sequence is found, `last` is returned. | (since C++11) | ### Complexity Does at most \(\scriptsize S\cdot(N-S+1)\)S·(N-S+1) comparisons where \(\scriptsize S\)S is `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first2, last2)` and \(\scriptsize N\)N is `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1)`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class ForwardIt1, class ForwardIt2> ForwardIt1 find_end(ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last) { if (s_first == s_last) return last; ForwardIt1 result = last; while (true) { ForwardIt1 new_result = std::search(first, last, s_first, s_last); if (new_result == last) { break; } else { result = new_result; first = result; ++first; } } return result; } ``` | | Second version | | ``` template<class ForwardIt1, class ForwardIt2, class BinaryPredicate> ForwardIt1 find_end(ForwardIt1 first, ForwardIt1 last, ForwardIt2 s_first, ForwardIt2 s_last, BinaryPredicate p) { if (s_first == s_last) return last; ForwardIt1 result = last; while (true) { ForwardIt1 new_result = std::search(first, last, s_first, s_last, p); if (new_result == last) { break; } else { result = new_result; first = result; ++first; } } return result; } ``` | ### Example The following code uses `find_end()` to search for two different sequences of numbers. ``` #include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> v{1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4}; std::vector<int>::iterator result; auto check = [&] { result == v.end() ? std::cout << "sequence not found\n" : std::cout << "last occurrence is at: " << std::distance(v.begin(), result) << "\n"; }; std::vector<int> t1{1, 2, 3}; result = std::find_end(v.begin(), v.end(), t1.begin(), t1.end()); check(); std::vector<int> t2{4, 5, 6}; result = std::find_end(v.begin(), v.end(), t2.begin(), t2.end()); check(); } ``` Output: ``` last occurrence is at: 8 sequence not found ``` ### See also | | | | --- | --- | | [search](search "cpp/algorithm/search") | searches for a range of elements (function template) | | [includes](includes "cpp/algorithm/includes") | returns true if one sequence is a subsequence of another (function template) | | [adjacent\_find](adjacent_find "cpp/algorithm/adjacent find") | finds the first two adjacent items that are equal (or satisfy a given predicate) (function template) | | [findfind\_iffind\_if\_not](find "cpp/algorithm/find") (C++11) | finds the first element satisfying specific criteria (function template) | | [find\_first\_of](find_first_of "cpp/algorithm/find first of") | searches for any one of a set of elements (function template) | | [search\_n](search_n "cpp/algorithm/search n") | searches a range for a number of consecutive copies of an element (function template) | | [ranges::find\_end](ranges/find_end "cpp/algorithm/ranges/find end") (C++20) | finds the last sequence of elements in a certain range (niebloid) |
programming_docs
cpp std::sample std::sample =========== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template< class PopulationIterator, class SampleIterator, class Distance, class URBG > SampleIterator sample( PopulationIterator first, PopulationIterator last, SampleIterator out, Distance n, URBG&& g ); ``` | | (since C++17) | Selects `n` elements from the sequence [first; last) (without replacement) such that each possible sample has equal probability of appearance, and writes those selected elements into the output iterator `out`. Random numbers are generated using the random number generator `g`. If `n` is greater than the number of elements in the sequence, selects `last-first` elements. The algorithm is stable (preserves the relative order of the selected elements) only if `PopulationIterator` meets the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). The behavior is undefined if `out` is in [first; last). ### Parameters | | | | | --- | --- | --- | | first, last | - | pair of iterators forming the range from which to make the sampling (the population) | | out | - | the output iterator where the samples are written | | n | - | number of samples to make | | g | - | the random number generator used as the source of randomness | | Type requirements | | -`PopulationIterator` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`SampleIterator` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`SampleIterator` must also meet the requirements of [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator") if `PopulationIterator` doesn't meet [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") | | -`PopulationIterator`'s value type must be writeable to `out` | | -`Distance` must be an integer type | | -`[std::remove\_reference\_t](http://en.cppreference.com/w/cpp/types/remove_reference)<URBG>` must meet the requirements of [UniformRandomBitGenerator](../named_req/uniformrandombitgenerator "cpp/named req/UniformRandomBitGenerator") and its return type must be convertible to `Distance` | ### Return value Returns a copy of `out` after the last sample that was output, that is, end of the sample range. ### Complexity Linear in `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first,last)`. ### Notes This function may implement selection sampling or reservoir sampling. | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | | --- | | [`__cpp_lib_sample`](../feature_test#Library_features "cpp/feature test") | ### Possible implementation See the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/14d8a5ae472ca5743016f37da2dd4770d83dea21/libstdc%2B%2B-v3/include/bits/stl_algo.h#L5743-L5869), [libc++](https://github.com/llvm/llvm-project/blob/f221d905b131158cbe3cbc4320d1ecd1376c3f22/libcxx/include/__algorithm/sample.h) and [MSVC STL](https://github.com/microsoft/STL/blob/472161105d596192194d4715ccad307c6c163b4a/stl/inc/algorithm#L4518-L4600). ### Example ``` #include <iostream> #include <random> #include <string> #include <iterator> #include <algorithm> int main() { std::string in = "hgfedcba", out; std::sample(in.begin(), in.end(), std::back_inserter(out), 5, std::mt19937{std::random_device{}()}); std::cout << "five random letters out of " << in << " : " << out << '\n'; } ``` Possible output: ``` five random letters out of hgfedcba: gfcba ``` ### See also | | | | --- | --- | | [random\_shuffleshuffle](random_shuffle "cpp/algorithm/random shuffle") (until C++17)(C++11) | randomly re-orders elements in a range (function template) | | [ranges::sample](ranges/sample "cpp/algorithm/ranges/sample") (C++20) | selects n random elements from a sequence (niebloid) | cpp std::partial_sort std::partial\_sort ================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class RandomIt > void partial_sort( RandomIt first, RandomIt middle, RandomIt last ); ``` | (until C++20) | | ``` template< class RandomIt > constexpr void partial_sort( RandomIt first, RandomIt middle, RandomIt last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class RandomIt > void partial_sort( ExecutionPolicy&& policy, RandomIt first, RandomIt middle, RandomIt last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class RandomIt, class Compare > void partial_sort( RandomIt first, RandomIt middle, RandomIt last, Compare comp ); ``` | (until C++20) | | ``` template< class RandomIt, class Compare > constexpr void partial_sort( RandomIt first, RandomIt middle, RandomIt last, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class RandomIt, class Compare > void partial_sort( ExecutionPolicy&& policy, RandomIt first, RandomIt middle, RandomIt last, Compare comp ); ``` | (4) | (since C++17) | Rearranges elements such that the range `[first, middle)` contains the sorted `middle − first` smallest elements in the range `[first, last)`. The order of equal elements is not guaranteed to be preserved. The order of the remaining elements in the range `[middle, last)` is unspecified. 1) Elements are compared using `operator<`. 3) Elements are compared using the given binary comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | random access iterators defining the range | | middle | - | random access iterator defining the one-past-the-end iterator of the range to be sorted | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `RandomIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`RandomIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). | | -The type of dereferenced `RandomIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). | ### Return value (none). ### Complexity Approximately (last-first)log(middle-first) applications of `cmp`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes #### Algorithm The algorithm used is typically *heap select* to select the smallest elements, and *heap sort* to sort the selected elements in the heap in ascending order. To select elements, a heap is used (see [heap](https://en.wikipedia.org/wiki/Heap_(data_structure)#Applications "enwiki:Heap (data structure)")). For example, for `operator<` as comparison function, *max-heap* is used to select `middle − first` smallest elements. [Heap sort](https://en.wikipedia.org/wiki/Heapsort "enwiki:Heapsort") is used after selection to sort `[first, middle)` selected elements (see `[std::sort\_heap](sort_heap "cpp/algorithm/sort heap")`). #### Intended use `std::partial_sort` algorithms are intended to be used for *small constant numbers* of `[first, middle)` selected elements. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L1915) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L5025). | First version | | --- | | ``` template<typename RandomIt, typename Compare> void partial_sort(RandomIt first, RandomIt middle, RandomIt last, Compare comp) { if (first == middle) return; std::make_heap(first, middle, comp); for (auto it {middle}; it != last; ++it) { if (comp(*it, *first)) { std::pop_heap(first, middle, comp); std::iter_swap(middle - 1, it); std::push_heap(first, middle, comp); } } std::sort_heap(first, middle, comp); } ``` | | Second version | | ``` namespace impl { template<typename RandomIt, typename Compare = std::less<typename std::iterator_traits<RandomIt>::value_type>> void sift_down(RandomIt begin, RandomIt end, const Compare &comp = {}) { // sift down element at 'begin' const auto length = static_cast<size_t>(end - begin); size_t current = 0; size_t next = 2; while (next < length) { if (comp(*(begin + next), *(begin + (next - 1)))) --next; if (!comp(*(begin + current), *(begin + next))) return; std::iter_swap(begin + current, begin + next); current = next; next = 2 * current + 2; } --next; if (next < length && comp(*(begin + current), *(begin + next))) std::iter_swap(begin + current, begin + next); } template<typename RandomIt, typename Compare = std::less<typename std::iterator_traits<RandomIt>::value_type>> void heap_select(RandomIt begin, RandomIt middle, RandomIt end, const Compare &comp = {}) { std::make_heap(begin, middle, comp); for (auto i = middle; i != end; ++i) if (comp(*i, *begin)) { std::iter_swap(begin, i); sift_down(begin, middle, comp); } } } // namespace impl template<typename RandomIt, typename Compare = std::less<typename std::iterator_traits<RandomIt>::value_type>> void partial_sort(RandomIt begin, RandomIt middle, RandomIt end, Compare comp = {}) { impl::heap_select(begin, middle, end, comp); std::sort_heap(begin, middle, comp); } ``` | Note that the first version may be less efficient in practice. ### Example ``` #include <algorithm> #include <array> #include <functional> #include <iostream> auto print = [](auto const& s, int middle) { for (int a : s) { std::cout << a << ' '; } std::cout << '\n'; if (middle > 0) { while (middle-->0) { std::cout << "──"; } std::cout << '^'; } else if (middle < 0) { for (auto i = s.size() + middle; --i; std::cout << " "); for (std::cout << '^'; middle++ < 0; std::cout << "──"); } std::cout << '\n'; }; int main() { std::array<int, 10> s{5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; print(s, 0); std::partial_sort(s.begin(), s.begin() + 3, s.end()); print(s, 3); std::partial_sort(s.rbegin(), s.rbegin() + 4, s.rend()); print(s, -4); std::partial_sort(s.rbegin(), s.rbegin() + 5, s.rend(), std::greater{}); print(s, -5); } ``` Possible output: ``` 5 7 4 2 8 6 1 9 0 3 0 1 2 7 8 6 5 9 4 3 ──────^ 4 5 6 7 8 9 3 2 1 0 ^──────── 4 3 2 1 0 5 6 7 8 9 ^────────── ``` ### See also | | | | --- | --- | | [nth\_element](nth_element "cpp/algorithm/nth element") | partially sorts the given range making sure that it is partitioned by the given element (function template) | | [partial\_sort\_copy](partial_sort_copy "cpp/algorithm/partial sort copy") | copies and partially sorts a range of elements (function template) | | [stable\_sort](stable_sort "cpp/algorithm/stable sort") | sorts a range of elements while preserving order between equal elements (function template) | | [sort](sort "cpp/algorithm/sort") | sorts a range into ascending order (function template) | | [ranges::partial\_sort](ranges/partial_sort "cpp/algorithm/ranges/partial sort") (C++20) | sorts the first N elements of a range (niebloid) | cpp std::reverse std::reverse ============ | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class BidirIt > void reverse( BidirIt first, BidirIt last ); ``` | (until C++20) | | ``` template< class BidirIt > constexpr void reverse( BidirIt first, BidirIt last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class BidirIt > void reverse( ExecutionPolicy&& policy, BidirIt first, BidirIt last ); ``` | (2) | (since C++17) | 1) Reverses the order of the elements in the range `[first, last)`. Behaves as if applying `[std::iter\_swap](iter_swap "cpp/algorithm/iter swap")` to every pair of iterators `first+i, (last-i) - 1` for each non-negative `i < (last-first)/2`. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to reverse | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | Type requirements | | -`BidirIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | ### Return value (none). ### Complexity Exactly `(last - first)/2` swaps. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes Implementations (e.g. [MSVC STL](https://github.com/microsoft/STL/blob/main/stl/src/vector_algorithms.cpp)) may enable vectorization when the iterator type satisfies [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") and swapping its value type calls neither non-trivial special member function nor [ADL](../language/adl "cpp/language/adl")-found `swap`. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/14d8a5ae472ca5743016f37da2dd4770d83dea21/libstdc%2B%2B-v3/include/bits/stl_algo.h#L1087-L1152), [libc++](https://github.com/llvm/llvm-project/blob/6adbc83ee9e46b476e0f75d5671c3a21f675a936/libcxx/include/__algorithm/reverse.h), and [MSVC STL](https://github.com/microsoft/STL/blob/472161105d596192194d4715ccad307c6c163b4a/stl/inc/xutility#L5335-L5370). | | | --- | | ``` template<class BidirIt> constexpr // since C++20 void reverse(BidirIt first, BidirIt last) { using iter_cat = typename std::iterator_traits<BidirIt>::iterator_category; // Tag dispatch, e.g. calling reverse_impl(first, last, iter_cat()), // can be used in C++14 and earlier modes. if constexpr (std::is_base_of_v<std::random_access_iterator_tag, iter_cat>) { if (first == last) return; for (--last; first < last; (void)++first, --last) { std::iter_swap(first, last); } } else { while ((first != last) && (first != --last)) { std::iter_swap(first++, last); } } } ``` | ### Example ``` #include <vector> #include <iostream> #include <iterator> #include <algorithm> int main() { std::vector<int> v{1, 2, 3}; std::reverse(v.begin(), v.end()); for(auto e : v) std::cout << e; std::cout << '\n'; int a[] = {4, 5, 6, 7}; std::reverse(std::begin(a), std::end(a)); for(auto e : a) std::cout << e; } ``` Output: ``` 321 7654 ``` ### See also | | | | --- | --- | | [reverse\_copy](reverse_copy "cpp/algorithm/reverse copy") | creates a copy of a range that is reversed (function template) | | [ranges::reverse](ranges/reverse "cpp/algorithm/ranges/reverse") (C++20) | reverses the order of elements in a range (niebloid) | cpp std::swap std::swap ========= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | (until C++11) | | --- | --- | --- | | Defined in header `[<utility>](../header/utility "cpp/header/utility")` | | (since C++11) | | Defined in header `[<string\_view>](../header/string_view "cpp/header/string view")` | | (since C++17) | | | (1) | | | ``` template< class T > void swap( T& a, T& b ); ``` | (until C++11) | | ``` template< class T > void swap( T& a, T& b ) noexcept(/* see below */); ``` | (since C++11) (until C++20) | | ``` template< class T > constexpr void swap( T& a, T& b ) noexcept(/* see below */); ``` | (since C++20) | | | (2) | | | ``` template< class T2, std::size_t N > void swap( T2 (&a)[N], T2 (&b)[N]) noexcept(/* see below */); ``` | (since C++11) (until C++20) | | ``` template< class T2, std::size_t N > constexpr void swap( T2 (&a)[N], T2 (&b)[N]) noexcept(/* see below */); ``` | (since C++20) | Exchanges the given values. 1) Swaps the values `a` and `b`. This overload does not participate in overload resolution unless `[std::is\_move\_constructible\_v](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T> && [std::is\_move\_assignable\_v](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T>` is `true`. (since C++17) 2) Swaps the arrays `a` and `b`. In effect calls `[std::swap\_ranges](http://en.cppreference.com/w/cpp/algorithm/swap_ranges)(a, a+N, b)`. This overload does not participate in overload resolution unless `[std::is\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<T2>` is `true`. (since C++17) ### Parameters | | | | | --- | --- | --- | | a, b | - | the values to be swapped | | Type requirements | | -`T` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). | | -`T2` must meet the requirements of [Swappable](../named_req/swappable "cpp/named req/Swappable"). | ### Return value (none). ### Exceptions 1) | | | | --- | --- | | (none). | (until C++11) | | [`noexcept`](../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept( [std::is\_nothrow\_move\_constructible](http://en.cppreference.com/w/cpp/types/is_move_constructible)<T>::value && [std::is\_nothrow\_move\_assignable](http://en.cppreference.com/w/cpp/types/is_move_assignable)<T>::value. )` | (since C++11) | 2) | | | | --- | --- | | [`noexcept`](../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept(noexcept(swap(*a, *b)))` The lookup for the identifier `swap` in the exception specification finds this function template in addition to anything found by the usual lookup rules, making the exception specification equivalent to C++17 `[std::is\_nothrow\_swappable](../types/is_swappable "cpp/types/is swappable")`. | (since C++11)(until C++17) | | [`noexcept`](../language/noexcept_spec "cpp/language/noexcept spec") specification: `noexcept([std::is\_nothrow\_swappable\_v](http://en.cppreference.com/w/cpp/types/is_swappable)<T2>)` | (since C++17) | ### Complexity 1) Constant 2) Linear in `N` ### Specializations | | | | --- | --- | | `std::swap` may be [specialized in namespace std](../language/extending_std "cpp/language/extending std") for program-defined types, but such specializations are not found by [ADL](../language/adl "cpp/language/adl") (the namespace std is not the associated namespace for the program-defined type). | (until C++20) | The expected way to make a program-defined type swappable is to provide a non-member function swap in the same namespace as the type: see [Swappable](../named_req/swappable "cpp/named req/Swappable") for details. The following overloads are already provided by the standard library: | | | | --- | --- | | [std::swap(std::pair)](../utility/pair/swap2 "cpp/utility/pair/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::tuple)](../utility/tuple/swap2 "cpp/utility/tuple/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::shared\_ptr)](../memory/shared_ptr/swap2 "cpp/memory/shared ptr/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::weak\_ptr)](../memory/weak_ptr/swap2 "cpp/memory/weak ptr/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::unique\_ptr)](../memory/unique_ptr/swap2 "cpp/memory/unique ptr/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::function)](../utility/functional/function/swap2 "cpp/utility/functional/function/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_string)](../string/basic_string/swap2 "cpp/string/basic string/swap2") | specializes the `std::swap` algorithm (function template) | | [std::swap(std::array)](../container/array/swap2 "cpp/container/array/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::deque)](../container/deque/swap2 "cpp/container/deque/swap2") | specializes the `std::swap` algorithm (function template) | | [std::swap(std::forward\_list)](../container/forward_list/swap2 "cpp/container/forward list/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::list)](../container/list/swap2 "cpp/container/list/swap2") | specializes the `std::swap` algorithm (function template) | | [std::swap(std::vector)](../container/vector/swap2 "cpp/container/vector/swap2") | specializes the `std::swap` algorithm (function template) | | [std::swap(std::map)](../container/map/swap2 "cpp/container/map/swap2") | specializes the `std::swap` algorithm (function template) | | [std::swap(std::multimap)](../container/multimap/swap2 "cpp/container/multimap/swap2") | specializes the `std::swap` algorithm (function template) | | [std::swap(std::set)](../container/set/swap2 "cpp/container/set/swap2") | specializes the `std::swap` algorithm (function template) | | [std::swap(std::multiset)](../container/multiset/swap2 "cpp/container/multiset/swap2") | specializes the `std::swap` algorithm (function template) | | [std::swap(std::unordered\_map)](../container/unordered_map/swap2 "cpp/container/unordered map/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::unordered\_multimap)](../container/unordered_multimap/swap2 "cpp/container/unordered multimap/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::unordered\_set)](../container/unordered_set/swap2 "cpp/container/unordered set/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::unordered\_multiset)](../container/unordered_multiset/swap2 "cpp/container/unordered multiset/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::queue)](../container/queue/swap2 "cpp/container/queue/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::priority\_queue)](../container/priority_queue/swap2 "cpp/container/priority queue/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::stack)](../container/stack/swap2 "cpp/container/stack/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::valarray)](../numeric/valarray/swap2 "cpp/numeric/valarray/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_stringbuf)](../io/basic_stringbuf/swap2 "cpp/io/basic stringbuf/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_istringstream)](../io/basic_istringstream/swap2 "cpp/io/basic istringstream/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_ostringstream)](../io/basic_ostringstream/swap2 "cpp/io/basic ostringstream/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_stringstream)](../io/basic_stringstream/swap2 "cpp/io/basic stringstream/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_filebuf)](../io/basic_filebuf/swap2 "cpp/io/basic filebuf/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_ifstream)](../io/basic_ifstream/swap2 "cpp/io/basic ifstream/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_ofstream)](../io/basic_ofstream/swap2 "cpp/io/basic ofstream/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_fstream)](../io/basic_fstream/swap2 "cpp/io/basic fstream/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_syncbuf)](../io/basic_syncbuf/swap2 "cpp/io/basic syncbuf/swap2") (C++20) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_spanbuf)](../io/basic_spanbuf/swap2 "cpp/io/basic spanbuf/swap2") (C++23) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_ispanstream)](../io/basic_ispanstream/swap2 "cpp/io/basic ispanstream/swap2") (C++23) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_ospanstream)](../io/basic_ospanstream/swap2 "cpp/io/basic ospanstream/swap2") (C++23) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_spanstream)](../io/basic_spanstream/swap2 "cpp/io/basic spanstream/swap2") (C++23) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_regex)](../regex/basic_regex/swap2 "cpp/regex/basic regex/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::match\_results)](../regex/match_results/swap2 "cpp/regex/match results/swap2") (C++11) | specializes the **`std::swap`** algorithm (function template) | | [std::swap(std::thread)](../thread/thread/swap2 "cpp/thread/thread/swap2") (C++11) | specializes the `std::swap` algorithm (function) | | [std::swap(std::unique\_lock)](../thread/unique_lock/swap2 "cpp/thread/unique lock/swap2") (C++11) | specialization of `std::swap` for `unique_lock` (function template) | | [std::swap(std::shared\_lock)](../thread/shared_lock/swap2 "cpp/thread/shared lock/swap2") (C++14) | specialization of `std::swap` for `shared_lock` (function template) | | [std::swap(std::promise)](../thread/promise/swap2 "cpp/thread/promise/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::packaged\_task)](../thread/packaged_task/swap2 "cpp/thread/packaged task/swap2") (C++11) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::optional)](../utility/optional/swap2 "cpp/utility/optional/swap2") (C++17) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::any)](../utility/any/swap2 "cpp/utility/any/swap2") (C++17) | specializes the `std::swap` algorithm (function) | | [std::swap(std::variant)](../utility/variant/swap2 "cpp/utility/variant/swap2") (C++17) | specializes the `std::swap` algorithm (function template) | | [std::swap(std::basic\_stacktrace)](../utility/basic_stacktrace/swap2 "cpp/utility/basic stacktrace/swap2") (C++23) | specializes the `std::swap` algorithm (function template) | | [swap(std::filesystem::path)](../filesystem/path/swap2 "cpp/filesystem/path/swap2") (C++17) | swaps two paths (function) | | [swap(std::expected)](../utility/expected/swap2 "cpp/utility/expected/swap2") (C++23) | specializes the `std::swap` algorithm (function) | | [swap(std::jthread)](../thread/jthread/swap2 "cpp/thread/jthread/swap2") (C++20) | specializes the `std::swap` algorithm (function) | | [swap(std::move\_only\_function)](../utility/functional/move_only_function/swap2 "cpp/utility/functional/move only function/swap2") (C++23) | overloads the `std::swap` algorithm (function) | | [swap(std::stop\_source)](../thread/stop_source/swap2 "cpp/thread/stop source/swap2") (C++20) | specializes the `std::swap` algorithm (function) | | [swap(std::stop\_token)](../thread/stop_token/swap2 "cpp/thread/stop token/swap2") (C++20) | specializes the `std::swap` algorithm (function) | ### Example ``` #include <algorithm> #include <iostream> namespace Ns { class A { int id{}; friend void swap(A& lhs, A& rhs) { std::cout << "swap(" << lhs << ", " << rhs << ")\n"; std::swap(lhs.id, rhs.id); } friend std::ostream& operator<< (std::ostream& os, A const& a) { return os << "A::id=" << a.id; } public: A(int i) : id{i} { } A(A const&) = delete; A& operator = (A const&) = delete; }; } int main() { int a = 5, b = 3; std::cout << a << ' ' << b << '\n'; std::swap(a,b); std::cout << a << ' ' << b << '\n'; Ns::A p{6}, q{9}; std::cout << p << ' ' << q << '\n'; // std::swap(p, q); // error, type requirements are not satisfied swap(p, q); // OK, ADL finds the appropriate friend `swap` std::cout << p << ' ' << q << '\n'; } ``` Output: ``` 5 3 3 5 A::id=6 A::id=9 swap(A::id=6, A::id=9) A::id=9 A::id=6 ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 2554](https://cplusplus.github.io/LWG/issue2554) | C++11 | swapping multi-dimensional arrays can never be `noexcept` due to name lookup problems | made to work | ### See also | | | | --- | --- | | [ranges::swap](../utility/ranges/swap "cpp/utility/ranges/swap") (C++20) | swaps the values of two objects (customization point object) | | [iter\_swap](iter_swap "cpp/algorithm/iter swap") | swaps the elements pointed to by two iterators (function template) | | [swap\_ranges](swap_ranges "cpp/algorithm/swap ranges") | swaps two ranges of elements (function template) | | [exchange](../utility/exchange "cpp/utility/exchange") (C++14) | replaces the argument with a new value and returns its previous value (function template) |
programming_docs
cpp std::transform_reduce std::transform\_reduce ====================== | Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt1, class InputIt2, class T > T transform_reduce( InputIt1 first1, InputIt1 last1, InputIt2 first2, T init ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt1, class InputIt2, class T > constexpr T transform_reduce( InputIt1 first1, InputIt1 last1, InputIt2 first2, T init ); ``` | (since C++20) | | | (2) | | | ``` template< class InputIt1, class InputIt2, class T, class BinaryReductionOp, class BinaryTransformOp > T transform_reduce( InputIt1 first1, InputIt1 last1, InputIt2 first2, T init, BinaryReductionOp reduce, BinaryTransformOp transform ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt1, class InputIt2, class T, class BinaryReductionOp, class BinaryTransformOp > constexpr T transform_reduce( InputIt1 first1, InputIt1 last1, InputIt2 first2, T init, BinaryReductionOp reduce, BinaryTransformOp transform ); ``` | (since C++20) | | | (3) | | | ``` template< class InputIt, class T, class BinaryReductionOp, class UnaryTransformOp > T transform_reduce( InputIt first, InputIt last, T init, BinaryReductionOp reduce, UnaryTransformOp transform ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt, class T, class BinaryReductionOp, class UnaryTransformOp > constexpr T transform_reduce( InputIt first, InputIt last, T init, BinaryReductionOp reduce, UnaryTransformOp transform ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T > T transform_reduce( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, T init ); ``` | (4) | (since C++17) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T, class BinaryReductionOp, class BinaryTransformOp > T transform_reduce( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, T init, BinaryReductionOp reduce, BinaryTransformOp transform ); ``` | (5) | (since C++17) | | ``` template< class ExecutionPolicy, class ForwardIt, class T, class BinaryReductionOp, class UnaryTransformOp > T transform_reduce( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, T init, BinaryReductionOp reduce, UnaryTransformOp transform ); ``` | (6) | (since C++17) | 1) Equivalent to `std::transform\_reduce(first1, last1, first2, init, [std::plus](http://en.cppreference.com/w/cpp/utility/functional/plus)<>(), [std::multiplies](http://en.cppreference.com/w/cpp/utility/functional/multiplies)<>());`, effectively parallelized version of the default `[std::inner\_product](inner_product "cpp/algorithm/inner product")` 2) Applies `transform` to each pair of elements from the ranges `[first; last)` and the range starting at `first2` and reduces the results (possibly permuted and aggregated in unspecified manner) along with the initial value `init` over `reduce` 3) Applies `transform` to each element in the range [first; last) and reduces the results (possibly permuted and aggregated in unspecified manner) along with the initial value `init` over `reduce`. 4-6) Same as (1-3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. The behavior is non-deterministic if `reduce` is not associative or not commutative. The behavior is undefined if `reduce`, or `transform` modifies any element or invalidates any iterator in the input ranges, including their end iterators. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to apply the algorithm to | | init | - | the initial value of the generalized sum | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | reduce | - | binary [FunctionObject](../named_req/functionobject "cpp/named req/FunctionObject") that will be applied in unspecified order to the results of `transform`, the results of other `reduce` and `init`. | | transform | - | unary or binary [FunctionObject](../named_req/functionobject "cpp/named req/FunctionObject") that will be applied to each element of the input range(s). The return type must be acceptable as input to `reduce` | | Type requirements | | -`T` must meet the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible") in order to use overloads (3,6). and the result of the expressions `reduce(init, transform(*first))`, `reduce(transform(*first), init)`, `reduce(init, init)`, and `reduce(transform(*first), transform(*first))` must be convertible to T | | -`T` must meet the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible") in order to use overloads (2,5). and the result of the expressions `reduce(init, transform(*first1, *first2))`, `reduce(transform(*first1, *first2), init)`, `reduce(init, init)`, and `reduce(transform(*first1, *first2), transform(*first1, *first2))` must be convertible to T | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value 2) Generalized sum of `init` and `transform(*first,*first2)`, `transform(*(first+1),*(first2+1))`, ..., over `reduce` 3) Generalized sum of `init` and `transform(*first)`, `transform(*(first+1))`, ... `transform(*(last-1))` over `reduce`, where generalized sum GSUM(op, a 1, ..., a N) is defined as follows: * if N=1, a 1 * if N > 1, op(GSUM(op, b 1, ..., b K), GSUM(op, b M, ..., b N)) where + b 1, ..., b N may be any permutation of a1, ..., aN and + 1 < K+1 = M ≤ N in other words, the results of transform or of reduce may be grouped and arranged in arbitrary order. ### Complexity 1,2,4,5) O(last1 - first1) applications each of `reduce` and `transform`. 3,6) O(last - first) applications each of `transform` and `reduce`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes In the unary-binary overload (3,6), `transform` is not applied to `init`. If `first == last` or `first1 == last1`, `init` is returned, unmodified. ### Example `transform_reduce` can be used to parallelize `[std::inner\_product](inner_product "cpp/algorithm/inner product")`: ``` #include <algorithm> #include <execution> #include <iostream> #include <iterator> #include <locale> #include <numeric> #include <vector> // to parallelize non-associate accumulative operation, you'd better choose // transform_reduce instead of reduce; e.g., a + b * b != b + a * a void print_sum_squared(long const num) { std::cout.imbue(std::locale{"en_US.UTF8"}); std::cout << "num = " << num << '\n'; // create an immutable vector filled with pattern: 1,2,3,4, 1,2,3,4 ... const std::vector<long> v { [n = num * 4] { std::vector<long> v; v.reserve(n); std::generate_n(std::back_inserter(v), n, [i=0]() mutable { return 1 + i++ % 4; }); return v; }()}; auto squared_sum = [](auto sum, auto val) { return sum + val * val; }; auto sum1 = std::accumulate(v.cbegin(), v.cend(), 0L, squared_sum); std::cout << "accumulate(): " << sum1 << '\n'; auto sum2 = std::reduce(std::execution::par, v.cbegin(), v.cend(), 0L, squared_sum); std::cout << "reduce(): " << sum2 << '\n'; auto sum3 = std::transform_reduce(std::execution::par, v.cbegin(), v.cend(), 0L, std::plus{}, [](auto val) { return val * val; }); std::cout << "transform_reduce(): " << sum3 << '\n'; std::cout << '\n'; } int main() { print_sum_squared(1); print_sum_squared(1'000); print_sum_squared(1'000'000); } ``` Possible output: ``` num = 1 accumulate(): 30 reduce(): 30 transform_reduce(): 30 num = 1,000 accumulate(): 30,000 reduce(): -7,025,681,278,312,630,348 transform_reduce(): 30,000 num = 1,000,000 accumulate(): 30,000,000 reduce(): -5,314,886,882,370,003,032 transform_reduce(): 30,000,000 ``` ### See also | | | | --- | --- | | [accumulate](accumulate "cpp/algorithm/accumulate") | sums up a range of elements (function template) | | [transform](transform "cpp/algorithm/transform") | applies a function to a range of elements, storing results in a destination range (function template) | | [reduce](reduce "cpp/algorithm/reduce") (C++17) | similar to `[std::accumulate](accumulate "cpp/algorithm/accumulate")`, except out of order (function template) | cpp std::remove, std::remove_if std::remove, std::remove\_if ============================ | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt, class T > ForwardIt remove( ForwardIt first, ForwardIt last, const T& value ); ``` | (until C++20) | | ``` template< class ForwardIt, class T > constexpr ForwardIt remove( ForwardIt first, ForwardIt last, const T& value ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class T > ForwardIt remove( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, const T& value ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class ForwardIt, class UnaryPredicate > ForwardIt remove_if( ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | (until C++20) | | ``` template< class ForwardIt, class UnaryPredicate > constexpr ForwardIt remove_if( ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate > ForwardIt remove_if( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | (4) | (since C++17) | Removes all elements satisfying specific criteria from the range `[first, last)` and returns a past-the-end iterator for the new end of the range. 1) Removes all elements that are equal to `value`, using `operator==` to compare them. 3) Removes all elements for which predicate `p` returns `true`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. Removing is done by shifting (by means of copy assignment (until C++11)move assignment (since C++11)) the elements in the range in such a way that the elements that are not to be removed appear in the beginning of the range. Relative order of the elements that remain is preserved and the *physical* size of the container is unchanged. Iterators pointing to an element between the new *logical* end and the *physical* end of the range are still dereferenceable, but the elements themselves have unspecified values (as per [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") post-condition). ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to process | | value | - | the value of elements to remove | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | unary predicate which returns ​`true` if the element should be removed. The expression `p(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `VT`, where `VT` is the value type of `ForwardIt`, regardless of [value category](../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `VT&`is not allowed, nor is `VT` unless for `VT` a move is equivalent to a copy (since C++11). ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -The type of dereferenced `ForwardIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable"). | | -`UnaryPredicate` must meet the requirements of [Predicate](../named_req/predicate "cpp/named req/Predicate"). | ### Return value Past-the-end iterator for the new range of values (if this is not `end`, then it points to an unspecified value, and so do iterators to any values between this iterator and `end`). ### Complexity Exactly `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` applications of the predicate. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes A call to `remove` is typically followed by a call to a container's `erase` method, which erases the unspecified values and reduces the *physical* size of the container to match its new *logical* size. These two invocations together constitute a so-called [*Erase–remove* idiom](https://en.wikipedia.org/wiki/Erase-remove_idiom "enwiki:Erase-remove idiom"), which can be achieved by the free function `[std::erase](../container/vector/erase2 "cpp/container/vector/erase2")` that has overloads for all standard *sequence* containers, or `[std::erase\_if](../container/vector/erase2 "cpp/container/vector/erase2")` that has overloads for *all* standard containers (since C++20). The similarly-named container member functions [`list::remove`](../container/list/remove "cpp/container/list/remove"), [`list::remove_if`](../container/list/remove "cpp/container/list/remove"), [`forward_list::remove`](../container/forward_list/remove "cpp/container/forward list/remove"), and [`forward_list::remove_if`](../container/forward_list/remove "cpp/container/forward list/remove") erase the removed elements. These algorithms cannot be used with associative containers such as `[std::set](../container/set "cpp/container/set")` and `[std::map](../container/map "cpp/container/map")` because their iterator types do not dereference to [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") types (the keys in these containers are not modifiable). The standard library also defines an overload of [`std::remove`](../io/c/remove "cpp/io/c/remove") in [`<cstdio>`](../header/cstdio "cpp/header/cstdio"), which takes a `const char*` and is used to delete files. Because `std::remove` takes `value` by reference, it can have unexpected behavior if it is a reference to an element of the range `[first, last)`. ### Possible implementation | First version | | --- | | ``` template< class ForwardIt, class T > ForwardIt remove(ForwardIt first, ForwardIt last, const T& value) { first = std::find(first, last, value); if (first != last) for(ForwardIt i = first; ++i != last; ) if (!(*i == value)) *first++ = std::move(*i); return first; } ``` | | Second version | | ``` template<class ForwardIt, class UnaryPredicate> ForwardIt remove_if(ForwardIt first, ForwardIt last, UnaryPredicate p) { first = std::find_if(first, last, p); if (first != last) for(ForwardIt i = first; ++i != last; ) if (!p(*i)) *first++ = std::move(*i); return first; } ``` | ### Examples The following code removes all spaces from a string by shifting all non-space characters to the left and then erasing the extra. This is an example of [erase-remove idiom](https://en.wikipedia.org/wiki/Erase-remove_idiom "enwiki:Erase-remove idiom"). ``` #include <algorithm> #include <string> #include <string_view> #include <iostream> #include <cctype> int main() { std::string str1 = "Text with some spaces"; auto noSpaceEnd = std::remove(str1.begin(), str1.end(), ' '); // The spaces are removed from the string only logically. // Note, we use view, the original string is still not shrunk: std::cout << std::string_view(str1.begin(), noSpaceEnd) << " size: " << str1.size() << '\n'; str1.erase(noSpaceEnd, str1.end()); // The spaces are removed from the string physically. std::cout << str1 << " size: " << str1.size() << '\n'; std::string str2 = "Text\n with\tsome \t whitespaces\n\n"; str2.erase(std::remove_if(str2.begin(), str2.end(), [](unsigned char x){return std::isspace(x);}), str2.end()); std::cout << str2 << '\n'; } ``` Output: ``` Textwithsomespaces size: 23 Textwithsomespaces size: 18 Textwithsomewhitespaces ``` ### See also | | | | --- | --- | | [remove\_copyremove\_copy\_if](remove_copy "cpp/algorithm/remove copy") | copies a range of elements omitting those that satisfy specific criteria (function template) | | [unique](unique "cpp/algorithm/unique") | removes consecutive duplicate elements in a range (function template) | | [ranges::removeranges::remove\_if](ranges/remove "cpp/algorithm/ranges/remove") (C++20)(C++20) | removes elements satisfying specific criteria (niebloid) | cpp std::partial_sum std::partial\_sum ================= | Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class OutputIt > OutputIt partial_sum( InputIt first, InputIt last, OutputIt d_first ); ``` | (until C++20) | | ``` template< class InputIt, class OutputIt > constexpr OutputIt partial_sum( InputIt first, InputIt last, OutputIt d_first ); ``` | (since C++20) | | | (2) | | | ``` template< class InputIt, class OutputIt, class BinaryOperation > OutputIt partial_sum( InputIt first, InputIt last, OutputIt d_first, BinaryOperation op ); ``` | (until C++20) | | ``` template< class InputIt, class OutputIt, class BinaryOperation > constexpr OutputIt partial_sum( InputIt first, InputIt last, OutputIt d_first, BinaryOperation op ); ``` | (since C++20) | Computes the partial sums of the elements in the subranges of the range `[first, last)` and writes them to the range beginning at `d_first`. The first version uses `operator+` to sum up the elements, the second version uses the given binary function `op`, both applying [`std::move`](../utility/move "cpp/utility/move") to their operands on the left hand side (since C++20). Equivalent operation: ``` *(d_first) = *first; *(d_first+1) = *first + *(first+1); *(d_first+2) = *first + *(first+1) + *(first+2); *(d_first+3) = *first + *(first+1) + *(first+2) + *(first+3); ... ``` | | | | --- | --- | | `op` must not have side effects. | (until C++11) | | `op` must not invalidate any iterators, including the end iterators, or modify any elements of the range involved. | (since C++11) | ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to sum | | d\_first | - | the beginning of the destination range; may be equal to `first` | | op | - | binary operation function object that will be applied. The signature of the function should be equivalent to the following: `Ret fun(const Type1 &a, const Type2 &b);` The signature does not need to have `const &`. The type `Type1` must be such that an object of type `iterator_traits<InputIt>::value_type` can be implicitly converted to `Type1`. The type `Type2` must be such that an object of type `InputIt` can be dereferenced and then implicitly converted to `Type2`. The type `Ret` must be such that an object of type `iterator_traits<InputIt>::value_type` can be assigned a value of type `Ret`. ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | ### Return value Iterator to the element past the last element written. ### Complexity Exactly `(last - first) - 1` applications of the binary operation. ### Possible implementation | First version | | --- | | ``` template<class InputIt, class OutputIt> constexpr // since C++20 OutputIt partial_sum(InputIt first, InputIt last, OutputIt d_first) { if (first == last) return d_first; typename std::iterator_traits<InputIt>::value_type sum = *first; *d_first = sum; while (++first != last) { sum = std::move(sum) + *first; // std::move since C++20 *++d_first = sum; } return ++d_first; // or, since C++14: // return std::partial_sum(first, last, d_first, std::plus<>()); } ``` | | Second version | | ``` template<class InputIt, class OutputIt, class BinaryOperation> constexpr // since C++20 OutputIt partial_sum(InputIt first, InputIt last, OutputIt d_first, BinaryOperation op) { if (first == last) return d_first; typename std::iterator_traits<InputIt>::value_type sum = *first; *d_first = sum; while (++first != last) { sum = op(std::move(sum), *first); // std::move since C++20 *++d_first = sum; } return ++d_first; } ``` | ### Example ``` #include <numeric> #include <vector> #include <iostream> #include <iterator> #include <functional> int main() { std::vector<int> v = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2}; // or std::vector<int>v(10, 2); std::cout << "The first 10 even numbers are: "; std::partial_sum(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; std::partial_sum(v.begin(), v.end(), v.begin(), std::multiplies<int>()); std::cout << "The first 10 powers of 2 are: "; for (auto n : v) { std::cout << n << " "; } std::cout << '\n'; } ``` Output: ``` The first 10 even numbers are: 2 4 6 8 10 12 14 16 18 20 The first 10 powers of 2 are: 2 4 8 16 32 64 128 256 512 1024 ``` ### See also | | | | --- | --- | | [adjacent\_difference](adjacent_difference "cpp/algorithm/adjacent difference") | computes the differences between adjacent elements in a range (function template) | | [accumulate](accumulate "cpp/algorithm/accumulate") | sums up a range of elements (function template) | | [inclusive\_scan](inclusive_scan "cpp/algorithm/inclusive scan") (C++17) | similar to `std::partial_sum`, includes the ith input element in the ith sum (function template) | | [exclusive\_scan](exclusive_scan "cpp/algorithm/exclusive scan") (C++17) | similar to `std::partial_sum`, excludes the ith input element from the ith sum (function template) |
programming_docs
cpp std::count, std::count_if std::count, std::count\_if ========================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class T > typename iterator_traits<InputIt>::difference_type count( InputIt first, InputIt last, const T& value ); ``` | (until C++20) | | ``` template< class InputIt, class T > constexpr typename iterator_traits<InputIt>::difference_type count( InputIt first, InputIt last, const T& value ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class T > typename iterator_traits<ForwardIt>::difference_type count( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, const T& value ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt, class UnaryPredicate > typename iterator_traits<InputIt>::difference_type count_if( InputIt first, InputIt last, UnaryPredicate p ); ``` | (until C++20) | | ``` template< class InputIt, class UnaryPredicate > constexpr typename iterator_traits<InputIt>::difference_type count_if( InputIt first, InputIt last, UnaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate > typename iterator_traits<ForwardIt>::difference_type count_if( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | (4) | (since C++17) | Returns the number of elements in the range `[first, last)` satisfying specific criteria. 1) counts the elements that are equal to `value`. 3) counts elements for which predicate `p` returns `true`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | value | - | the value to search for | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | unary predicate which returns ​`true` for the required elements. The expression `p(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `VT`, where `VT` is the value type of `InputIt`, regardless of [value category](../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `VT&`is not allowed, nor is `VT` unless for `VT` a move is equivalent to a copy (since C++11). ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value number of elements satisfying the condition. ### Complexity exactly `last` - `first` comparisons / applications of the predicate. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes For the number of elements in the range `[first, last)` without any additional criteria, see `[std::distance](../iterator/distance "cpp/iterator/distance")`. ### Possible implementation See also the implementations of `count` in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L4056) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L1171). See also the implementations of `count_if` in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L4079) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L1186). | First version | | --- | | ``` template<class InputIt, class T> typename iterator_traits<InputIt>::difference_type count(InputIt first, InputIt last, const T& value) { typename iterator_traits<InputIt>::difference_type ret = 0; for (; first != last; ++first) { if (*first == value) { ret++; } } return ret; } ``` | | Second version | | ``` template<class InputIt, class UnaryPredicate> typename iterator_traits<InputIt>::difference_type count_if(InputIt first, InputIt last, UnaryPredicate p) { typename iterator_traits<InputIt>::difference_type ret = 0; for (; first != last; ++first) { if (p(*first)) { ret++; } } return ret; } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <array> int main() { constexpr std::array v = { 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 }; std::cout << "v: "; std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; // determine how many integers match a target value. for (const int target: {3, 4, 5}) { const int num_items = std::count(v.cbegin(), v.cend(), target); std::cout << "number: " << target << ", count: " << num_items << '\n'; } // use a lambda expression to count elements divisible by 4. int count_div4 = std::count_if(v.begin(), v.end(), [](int i){return i % 4 == 0;}); std::cout << "numbers divisible by four: " << count_div4 << '\n'; // A simplified version of `distance` with O(N) complexity: auto distance = [](auto first, auto last) { return std::count_if(first, last, [](auto){return true;}); }; static_assert(distance(v.begin(), v.end()) == 10); } ``` Output: ``` v: 1 2 3 4 4 3 7 8 9 10 number: 3, count: 2 number: 4, count: 2 number: 5, count: 0 numbers divisible by four: 3 ``` ### See also | | | | --- | --- | | [distance](../iterator/distance "cpp/iterator/distance") | returns the distance between two iterators (function template) | | [ranges::countranges::count\_if](ranges/count "cpp/algorithm/ranges/count") (C++20)(C++20) | returns the number of elements satisfying specific criteria (niebloid) | cpp std::adjacent_difference std::adjacent\_difference ========================= | Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class OutputIt > OutputIt adjacent_difference( InputIt first, InputIt last, OutputIt d_first ); ``` | (until C++20) | | ``` template< class InputIt, class OutputIt > constexpr OutputIt adjacent_difference( InputIt first, InputIt last, OutputIt d_first ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > ForwardIt2 adjacent_difference( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt, class OutputIt, class BinaryOperation > OutputIt adjacent_difference( InputIt first, InputIt last, OutputIt d_first, BinaryOperation op ); ``` | (until C++20) | | ``` template< class InputIt, class OutputIt, class BinaryOperation > constexpr OutputIt adjacent_difference( InputIt first, InputIt last, OutputIt d_first, BinaryOperation op ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryOperation > ForwardIt2 adjacent_difference( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, BinaryOperation op ); ``` | (4) | (since C++17) | Computes the differences between the second and the first of each adjacent pair of elements of the range `[first, last)` and writes them to the range beginning at `d_first + 1`. An unmodified copy of `*first` is written to `*d_first`. 1,3) First, creates an accumulator `acc` whose type is `InputIt`'s value type, initializes it with `*first`, and assigns the result to `*d_first`. Then, for every iterator `i` in `[first + 1, last)` in order, creates an object `val` whose type is `InputIt`'s value type, initializes it with `*i`, computes `val - acc` (until C++20)`val - std::move(acc)` (since C++20) (overload (1)) or `op(val, acc)` (until C++20)`op(val, std::move(acc))` (since C++20) (overload (3)), assigns the result to `*(d_first + (i - first))`, and move assigns from `val` to `acc`. `first` may be equal to `d_first`. 2,4) Performs `*d_first = *first;`. For every `d` in `[1, last - first - 1]`, assigns `*(first + d) - *(first + d - 1)` (overload (2)) or `op(*(first + d), *(first + d - 1))` (overload (4)) to `*(d_first + d)`. This is executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. The behavior is undefined if the input and output ranges overlap in any way. Equivalent operation: ``` *(d_first) = *first; *(d_first+1) = *(first+1) - *(first); *(d_first+2) = *(first+2) - *(first+1); *(d_first+3) = *(first+3) - *(first+2); ... ``` | | | | --- | --- | | `op` must not have side effects. | (until C++11) | | `op` must not invalidate any iterators, including the end iterators, or modify any elements of the ranges involved. | (since C++11) | ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements | | d\_first | - | the beginning of the destination range | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | op | - | binary operation function object that will be applied. The signature of the function should be equivalent to the following: `Ret fun(const Type1 &a, const Type2 &b);` The signature does not need to have `const &`. The types `Type1` and `Type2` must be such that an object of type `iterator_traits<InputIt>::value_type` can be implicitly converted to both of them. The type `Ret` must be such that an object of type `OutputIt` can be dereferenced and assigned a value of type `Ret`. ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). InputIt's value type must be [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and constructible from the type of `*first` | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). both `acc` (the accumulated value) and the result of `val - acc` or `op(val, acc)` (until C++20)`val - std::move(acc)` or `op(val, std::move(acc))` (since C++20) must be writable to `OutputIt` | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). The results of `*first`, `*first - *first` (for (2)) and `op(*first, *first)` (for (4)) must be writable to `ForwardIt2`. | ### Return value Iterator to the element past the last element written. ### Notes If `first == last`, this function has no effect and will merely return `d_first`. ### Complexity Exactly `(last - first) - 1` applications of the binary operation. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class InputIt, class OutputIt> constexpr // since C++20 OutputIt adjacent_difference(InputIt first, InputIt last, OutputIt d_first) { if (first == last) return d_first; typedef typename std::iterator_traits<InputIt>::value_type value_t; value_t acc = *first; *d_first = acc; while (++first != last) { value_t val = *first; *++d_first = val - std::move(acc); // std::move since C++20 acc = std::move(val); } return ++d_first; } ``` | | Second version | | ``` template<class InputIt, class OutputIt, class BinaryOperation> constexpr // since C++20 OutputIt adjacent_difference(InputIt first, InputIt last, OutputIt d_first, BinaryOperation op) { if (first == last) return d_first; typedef typename std::iterator_traits<InputIt>::value_type value_t; value_t acc = *first; *d_first = acc; while (++first != last) { value_t val = *first; *++d_first = op(val, std::move(acc)); // std::move since C++20 acc = std::move(val); } return ++d_first; } ``` | ### Example ``` #include <numeric> #include <vector> #include <array> #include <iostream> #include <functional> #include <iterator> auto print = [](auto comment, auto const& sequence) { std::cout << comment; for (const auto& n : sequence) std::cout << n << ' '; std::cout << '\n'; }; int main() { // Default implementation - the difference b/w two adjacent items std::vector v {4, 6, 9, 13, 18, 19, 19, 15, 10}; print("Initially, v = ", v); std::adjacent_difference(v.begin(), v.end(), v.begin()); print("Modified v = ", v); // Fibonacci std::array<int, 10> a {1}; adjacent_difference(begin(a), std::prev(end(a)), std::next(begin(a)), std::plus<> {}); print("Fibonacci, a = ", a); } ``` Output: ``` Initially, v = 4 6 9 13 18 19 19 15 10 Modified v = 4 2 3 4 5 1 0 -4 -5 Fibonacci, a = 1 1 2 3 5 8 13 21 34 55 ``` ### See also | | | | --- | --- | | [partial\_sum](partial_sum "cpp/algorithm/partial sum") | computes the partial sum of a range of elements (function template) | | [accumulate](accumulate "cpp/algorithm/accumulate") | sums up a range of elements (function template) | cpp std::prev_permutation std::prev\_permutation ====================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class BidirIt > bool prev_permutation( BidirIt first, BidirIt last ); ``` | (until C++20) | | ``` template< class BidirIt > constexpr bool prev_permutation( BidirIt first, BidirIt last ); ``` | (since C++20) | | | (2) | | | ``` template< class BidirIt, class Compare > bool prev_permutation( BidirIt first, BidirIt last, Compare comp ); ``` | (until C++20) | | ``` template< class BidirIt, class Compare > constexpr bool prev_permutation( BidirIt first, BidirIt last, Compare comp ); ``` | (since C++20) | Transforms the range `[first, last)` into the previous permutation from the set of all permutations that are lexicographically ordered with respect to `operator<` or `comp`. Returns `true` if such permutation exists, otherwise transforms the range into the last permutation (as if by `std::sort(first, last); std::reverse(first, last);`) and returns `false`. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to permute | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `BidirIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`BidirIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | ### Return value `true` if the new permutation precedes the old in lexicographical order. `false` if the first permutation was reached and the range was reset to the last permutation. ### Exceptions Any exceptions thrown from iterator operations or the element swap. ### Complexity At most `(last-first)/2` swaps. Averaged over the entire sequence of permutations, typical implementations use about 3 comparisons and 1.5 swaps per call. ### Notes Implementations (e.g. [MSVC STL](https://github.com/microsoft/STL/blob/main/stl/src/vector_algorithms.cpp)) may enable vectorization when the iterator type satisfies [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") and swapping its value type calls neither non-trivial special member function nor [ADL](../language/adl "cpp/language/adl")-found `swap`. ### Possible implementation | | | --- | | ``` template<class BidirIt> bool prev_permutation(BidirIt first, BidirIt last) { if (first == last) return false; BidirIt i = last; if (first == --i) return false; while (1) { BidirIt i1, i2; i1 = i; if (*i1 < *--i) { i2 = last; while (!(*--i2 < *i)) ; std::iter_swap(i, i2); std::reverse(i1, last); return true; } if (i == first) { std::reverse(first, last); return false; } } } ``` | ### Example The following code prints all six permutations of the string "abc" in reverse order. ``` #include <algorithm> #include <string> #include <iostream> #include <functional> int main() { std::string s="abc"; std::sort(s.begin(), s.end(), std::greater<char>()); do { std::cout << s << ' '; } while(std::prev_permutation(s.begin(), s.end())); std::cout << '\n'; } ``` Output: ``` cba cab bca bac acb abc ``` ### See also | | | | --- | --- | | [is\_permutation](is_permutation "cpp/algorithm/is permutation") (C++11) | determines if a sequence is a permutation of another sequence (function template) | | [next\_permutation](next_permutation "cpp/algorithm/next permutation") | generates the next greater lexicographic permutation of a range of elements (function template) | | [ranges::prev\_permutation](ranges/prev_permutation "cpp/algorithm/ranges/prev permutation") (C++20) | generates the next smaller lexicographic permutation of a range of elements (niebloid) |
programming_docs
cpp std::replace, std::replace_if std::replace, std::replace\_if ============================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt, class T > void replace( ForwardIt first, ForwardIt last, const T& old_value, const T& new_value ); ``` | (until C++20) | | ``` template< class ForwardIt, class T > constexpr void replace( ForwardIt first, ForwardIt last, const T& old_value, const T& new_value ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class T > void replace( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, const T& old_value, const T& new_value ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class ForwardIt, class UnaryPredicate, class T > void replace_if( ForwardIt first, ForwardIt last, UnaryPredicate p, const T& new_value ); ``` | (until C++20) | | ``` template< class ForwardIt, class UnaryPredicate, class T > constexpr void replace_if( ForwardIt first, ForwardIt last, UnaryPredicate p, const T& new_value ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate, class T > void replace_if( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate p, const T& new_value ); ``` | (4) | (since C++17) | Replaces all elements satisfying specific criteria with `new_value` in the range `[first, last)`. 1) Replaces all elements that are equal to `old_value`. 3) Replaces all elements for which predicate `p` returns `true`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to process | | old\_value | - | the value of elements to replace | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | unary predicate which returns ​`true` if the element value should be replaced. The expression `p(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `VT`, where `VT` is the value type of `ForwardIt`, regardless of [value category](../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `VT&`is not allowed, nor is `VT` unless for `VT` a move is equivalent to a copy (since C++11). ​ | | new\_value | - | the value to use as replacement | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`UnaryPredicate` must meet the requirements of [Predicate](../named_req/predicate "cpp/named req/Predicate"). | ### Return value (none). ### Complexity Exactly `last - first` applications of the predicate. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes Because the algorithm takes `old_value` and `new_value` by reference, it can have unexpected behavior if either is a reference to an element of the range `[first, last)`. ### Possible implementation | First version | | --- | | ``` template<class ForwardIt, class T> void replace(ForwardIt first, ForwardIt last, const T& old_value, const T& new_value) { for (; first != last; ++first) { if (*first == old_value) { *first = new_value; } } } ``` | | Second version | | ``` template<class ForwardIt, class UnaryPredicate, class T> void replace_if(ForwardIt first, ForwardIt last, UnaryPredicate p, const T& new_value) { for (; first != last; ++first) { if(p(*first)) { *first = new_value; } } } ``` | ### Example The following code at first replaces all occurrences of `8` with `88` in a vector of integers. Then it replaces all values less than `5` with 55. ``` #include <algorithm> #include <array> #include <iostream> #include <functional> int main() { std::array<int, 10> s{5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; std::replace(s.begin(), s.end(), 8, 88); for (int a : s) { std::cout << a << " "; } std::cout << '\n'; std::replace_if(s.begin(), s.end(), std::bind(std::less<int>(), std::placeholders::_1, 5), 55); for (int a : s) { std::cout << a << " "; } std::cout << '\n'; } ``` Output: ``` 5 7 4 2 88 6 1 9 0 3 5 7 55 55 88 6 55 9 55 55 ``` ### See also | | | | --- | --- | | [replace\_copyreplace\_copy\_if](replace_copy "cpp/algorithm/replace copy") | copies a range, replacing elements satisfying specific criteria with another value (function template) | | [ranges::replaceranges::replace\_if](ranges/replace "cpp/algorithm/ranges/replace") (C++20)(C++20) | replaces all values satisfying specific criteria with another value (niebloid) | cpp std::remove_copy, std::remove_copy_if std::remove\_copy, std::remove\_copy\_if ======================================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class OutputIt, class T > OutputIt remove_copy( InputIt first, InputIt last, OutputIt d_first, const T& value ); ``` | (until C++20) | | ``` template< class InputIt, class OutputIt, class T > constexpr OutputIt remove_copy( InputIt first, InputIt last, OutputIt d_first, const T& value ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T > ForwardIt2 remove_copy( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, const T& value ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt, class OutputIt, class UnaryPredicate > OutputIt remove_copy_if( InputIt first, InputIt last, OutputIt d_first, UnaryPredicate p ); ``` | (until C++20) | | ``` template< class InputIt, class OutputIt, class UnaryPredicate > constexpr OutputIt remove_copy_if( InputIt first, InputIt last, OutputIt d_first, UnaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class UnaryPredicate > ForwardIt2 remove_copy_if( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, UnaryPredicate p ); ``` | (4) | (since C++17) | Copies elements from the range `[first, last)`, to another range beginning at `d_first`, omitting the elements which satisfy specific criteria. Source and destination ranges cannot overlap. 1) Ignores all elements that are equal to `value`. 3) Ignores all elements for which predicate `p` returns `true`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to copy | | d\_first | - | the beginning of the destination range. | | value | - | the value of the elements not to copy | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`UnaryPredicate` must meet the requirements of [Predicate](../named_req/predicate "cpp/named req/Predicate"). | ### Return value Iterator to the element past the last element copied. ### Complexity Exactly `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` applications of the predicate. For the overloads with an ExecutionPolicy, there may be a performance cost if `ForwardIt1`'s value\_type is not [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class InputIt, class OutputIt, class T> OutputIt remove_copy(InputIt first, InputIt last, OutputIt d_first, const T& value) { for (; first != last; ++first) { if (!(*first == value)) { *d_first++ = *first; } } return d_first; } ``` | | Second version | | ``` template<class InputIt, class OutputIt, class UnaryPredicate> OutputIt remove_copy_if(InputIt first, InputIt last, OutputIt d_first, UnaryPredicate p) { for (; first != last; ++first) { if (!p(*first)) { *d_first++ = *first; } } return d_first; } ``` | ### Example The following code outputs a string while erasing the hash characters '#' on the fly. ``` #include <algorithm> #include <iterator> #include <string> #include <iostream> #include <iomanip> int main() { std::string str = "#Return #Value #Optimization"; std::cout << "before: " << std::quoted(str) << "\n"; std::cout << "after: \""; std::remove_copy(str.begin(), str.end(), std::ostream_iterator<char>(std::cout), '#'); std::cout << "\"\n"; } ``` Output: ``` before: "#Return #Value #Optimization" after: "Return Value Optimization" ``` ### See also | | | | --- | --- | | [removeremove\_if](remove "cpp/algorithm/remove") | removes elements satisfying specific criteria (function template) | | [copycopy\_if](copy "cpp/algorithm/copy") (C++11) | copies a range of elements to a new location (function template) | | [partition\_copy](partition_copy "cpp/algorithm/partition copy") (C++11) | copies a range dividing the elements into two groups (function template) | | [ranges::remove\_copyranges::remove\_copy\_if](ranges/remove_copy "cpp/algorithm/ranges/remove copy") (C++20)(C++20) | copies a range of elements omitting those that satisfy specific criteria (niebloid) | cpp std::search_n std::search\_n ============== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt, class Size, class T > ForwardIt search_n( ForwardIt first, ForwardIt last, Size count, const T& value ); ``` | (until C++20) | | ``` template< class ForwardIt, class Size, class T > constexpr ForwardIt search_n( ForwardIt first, ForwardIt last, Size count, const T& value ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class Size, class T > ForwardIt search_n( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, Size count, const T& value ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class ForwardIt, class Size, class T, class BinaryPredicate > ForwardIt search_n( ForwardIt first, ForwardIt last, Size count, const T& value, BinaryPredicate p ); ``` | (until C++20) | | ``` template< class ForwardIt, class Size, class T, class BinaryPredicate > constexpr ForwardIt search_n( ForwardIt first, ForwardIt last, Size count, const T& value, BinaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class Size, class T, class BinaryPredicate > ForwardIt search_n( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, Size count, const T& value, BinaryPredicate p ); ``` | (4) | (since C++17) | Searches the range `[first, last)` for the first sequence of count identical elements, each equal to the given value. 1) Elements are compared using `operator==`. 3) Elements are compared using the given binary predicate `p`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | count | - | the length of the sequence to search for | | value | - | the value of the elements to search for | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | binary predicate which returns ​`true` if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The type `Type1` must be such that an object of type `ForwardIt` can be dereferenced and then implicitly converted to `Type1`. The type `Type2` must be such that an object of type `T` can be implicitly converted to `Type2`. ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value Iterator to the beginning of the found sequence in the range `[first, last)`. If no such sequence is found, `last` is returned. If `count` is zero or negative, `first` is returned. ### Complexity At most `last - first` applications of the predicate. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class ForwardIt, class Size, class T> ForwardIt search_n(ForwardIt first, ForwardIt last, Size count, const T& value) { if (count <= 0) { return first; } for(; first != last; ++first) { if (!(*first == value)) { continue; } ForwardIt candidate = first; Size cur_count = 0; while (true) { ++cur_count; if (cur_count >= count) { // success return candidate; } ++first; if (first == last) { // exhausted the list return last; } if (!(*first == value)) { // too few in a row break; } } } return last; } ``` | | Second version | | ``` template<class ForwardIt, class Size, class T, class BinaryPredicate> ForwardIt search_n(ForwardIt first, ForwardIt last, Size count, const T& value, BinaryPredicate p) { if (count <= 0) { return first; } for(; first != last; ++first) { if (!p(*first, value)) { continue; } ForwardIt candidate = first; Size cur_count = 0; while (true) { ++cur_count; if (cur_count >= count) { // success return candidate; } ++first; if (first == last) { // exhausted the list return last; } if (!p(*first, value)) { // too few in a row break; } } } return last; } ``` | ### Example ``` #include <iostream> #include <algorithm> #include <iterator> template <class Container, class Size, class T> bool consecutive_values(const Container& c, Size count, const T& v) { return std::search_n(std::begin(c),std::end(c),count,v) != std::end(c); } int main() { const char sequence[] = "1001010100010101001010101"; std::cout << std::boolalpha; std::cout << "Has 4 consecutive zeros: " << consecutive_values(sequence,4,'0') << '\n'; std::cout << "Has 3 consecutive zeros: " << consecutive_values(sequence,3,'0') << '\n'; } ``` Output: ``` Has 4 consecutive zeros: false Has 3 consecutive zeros: true ``` ### See also | | | | --- | --- | | [find\_end](find_end "cpp/algorithm/find end") | finds the last sequence of elements in a certain range (function template) | | [findfind\_iffind\_if\_not](find "cpp/algorithm/find") (C++11) | finds the first element satisfying specific criteria (function template) | | [search](search "cpp/algorithm/search") | searches for a range of elements (function template) | | [ranges::search\_n](ranges/search_n "cpp/algorithm/ranges/search n") (C++20) | searches for a number consecutive copies of an element in a range (niebloid) |
programming_docs
cpp std::qsort std::qsort ========== | Defined in header `[<cstdlib>](../header/cstdlib "cpp/header/cstdlib")` | | | | --- | --- | --- | | ``` void qsort( void *ptr, std::size_t count, std::size_t size, /*compare-pred*/* comp ); void qsort( void *ptr, std::size_t count, std::size_t size, /*c-compare-pred*/* comp ); ``` | (1) | | | ``` extern "C++" using /*compare-pred*/ = int(const void*, const void*); // exposition-only extern "C" using /*c-compare-pred*/ = int(const void*, const void*); // exposition-only ``` | (2) | | Sorts the given array pointed to by `ptr` in ascending order. The array contains `count` elements of `size` bytes. Function pointed to by `comp` is used for object comparison. If `comp` indicates two elements as equivalent, their order is unspecified. If the type of the elements of the array is not a [PODType](../named_req/podtype "cpp/named req/PODType") (until C++11)[TriviallyCopyable](../named_req/triviallycopyable "cpp/named req/TriviallyCopyable") type (since C++11), the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | ptr | - | pointer to the array to sort | | count | - | number of elements in the array | | size | - | size of each element in the array in bytes | | comp | - | comparison function which returns ​a negative integer value if the first argument is *less* than the second, a positive integer value if the first argument is *greater* than the second and zero if the arguments are equivalent. The signature of the comparison function should be equivalent to the following: `int cmp(const void *a, const void *b);` The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array. ​ | ### Return value (none). ### Notes Despite the name, C++, C, and POSIX standards do not require this function to be implemented using [quicksort](https://en.wikipedia.org/wiki/Quicksort "enwiki:Quicksort") or make any complexity or stability guarantees. The two overloads provided by the C++ standard library are distinct because the types of the parameter `comp` are distinct ([language linkage](../language/language_linkage "cpp/language/language linkage") is part of its type). ### Example The following code sorts an array of integers using `qsort()`. ``` #include <iostream> #include <cstdlib> #include <climits> #include <compare> #include <array> int main() { std::array a { -2, 99, 0, -743, INT_MAX, 2, INT_MIN, 4 }; std::qsort( a.data(), a.size(), sizeof(decltype(a)::value_type), [](const void* x, const void* y) { const int arg1 = *static_cast<const int*>(x); const int arg2 = *static_cast<const int*>(y); const auto cmp = arg1 <=> arg2; if (cmp < 0) return -1; if (cmp > 0) return 1; return 0; }); for (int ai : a) std::cout << ai << ' '; } ``` Output: ``` -2147483648 -743 -2 0 2 4 99 2147483647 ``` ### See also | | | | --- | --- | | [bsearch](bsearch "cpp/algorithm/bsearch") | searches an array for an element of unspecified type (function) | | [sort](sort "cpp/algorithm/sort") | sorts a range into ascending order (function template) | | [is\_trivial](../types/is_trivial "cpp/types/is trivial") (C++11) | checks if a type is trivial (class template) | | [C documentation](https://en.cppreference.com/w/c/algorithm/qsort "c/algorithm/qsort") for `qsort` | cpp std::generate std::generate ============= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt, class Generator > void generate( ForwardIt first, ForwardIt last, Generator g ); ``` | (until C++20) | | ``` template< class ForwardIt, class Generator > constexpr void generate( ForwardIt first, ForwardIt last, Generator g ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class Generator > void generate( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, Generator g ); ``` | (2) | (since C++17) | 1) Assigns each element in range `[first, last)` a value generated by the given function object `g`. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to generate | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | g | - | generator function object that will be called. The signature of the function should be equivalent to the following: | | | | | --- | --- | --- | | ``` Ret fun(); ``` | | | The type `Ret` must be such that an object of type `ForwardIt` can be dereferenced and assigned a value of type `Ret`. ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value (none). ### Complexity Exactly `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)` invocations of `g()` and assignments. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | | | --- | | ``` template<class ForwardIt, class Generator> constexpr // Since C++20 void generate(ForwardIt first, ForwardIt last, Generator g) { while (first != last) { *first++ = g(); } } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> int f() { static int i; return ++i; } int main() { std::vector<int> v(5); auto print = [&] { for (std::cout << "v: "; auto iv: v) std::cout << iv << " "; std::cout << "\n"; }; std::generate(v.begin(), v.end(), f); print(); // Initialize with default values 0,1,2,3,4 from a lambda function // Equivalent to std::iota(v.begin(), v.end(), 0); std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; }); print(); } ``` Output: ``` v: 1 2 3 4 5 v: 0 1 2 3 4 ``` ### See also | | | | --- | --- | | [fill](fill "cpp/algorithm/fill") | copy-assigns the given value to every element in a range (function template) | | [generate\_n](generate_n "cpp/algorithm/generate n") | assigns the results of successive function calls to N elements in a range (function template) | | [iota](iota "cpp/algorithm/iota") (C++11) | fills a range with successive increments of the starting value (function template) | | [ranges::generate](ranges/generate "cpp/algorithm/ranges/generate") (C++20) | saves the result of a function in a range (niebloid) | cpp std::adjacent_find std::adjacent\_find =================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt > ForwardIt adjacent_find( ForwardIt first, ForwardIt last ); ``` | (until C++20) | | ``` template< class ForwardIt > constexpr ForwardIt adjacent_find( ForwardIt first, ForwardIt last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt > ForwardIt adjacent_find( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class ForwardIt, class BinaryPredicate> ForwardIt adjacent_find( ForwardIt first, ForwardIt last, BinaryPredicate p ); ``` | (until C++20) | | ``` template< class ForwardIt, class BinaryPredicate> constexpr ForwardIt adjacent_find( ForwardIt first, ForwardIt last, BinaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class BinaryPredicate> ForwardIt adjacent_find( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, BinaryPredicate p ); ``` | (4) | (since C++17) | Searches the range `[first, last)` for two consecutive equal elements. 1) Elements are compared using `operator==`. 3) Elements are compared using the given binary predicate `p`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | binary predicate which returns ​`true` if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `ForwardIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value an iterator to the first of the first pair of identical elements, that is, the first iterator `it` such that `*it == *(it+1)` for the first version or `p(*it, *(it + 1)) != false` for the second version. If no such elements are found, `last` is returned. ### Complexity 1,3) Exactly `min((result-first)+1, (last-first)-1)` applications of the predicate where `result` is the return value. 2,4) `O(last-first)` applications of the corresponding predicate. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class ForwardIt> ForwardIt adjacent_find(ForwardIt first, ForwardIt last) { if (first == last) { return last; } ForwardIt next = first; ++next; for (; next != last; ++next, ++first) { if (*first == *next) { return first; } } return last; } ``` | | Second version | | ``` template<class ForwardIt, class BinaryPredicate> ForwardIt adjacent_find(ForwardIt first, ForwardIt last, BinaryPredicate p) { if (first == last) { return last; } ForwardIt next = first; ++next; for (; next != last; ++next, ++first) { if (p(*first, *next)) { return first; } } return last; } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <vector> #include <functional> int main() { std::vector<int> v1{0, 1, 2, 3, 40, 40, 41, 41, 5}; auto i1 = std::adjacent_find(v1.begin(), v1.end()); if (i1 == v1.end()) { std::cout << "No matching adjacent elements\n"; } else { std::cout << "The first adjacent pair of equal elements is at " << std::distance(v1.begin(), i1) << ", *i1 = " << *i1 << '\n'; } auto i2 = std::adjacent_find(v1.begin(), v1.end(), std::greater<int>()); if (i2 == v1.end()) { std::cout << "The entire vector is sorted in ascending order\n"; } else { std::cout << "The last element in the non-decreasing subsequence is at " << std::distance(v1.begin(), i2) << ", *i2 = " << *i2 << '\n'; } } ``` Output: ``` The first adjacent pair of equal elements is at 4, *i1 = 40 The last element in the non-decreasing subsequence is at 7, *i2 = 41 ``` ### See also | | | | --- | --- | | [unique](unique "cpp/algorithm/unique") | removes consecutive duplicate elements in a range (function template) | | [ranges::adjacent\_find](ranges/adjacent_find "cpp/algorithm/ranges/adjacent find") (C++20) | finds the first two adjacent items that are equal (or satisfy a given predicate) (niebloid) | cpp std::set_difference std::set\_difference ==================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt1, class InputIt2, class OutputIt > OutputIt set_difference( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class OutputIt > constexpr OutputIt set_difference( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class ForwardIt3 > ForwardIt3 set_difference( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, ForwardIt3 d_first ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt1, class InputIt2, class OutputIt, class Compare > OutputIt set_difference( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class OutputIt, class Compare > constexpr OutputIt set_difference( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class ForwardIt3, class Compare > ForwardIt3 set_difference( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, ForwardIt3 d_first, Compare comp ); ``` | (4) | (since C++17) | Copies the elements from the sorted range `[first1, last1)` which are not found in the sorted range `[first2, last2)` to the range beginning at `d_first`. The resulting range is also sorted. Equivalent elements are treated individually, that is, if some element is found `m` times in `[first1, last1)` and `n` times in `[first2, last2)`, it will be copied to `d_first` exactly `[std::max](http://en.cppreference.com/w/cpp/algorithm/max)(m-n, 0)` times. The resulting range cannot overlap with either of the input ranges. 1) Elements are compared using `operator<` and the ranges must be sorted with respect to the same. 3) Elements are compared using the given binary comparison function `comp` and the ranges must be sorted with respect to the same. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the range of elements to examine | | first2, last2 | - | the range of elements to search for | | d\_first | - | the beginning of the destination range | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that objects of types `InputIt1` and `InputIt2` can be dereferenced and then implicitly converted to both `Type1` and `Type2`. ​ | | Type requirements | | -`InputIt1, InputIt2` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1, ForwardIt2, ForwardIt3` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value Iterator past the end of the constructed range. ### Complexity At most \(\scriptsize 2\cdot(N\_1+N\_2)-1\)2·(N 1+N 2)-1 comparisons, where \(\scriptsize N\_1\)N 1 and \(\scriptsize N\_2\)N 2 are `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1)` and `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first2, last2)`, respectively. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class InputIt1, class InputIt2, class OutputIt> OutputIt set_difference(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first) { while (first1 != last1) { if (first2 == last2) return std::copy(first1, last1, d_first); if (*first1 < *first2) { *d_first++ = *first1++; } else { if (! (*first2 < *first1)) { ++first1; } ++first2; } } return d_first; } ``` | | Second version | | ``` template<class InputIt1, class InputIt2, class OutputIt, class Compare> OutputIt set_difference( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp) { while (first1 != last1) { if (first2 == last2) return std::copy(first1, last1, d_first); if (comp(*first1, *first2)) { *d_first++ = *first1++; } else { if (!comp(*first2, *first1)) { ++first1; } ++first2; } } return d_first; } ``` | ### Example ``` #include <algorithm> #include <iostream> #include <iterator> #include <string_view> #include <vector> auto print = [](const auto& v, std::string_view end = "") { std::cout << "{ "; for (auto i : v) std::cout << i << ' '; std::cout << "} " << end; }; struct Order // a struct with some interesting data { int order_id; friend std::ostream& operator<<(std::ostream& os, const Order& ord) { return os << ord.order_id << ','; } }; int main() { const std::vector<int> v1 {1, 2, 5, 5, 5, 9}; const std::vector<int> v2 {2, 5, 7}; std::vector<int> diff; std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::inserter(diff, diff.begin())); print(v1, "∖ "); print(v2, "= "); print(diff, "\n"); // we want to know which orders "cut" between old and new states: std::vector<Order> old_orders { {1}, {2}, {5}, {9} }; std::vector<Order> new_orders { {2}, {5}, {7} }; std::vector<Order> cut_orders; std::set_difference(old_orders.begin(), old_orders.end(), new_orders.begin(), new_orders.end(), std::back_inserter(cut_orders), [](auto& a, auto& b) { return a.order_id < b.order_id; }); std::cout << "old orders = "; print(old_orders, "\n"); std::cout << "new orders = "; print(new_orders, "\n"); std::cout << "cut orders = "; print(cut_orders, "\n"); } ``` Output: ``` { 1 2 5 5 5 9 } ∖ { 2 5 7 } = { 1 5 5 9 } old orders = { 1, 2, 5, 9, } new orders = { 2, 5, 7, } cut orders = { 1, 9, } ``` ### See also | | | | --- | --- | | [includes](includes "cpp/algorithm/includes") | returns true if one sequence is a subsequence of another (function template) | | [set\_symmetric\_difference](set_symmetric_difference "cpp/algorithm/set symmetric difference") | computes the symmetric difference between two sets (function template) | | [ranges::set\_difference](ranges/set_difference "cpp/algorithm/ranges/set difference") (C++20) | computes the difference between two sets (niebloid) |
programming_docs
cpp std::unique_copy std::unique\_copy ================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class OutputIt > OutputIt unique_copy( InputIt first, InputIt last, OutputIt d_first ); ``` | (until C++20) | | ``` template< class InputIt, class OutputIt > constexpr OutputIt unique_copy( InputIt first, InputIt last, OutputIt d_first ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > ForwardIt2 unique_copy( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt, class OutputIt, class BinaryPredicate > OutputIt unique_copy( InputIt first, InputIt last, OutputIt d_first, BinaryPredicate p ); ``` | (until C++20) | | ``` template< class InputIt, class OutputIt, class BinaryPredicate > constexpr OutputIt unique_copy( InputIt first, InputIt last, OutputIt d_first, BinaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryPredicate > ForwardIt2 unique_copy( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, BinaryPredicate p ); ``` | (4) | (since C++17) | Copies the elements from the range `[first, last)`, to another range beginning at `d_first` in such a way that there are no consecutive equal elements. Only the first element of each group of equal elements is copied. 1) Elements are compared using `operator==`. The behavior is undefined if it is not an [equivalence relation](https://en.wikipedia.org/wiki/equivalence_relation "enwiki:equivalence relation"). 3) Elements are compared using the given binary predicate `p`. The behavior is undefined if it is not an equivalence relation. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to process | | d\_first | - | the beginning of the destination range | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | binary predicate which returns ​`true` if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `InputIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -The type of dereferenced `InputIt` must meet the requirements of [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"). if `InputIt` does not satisfy [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") | | -The type of dereferenced `InputIt` must meet the requirements of [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible"). if neither `InputIt` nor `OutputIt` satisfies [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"), or if `InputIt` does not satisfy [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator") and the value type of `InputIt` differs from that of `OutputIt`. | ### Return value Output iterator to the element past the last written element. ### Complexity For nonempty ranges, exactly `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last) - 1` applications of the corresponding predicate. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes If `InputIt` satisfies [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"), this function rereads the input in order to detect duplicates. Otherwise, if `OutputIt` satisfies [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"), and the value type of `InputIt` is the same as that of `OutputIt`, this function compare `*d_first` to `*first`. Otherwise, this function compares `*first` to a local element copy. For the overloads with an ExecutionPolicy, there may be a performance cost if the value type of `ForwardIterator1` is not both [CopyConstructible](../named_req/copyconstructible "cpp/named req/CopyConstructible") and [CopyAssignable](../named_req/copyassignable "cpp/named req/CopyAssignable"). ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L1046) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L2177). ### Example ``` #include <string> #include <iostream> #include <algorithm> #include <iterator> int main() { std::string s1 = "The string with many spaces!"; std::cout << "before: " << s1 << '\n'; std::string s2; std::unique_copy(s1.begin(), s1.end(), std::back_inserter(s2), [](char c1, char c2){ return c1 == ' ' && c2 == ' '; }); std::cout << "after: " << s2 << '\n'; } ``` Output: ``` before: The string with many spaces! after: The string with many spaces! ``` ### See also | | | | --- | --- | | [adjacent\_find](adjacent_find "cpp/algorithm/adjacent find") | finds the first two adjacent items that are equal (or satisfy a given predicate) (function template) | | [unique](unique "cpp/algorithm/unique") | removes consecutive duplicate elements in a range (function template) | | [copycopy\_if](copy "cpp/algorithm/copy") (C++11) | copies a range of elements to a new location (function template) | | [ranges::unique\_copy](ranges/unique_copy "cpp/algorithm/ranges/unique copy") (C++20) | creates a copy of some range of elements that contains no consecutive duplicates (niebloid) | cpp std::find, std::find_if, std::find_if_not std::find, std::find\_if, std::find\_if\_not ============================================ | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class T > InputIt find( InputIt first, InputIt last, const T& value ); ``` | (until C++20) | | ``` template< class InputIt, class T > constexpr InputIt find( InputIt first, InputIt last, const T& value ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class T > ForwardIt find( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, const T& value ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt, class UnaryPredicate > InputIt find_if( InputIt first, InputIt last, UnaryPredicate p ); ``` | (until C++20) | | ``` template< class InputIt, class UnaryPredicate > constexpr InputIt find_if( InputIt first, InputIt last, UnaryPredicate p ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate > ForwardIt find_if( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate p ); ``` | (4) | (since C++17) | | | (5) | | | ``` template< class InputIt, class UnaryPredicate > InputIt find_if_not( InputIt first, InputIt last, UnaryPredicate q ); ``` | (since C++11) (until C++20) | | ``` template< class InputIt, class UnaryPredicate > constexpr InputIt find_if_not( InputIt first, InputIt last, UnaryPredicate q ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate > ForwardIt find_if_not( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate q ); ``` | (6) | (since C++17) | Returns an iterator to the first element in the range `[first, last)` that satisfies specific criteria: 1) `find` searches for an element equal to `value` 3) `find_if` searches for an element for which predicate `p` returns `true` 5) `find_if_not` searches for an element for which predicate `q` returns `false` 2,4,6) Same as (1,3,5), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | value | - | value to compare the elements to | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | unary predicate which returns ​`true` for the required element. The expression `p(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `VT`, where `VT` is the value type of `InputIt`, regardless of [value category](../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `VT&`is not allowed, nor is `VT` unless for `VT` a move is equivalent to a copy (since C++11). ​ | | q | - | unary predicate which returns ​`false` for the required element. The expression `q(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `VT`, where `VT` is the value type of `InputIt`, regardless of [value category](../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `VT&`is not allowed, nor is `VT` unless for `VT` a move is equivalent to a copy (since C++11). ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`UnaryPredicate` must meet the requirements of [Predicate](../named_req/predicate "cpp/named req/Predicate"). | ### Return value Iterator to the first element satisfying the condition or `last` if no such element is found. ### Complexity At most `N` applications of the predicate, where `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class InputIt, class T> constexpr InputIt find(InputIt first, InputIt last, const T& value) { for (; first != last; ++first) { if (*first == value) { return first; } } return last; } ``` | | Second version | | ``` template<class InputIt, class UnaryPredicate> constexpr InputIt find_if(InputIt first, InputIt last, UnaryPredicate p) { for (; first != last; ++first) { if (p(*first)) { return first; } } return last; } ``` | | Third version | | ``` template<class InputIt, class UnaryPredicate> constexpr InputIt find_if_not(InputIt first, InputIt last, UnaryPredicate q) { for (; first != last; ++first) { if (!q(*first)) { return first; } } return last; } ``` | ### Notes If you do not have C++11, an equivalent to `std::find_if_not` is to use `std::find_if` with the negated predicate. | | | --- | | ``` template<class InputIt, class UnaryPredicate> InputIt find_if_not(InputIt first, InputIt last, UnaryPredicate q) { return std::find_if(first, last, std::not1(q)); } ``` | ### Example The following example finds integers in given vector. ``` #include <iostream> #include <algorithm> #include <vector> #include <iterator> int main() { std::vector<int> v{1, 2, 3, 4}; int n1 = 3; int n2 = 5; auto is_even = [](int i){ return i%2 == 0; }; auto result1 = std::find(begin(v), end(v), n1); auto result2 = std::find(begin(v), end(v), n2); auto result3 = std::find_if(begin(v), end(v), is_even); (result1 != std::end(v)) ? std::cout << "v contains " << n1 << '\n' : std::cout << "v does not contain " << n1 << '\n'; (result2 != std::end(v)) ? std::cout << "v contains " << n2 << '\n' : std::cout << "v does not contain " << n2 << '\n'; (result3 != std::end(v)) ? std::cout << "v contains an even number: " << *result3 << '\n' : std::cout << "v does not contain even numbers\n"; } ``` Output: ``` v contains 3 v does not contain 5 v contains an even number: 2 ``` ### See also | | | | --- | --- | | [adjacent\_find](adjacent_find "cpp/algorithm/adjacent find") | finds the first two adjacent items that are equal (or satisfy a given predicate) (function template) | | [find\_end](find_end "cpp/algorithm/find end") | finds the last sequence of elements in a certain range (function template) | | [find\_first\_of](find_first_of "cpp/algorithm/find first of") | searches for any one of a set of elements (function template) | | [mismatch](mismatch "cpp/algorithm/mismatch") | finds the first position where two ranges differ (function template) | | [search](search "cpp/algorithm/search") | searches for a range of elements (function template) | | [ranges::findranges::find\_ifranges::find\_if\_not](ranges/find "cpp/algorithm/ranges/find") (C++20)(C++20)(C++20) | finds the first element satisfying specific criteria (niebloid) | cpp std::stable_partition std::stable\_partition ====================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | ``` template< class BidirIt, class UnaryPredicate > BidirIt stable_partition( BidirIt first, BidirIt last, UnaryPredicate p ); ``` | (1) | | | ``` template< class ExecutionPolicy, class BidirIt, class UnaryPredicate > BidirIt stable_partition( ExecutionPolicy&& policy, BidirIt first, BidirIt last, UnaryPredicate p ); ``` | (2) | (since C++17) | 1) Reorders the elements in the range `[first, last)` in such a way that all elements for which the predicate `p` returns `true` precede the elements for which predicate `p` returns `false`. Relative order of the elements is preserved. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to reorder | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | unary predicate which returns ​`true` if the element should be ordered before other elements. The expression `p(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `VT`, where `VT` is the value type of `BidirIt`, regardless of [value category](../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `VT&`is not allowed, nor is `VT` unless for `VT` a move is equivalent to a copy (since C++11). ​ | | Type requirements | | -`BidirIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator"). | | -The type of dereferenced `BidirIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). | | -`UnaryPredicate` must meet the requirements of [Predicate](../named_req/predicate "cpp/named req/Predicate"). | ### Return value Iterator to the first element of the second group. ### Complexity Given N = `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`, 1) Exactly `N` applications of the predicate and `O(N)` swaps if there is enough extra memory. If memory is insufficient, at most `N log N` swaps. 2) `O(N log N)` swaps and `O(N)` applications of the predicate ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes This function attempts to allocate a temporary buffer. If the allocation fails, the less efficient algorithm is chosen. Implementations in libc++ and libstdc++ also accept ranges denoted by [LegacyForwardIterators](../named_req/forwarditerator "cpp/named req/ForwardIterator") as an extension. ### Example ``` #include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> v{0, 0, 3, -1, 2, 4, 5, 0, 7}; std::stable_partition(v.begin(), v.end(), [](int n){return n>0;}); for (int n : v) { std::cout << n << ' '; } std::cout << '\n'; } ``` Output: ``` 3 2 4 5 7 0 0 -1 0 ``` ### See also | | | | --- | --- | | [partition](partition "cpp/algorithm/partition") | divides a range of elements into two groups (function template) | | [ranges::stable\_partition](ranges/stable_partition "cpp/algorithm/ranges/stable partition") (C++20) | divides elements into two groups while preserving their relative order (niebloid) |
programming_docs
cpp std::equal_range std::equal\_range ================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt, class T > std::pair<ForwardIt,ForwardIt> equal_range( ForwardIt first, ForwardIt last, const T& value ); ``` | (until C++20) | | ``` template< class ForwardIt, class T > constexpr std::pair<ForwardIt,ForwardIt> equal_range( ForwardIt first, ForwardIt last, const T& value ); ``` | (since C++20) | | | (2) | | | ``` template< class ForwardIt, class T, class Compare > std::pair<ForwardIt,ForwardIt> equal_range( ForwardIt first, ForwardIt last, const T& value, Compare comp ); ``` | (until C++20) | | ``` template< class ForwardIt, class T, class Compare > constexpr std::pair<ForwardIt,ForwardIt> equal_range( ForwardIt first, ForwardIt last, const T& value, Compare comp ); ``` | (since C++20) | Returns a range containing all elements equivalent to `value` in the range `[first, last)`. The range `[first, last)` must be at least partially ordered with respect to `value`, i.e. it must satisfy all of the following requirements: * partitioned with respect to `element < value` or `comp(element, value)` (that is, all elements for which the expression is `true` precedes all elements for which the expression is `false`) * partitioned with respect to `!(value < element)` or `!comp(value, element)` * for all elements, if `element < value` or `comp(element, value)` is `true` then `!(value < element)` or `!comp(value, element)` is also `true` A fully-sorted range meets these criteria. The returned range is defined by two iterators, one pointing to the first element that is *not less* than `value` and another pointing to the first element *greater* than `value`. The first iterator may be alternatively obtained with `[std::lower\_bound()](lower_bound "cpp/algorithm/lower bound")`, the second - with `[std::upper\_bound()](upper_bound "cpp/algorithm/upper bound")`. The first version uses `operator<` to compare the elements, the second version uses the given comparison function `comp`. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | value | - | value to compare the elements to | | comp | - | binary predicate which returns ​`true` if the first argument is *less* than (i.e. is ordered before) the second. The signature of the predicate function should be equivalent to the following: `bool pred(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `T` can be implicitly converted to both `Type1` and `Type2`, and an object of type `ForwardIt` can be dereferenced and then implicitly converted to both `Type1` and `Type2`. ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`Compare` must meet the requirements of [BinaryPredicate](../named_req/binarypredicate "cpp/named req/BinaryPredicate"). it is not required to satisfy [Compare](../named_req/compare "cpp/named req/Compare") | ### Return value `[std::pair](../utility/pair "cpp/utility/pair")` containing a pair of iterators defining the wanted range, the first pointing to the first element that is *not less* than `value` and the second pointing to the first element *greater* than `value`. If there are no elements *not less* than `value`, `last` is returned as the first element. Similarly if there are no elements *greater* than `value`, `last` is returned as the second element. ### Complexity The number of comparisons performed is logarithmic in the distance between `first` and `last` (At most 2 \* log 2(last - first) + O(1) comparisons). However, for non-[LegacyRandomAccessIterators](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"), the number of iterator increments is linear. Notably, `[std::set](../container/set "cpp/container/set")` and `[std::multiset](../container/multiset "cpp/container/multiset")` iterators are not random access, and so their member functions `[std::set::equal\_range](../container/set/equal_range "cpp/container/set/equal range")` (resp. `[std::multiset::equal\_range](../container/multiset/equal_range "cpp/container/multiset/equal range")`) should be preferred. ### Possible implementation | First version | | --- | | ``` template<class ForwardIt, class T> std::pair<ForwardIt,ForwardIt> equal_range(ForwardIt first, ForwardIt last, const T& value) { return std::make_pair(std::lower_bound(first, last, value), std::upper_bound(first, last, value)); } ``` | | Second version | | ``` template<class ForwardIt, class T, class Compare> std::pair<ForwardIt,ForwardIt> equal_range(ForwardIt first, ForwardIt last, const T& value, Compare comp) { return std::make_pair(std::lower_bound(first, last, value, comp), std::upper_bound(first, last, value, comp)); } ``` | ### Example ``` #include <algorithm> #include <vector> #include <iostream> struct S { int number; char name; // note: name is ignored by this comparison operator bool operator< ( const S& s ) const { return number < s.number; } }; int main() { // note: not ordered, only partitioned w.r.t. S defined below const std::vector<S> vec = { {1,'A'}, {2,'B'}, {2,'C'}, {2,'D'}, {4,'G'}, {3,'F'} }; const S value = {2, '?'}; std::cout << "Compare using S::operator<(): "; const auto p = std::equal_range(vec.begin(), vec.end(), value); for ( auto i = p.first; i != p.second; ++i ) std::cout << i->name << ' '; std::cout << "\n" "Using heterogeneous comparison: "; struct Comp { bool operator() ( const S& s, int i ) const { return s.number < i; } bool operator() ( int i, const S& s ) const { return i < s.number; } }; const auto p2 = std::equal_range(vec.begin(),vec.end(), 2, Comp{}); for ( auto i = p2.first; i != p2.second; ++i ) std::cout << i->name << ' '; } ``` Output: ``` Compare using S::operator<(): B C D Using heterogeneous comparison: B C D ``` ### Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. | DR | Applied to | Behavior as published | Correct behavior | | --- | --- | --- | --- | | [LWG 270](https://cplusplus.github.io/LWG/issue270) | C++98 | Compare was required to be a strict weak ordering | only a partitioning is needed; heterogeneous comparisons permitted | ### See also | | | | --- | --- | | [lower\_bound](lower_bound "cpp/algorithm/lower bound") | returns an iterator to the first element *not less* than the given value (function template) | | [upper\_bound](upper_bound "cpp/algorithm/upper bound") | returns an iterator to the first element *greater* than a certain value (function template) | | [binary\_search](binary_search "cpp/algorithm/binary search") | determines if an element exists in a partially-ordered range (function template) | | [partition](partition "cpp/algorithm/partition") | divides a range of elements into two groups (function template) | | [equal](equal "cpp/algorithm/equal") | determines if two sets of elements are the same (function template) | | [equal\_range](../container/set/equal_range "cpp/container/set/equal range") | returns range of elements matching a specific key (public member function of `std::set<Key,Compare,Allocator>`) | | [equal\_range](../container/multiset/equal_range "cpp/container/multiset/equal range") | returns range of elements matching a specific key (public member function of `std::multiset<Key,Compare,Allocator>`) | | [ranges::equal\_range](ranges/equal_range "cpp/algorithm/ranges/equal range") (C++20) | returns range of elements matching a specific key (niebloid) | cpp std::rotate_copy std::rotate\_copy ================= | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt, class OutputIt > OutputIt rotate_copy( ForwardIt first, ForwardIt n_first, ForwardIt last, OutputIt d_first ); ``` | (until C++20) | | ``` template< class ForwardIt, class OutputIt > constexpr OutputIt rotate_copy( ForwardIt first, ForwardIt n_first, ForwardIt last, OutputIt d_first ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 > ForwardIt2 rotate_copy( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 n_first, ForwardIt1 last, ForwardIt2 d_first ); ``` | (2) | (since C++17) | 1) Copies the elements from the range `[first, last)`, to another range beginning at `d_first` in such a way, that the element `*(n_first)` becomes the first element of the new range and `*(n_first - 1)` becomes the last element. The behavior is undefined if either `[first, n_first)` or `[n_first, last)` is not a valid range, or the source and destination ranges overlap. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to copy | | n\_first | - | an iterator to an element in `[first, last)` that should appear at the beginning of the new range | | d\_first | - | beginning of the destination range | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | Type requirements | | -`ForwardIt, ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | ### Return value Output iterator to the element past the last element copied. ### Complexity linear in the distance between `first` and `last`. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/14d8a5ae472ca5743016f37da2dd4770d83dea21/libstdc%2B%2B-v3/include/bits/stl_algo.h#L1440-L1455), [libc++](https://github.com/llvm/llvm-project/tree/f221d905b131158cbe3cbc4320d1ecd1376c3f22/libcxx/include/__algorithm/rotate_copy.h), and [MSVC STL](https://github.com/microsoft/STL/blob/472161105d596192194d4715ccad307c6c163b4a/stl/inc/algorithm#L4438-L4459). | | | --- | | ``` template<class ForwardIt, class OutputIt> constexpr // since C++20 OutputIt rotate_copy(ForwardIt first, ForwardIt n_first, ForwardIt last, OutputIt d_first) { d_first = std::copy(n_first, last, d_first); return std::copy(first, n_first, d_first); } ``` | ### Example ``` #include <algorithm> #include <vector> #include <iostream> #include <iterator> int main() { std::vector<int> src = {1, 2, 3, 4, 5}; std::vector<int> dest(src.size()); auto pivot = std::find(src.begin(), src.end(), 3); std::rotate_copy(src.begin(), pivot, src.end(), dest.begin()); for (int i : dest) { std::cout << i << ' '; } std::cout << '\n'; // copy the rotation result directly to the std::cout pivot = std::find(dest.begin(), dest.end(), 1); std::rotate_copy(dest.begin(), pivot, dest.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; } ``` Output: ``` 3 4 5 1 2 1 2 3 4 5 ``` ### See also | | | | --- | --- | | [rotate](rotate "cpp/algorithm/rotate") | rotates the order of elements in a range (function template) | | [ranges::rotate\_copy](ranges/rotate_copy "cpp/algorithm/ranges/rotate copy") (C++20) | copies and rotate a range of elements (niebloid) | cpp std::partial_sort_copy std::partial\_sort\_copy ======================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class RandomIt > RandomIt partial_sort_copy( InputIt first, InputIt last, RandomIt d_first, RandomIt d_last ); ``` | (until C++20) | | ``` template< class InputIt, class RandomIt > constexpr RandomIt partial_sort_copy( InputIt first, InputIt last, RandomIt d_first, RandomIt d_last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class RandomIt > RandomIt partial_sort_copy( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, RandomIt d_first, RandomIt d_last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt, class RandomIt, class Compare > RandomIt partial_sort_copy( InputIt first, InputIt last, RandomIt d_first, RandomIt d_last, Compare comp ); ``` | (until C++20) | | ``` template< class InputIt, class RandomIt, class Compare > constexpr RandomIt partial_sort_copy( InputIt first, InputIt last, RandomIt d_first, RandomIt d_last, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class RandomIt, class Compare > RandomIt partial_sort_copy( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, RandomIt d_first, RandomIt d_last, Compare comp ); ``` | (4) | (since C++17) | Sorts some of the elements in the range `[first, last)` in ascending order, storing the result in the range `[d_first, d_last)`. At most `d_last - d_first` of the elements are placed sorted to the range `[d_first, d_first + n)`. `n` is the number of elements to sort (`n = min(last - first, d_last - d_first)`). The order of equal elements is not guaranteed to be preserved. 1) Elements are compared using `operator<`. 3) Elements are compared using the given binary comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to sort | | d\_first, d\_last | - | random access iterators defining the destination range | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `RandomIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`RandomIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). | | -The type of dereferenced `RandomIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). | ### Return value an iterator to the element defining the upper boundary of the sorted range, i.e. `d_first + min(last - first, d_last - d_first)`. ### Complexity O(N·log(min(D,N)), where `N = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first, last)`, `D = [std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(d_first, d_last)` applications of `cmp`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L1669) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L5064). ### Example The following code sorts a vector of integers and copies them into a smaller and a larger vector. ``` #include <algorithm> #include <vector> #include <functional> #include <iostream> int main() { const auto v0 = {4, 2, 5, 1, 3}; std::vector<int> v1{10, 11, 12}; std::vector<int> v2{10, 11, 12, 13, 14, 15, 16}; std::vector<int>::iterator it; it = std::partial_sort_copy(v0.begin(), v0.end(), v1.begin(), v1.end()); std::cout << "Writing to the smaller vector in ascending order gives: "; for (int a : v1) { std::cout << a << " "; } std::cout << '\n'; if(it == v1.end()) std::cout << "The return value is the end iterator\n"; it = std::partial_sort_copy(v0.begin(), v0.end(), v2.begin(), v2.end(), std::greater<int>()); std::cout << "Writing to the larger vector in descending order gives: "; for (int a : v2) { std::cout << a << " "; } std::cout << '\n' << "The return value is the iterator to " << *it << '\n'; } ``` Output: ``` Writing to the smaller vector in ascending order gives: 1 2 3 The return value is the end iterator Writing to the larger vector in descending order gives: 5 4 3 2 1 15 16 The return value is the iterator to 15 ``` ### See also | | | | --- | --- | | [partial\_sort](partial_sort "cpp/algorithm/partial sort") | sorts the first N elements of a range (function template) | | [sort](sort "cpp/algorithm/sort") | sorts a range into ascending order (function template) | | [stable\_sort](stable_sort "cpp/algorithm/stable sort") | sorts a range of elements while preserving order between equal elements (function template) | | [ranges::partial\_sort\_copy](ranges/partial_sort_copy "cpp/algorithm/ranges/partial sort copy") (C++20) | copies and partially sorts a range of elements (niebloid) |
programming_docs
cpp std::transform_inclusive_scan std::transform\_inclusive\_scan =============================== | Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class OutputIt, class BinaryOperation, class UnaryOperation > OutputIt transform_inclusive_scan( InputIt first, InputIt last, OutputIt d_first, BinaryOperation binary_op, UnaryOperation unary_op ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt, class OutputIt, class BinaryOperation, class UnaryOperation > constexpr OutputIt transform_inclusive_scan( InputIt first, InputIt last, OutputIt d_first, BinaryOperation binary_op, UnaryOperation unary_op ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryOperation, class UnaryOperation > ForwardIt2 transform_inclusive_scan( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, BinaryOperation binary_op, UnaryOperation unary_op ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt, class OutputIt, class BinaryOperation, class UnaryOperation, class T > OutputIt transform_inclusive_scan( InputIt first, InputIt last, OutputIt d_first, BinaryOperation binary_op, UnaryOperation unary_op, T init ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt, class OutputIt, class BinaryOperation, class UnaryOperation, class T > constexpr OutputIt transform_inclusive_scan( InputIt first, InputIt last, OutputIt d_first, BinaryOperation binary_op, UnaryOperation unary_op, T init ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryOperation, class UnaryOperation, class T > ForwardIt2 transform_inclusive_scan( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, BinaryOperation binary_op, UnaryOperation unary_op, T init ); ``` | (4) | (since C++17) | Transforms each element in the range `[first, last)` with `unary_op`, then computes an inclusive prefix sum operation using `binary_op` over the resulting range, optionally with `init` as the initial value, and writes the results to the range beginning at `d_first`. "inclusive" means that the i-th input element is included in the i-th sum. Formally, assigns through each iterator `i` in [d\_first, d\_first + (last - first)) the value of. * for overloads (1-2), the generalized noncommutative sum of `unary_op(*j)...` for every `j` in [first, first + (i - d\_first + 1)) over `binary_op`, * for overloads (3-4), the generalized noncommutative sum of `init, unary_op(*j)...` for every `j` in [first, first + (i - d\_first + 1)) over `binary_op`, where generalized noncommutative sum GNSUM(op, a 1, ..., a N) is defined as follows: * if N=1, a 1 * if N > 1, op(GNSUM(op, a 1, ..., a K), GNSUM(op, a M, ..., a N)) for any K where 1 < K+1 = M ≤ N In other words, the summation operations may be performed in arbitrary order, and the behavior is nondeterministic if `binary_op` is not associative. Overloads (2, 4) are executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. `unary_op` and `binary_op` shall not invalidate iterators (including the end iterators) or subranges, nor modify elements in the ranges [first, last) or [d\_first, d\_first + (last - first)). Otherwise, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to sum | | d\_first | - | the beginning of the destination range; may be equal to `first` | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | init | - | the initial value | | unary\_op | - | unary [FunctionObject](../named_req/functionobject "cpp/named req/FunctionObject") that will be applied to each element of the input range. The return type must be acceptable as input to `binary_op`. | | binary\_op | - | binary [FunctionObject](../named_req/functionobject "cpp/named req/FunctionObject") that will be applied in to the result of `unary_op`, the results of other `binary_op`, and `init` if provided. | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -If `init` is not provided, `decltype(first)`'s value type must be [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible") and `binary_op(unary_op(*first), unary_op(*first))` must be convertible to `decltype(first)`'s value type | | -`T (if init is provided)` must meet the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). All of `binary_op(init, unary_op(*first))`, `binary_op(init, init)`, and `binary_op(unary_op(*first), unary_op(*first))` must be convertible to T | ### Return value Iterator to the element past the last element written. ### Complexity O(last - first) applications of each of `binary_op` and `unary_op`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes `unary_op` is not applied to `init`. The parameter `init` appears last, differing from `[std::transform\_exclusive\_scan](transform_exclusive_scan "cpp/algorithm/transform exclusive scan")`, because it is optional for this function. ### Example ``` #include <functional> #include <iostream> #include <iterator> #include <numeric> #include <vector> int main() { std::vector data {3, 1, 4, 1, 5, 9, 2, 6}; auto times_10 = [](int x) { return x * 10; }; std::cout << "10 times exclusive sum: "; std::transform_exclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "), 0, std::plus<int>{}, times_10); std::cout << "\n10 times inclusive sum: "; std::transform_inclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "), std::plus<int>{}, times_10); } ``` Output: ``` 10 times exclusive sum: 0 30 40 80 90 140 230 250 10 times inclusive sum: 30 40 80 90 140 230 250 310 ``` ### See also | | | | --- | --- | | [partial\_sum](partial_sum "cpp/algorithm/partial sum") | computes the partial sum of a range of elements (function template) | | [transform](transform "cpp/algorithm/transform") | applies a function to a range of elements, storing results in a destination range (function template) | | [inclusive\_scan](inclusive_scan "cpp/algorithm/inclusive scan") (C++17) | similar to `[std::partial\_sum](partial_sum "cpp/algorithm/partial sum")`, includes the ith input element in the ith sum (function template) | | [transform\_exclusive\_scan](transform_exclusive_scan "cpp/algorithm/transform exclusive scan") (C++17) | applies an invocable, then calculates exclusive scan (function template) | cpp std::exclusive_scan std::exclusive\_scan ==================== | Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class OutputIt, class T > OutputIt exclusive_scan( InputIt first, InputIt last, OutputIt d_first, T init ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt, class OutputIt, class T > constexpr OutputIt exclusive_scan( InputIt first, InputIt last, OutputIt d_first, T init ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T > ForwardIt2 exclusive_scan( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, T init ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt, class OutputIt, class T, class BinaryOperation > OutputIt exclusive_scan( InputIt first, InputIt last, OutputIt d_first, T init, BinaryOperation binary_op ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt, class OutputIt, class T, class BinaryOperation > constexpr OutputIt exclusive_scan( InputIt first, InputIt last, OutputIt d_first, T init, BinaryOperation binary_op ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T, class BinaryOperation > ForwardIt2 exclusive_scan( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, T init, BinaryOperation binary_op ); ``` | (4) | (since C++17) | Computes an exclusive prefix sum operation using `binary_op` (or `[std::plus](http://en.cppreference.com/w/cpp/utility/functional/plus)<>()` for overloads (1-2)) for the range `[first, last)`, using `init` as the initial value, and writes the results to the range beginning at `d_first`. "exclusive" means that the i-th input element is not included in the i-th sum. Formally, assigns through each iterator `i` in [d\_first, d\_first + (last - first)) the value of the generalized noncommutative sum of `init, *j...` for every `j` in [first, first + (i - d\_first)) over `binary_op`, where generalized noncommutative sum GNSUM(op, a 1, ..., a N) is defined as follows: * if N=1, a 1 * if N > 1, op(GNSUM(op, a 1, ..., a K), GNSUM(op, a M, ..., a N)) for any K where 1 < K+1 = M ≤ N In other words, the summation operations may be performed in arbitrary order, and the behavior is nondeterministic if `binary_op` is not associative. Overloads (2,4) are executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. `binary_op` shall not invalidate iterators (including the end iterators) or subranges, nor modify elements in the ranges [first, last) or [d\_first, d\_first + (last - first)). Otherwise, the behavior is undefined. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to sum | | d\_first | - | the beginning of the destination range; may be equal to `first` | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | init | - | the initial value | | binary\_op | - | binary [FunctionObject](../named_req/functionobject "cpp/named req/FunctionObject") that will be applied in to the result of dereferencing the input iterators, the results of other `binary_op`, and `init`. | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`T` must meet the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). and `binary_op(init, *first)`, `binary_op(init, init)`, and `binary_op(*first, *first)` must be convertible to `T` | ### Return value Iterator to the element past the last element written. ### Complexity O(last - first) applications of the binary operation. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Example ``` #include <functional> #include <iostream> #include <iterator> #include <numeric> #include <vector> int main() { std::vector data {3, 1, 4, 1, 5, 9, 2, 6}; std::cout << "exclusive sum: "; std::exclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "), 0); std::cout << "\ninclusive sum: "; std::inclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n\nexclusive product: "; std::exclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "), 1, std::multiplies<>{}); std::cout << "\ninclusive product: "; std::inclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "), std::multiplies<>{}); } ``` Output: ``` exclusive sum: 0 3 4 8 9 14 23 25 inclusive sum: 3 4 8 9 14 23 25 31 exclusive product: 1 3 3 12 12 60 540 1080 inclusive product: 3 3 12 12 60 540 1080 6480 ``` ### See also | | | | --- | --- | | [adjacent\_difference](adjacent_difference "cpp/algorithm/adjacent difference") | computes the differences between adjacent elements in a range (function template) | | [accumulate](accumulate "cpp/algorithm/accumulate") | sums up a range of elements (function template) | | [partial\_sum](partial_sum "cpp/algorithm/partial sum") | computes the partial sum of a range of elements (function template) | | [transform\_exclusive\_scan](transform_exclusive_scan "cpp/algorithm/transform exclusive scan") (C++17) | applies an invocable, then calculates exclusive scan (function template) | | [inclusive\_scan](inclusive_scan "cpp/algorithm/inclusive scan") (C++17) | similar to `[std::partial\_sum](partial_sum "cpp/algorithm/partial sum")`, includes the ith input element in the ith sum (function template) | cpp Constrained algorithms (since C++20) Constrained algorithms (since C++20) ==================================== C++20 provides [constrained](../language/constraints "cpp/language/constraints") versions of most algorithms in the namespace `std::ranges`. In these algorithms, a range can be specified as either a [iterator](../iterator/input_or_output_iterator "cpp/iterator/input or output iterator")-[sentinel](../iterator/sentinel_for "cpp/iterator/sentinel for") pair or as a single [`range`](../ranges/range "cpp/ranges/range") argument, and projections and pointer-to-member callables are supported. Additionally, the [return types](ranges#Return_types "cpp/algorithm/ranges") of most algorithms have been changed to return all potentially useful information computed during the execution of the algorithm. ### Constrained algorithms | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | --- | | Defined in namespace `std::ranges` | | Non-modifying sequence operations | | [ranges::all\_ofranges::any\_ofranges::none\_of](ranges/all_any_none_of "cpp/algorithm/ranges/all any none of") (C++20)(C++20)(C++20) | checks if a predicate is `true` for all, any or none of the elements in a range (niebloid) | | [ranges::for\_each](ranges/for_each "cpp/algorithm/ranges/for each") (C++20) | applies a function to a range of elements (niebloid) | | [ranges::for\_each\_n](ranges/for_each_n "cpp/algorithm/ranges/for each n") (C++20) | applies a function object to the first n elements of a sequence (niebloid) | | [ranges::countranges::count\_if](ranges/count "cpp/algorithm/ranges/count") (C++20)(C++20) | returns the number of elements satisfying specific criteria (niebloid) | | [ranges::mismatch](ranges/mismatch "cpp/algorithm/ranges/mismatch") (C++20) | finds the first position where two ranges differ (niebloid) | | [ranges::equal](ranges/equal "cpp/algorithm/ranges/equal") (C++20) | determines if two sets of elements are the same (niebloid) | | [ranges::lexicographical\_compare](ranges/lexicographical_compare "cpp/algorithm/ranges/lexicographical compare") (C++20) | returns true if one range is lexicographically less than another (niebloid) | | [ranges::findranges::find\_ifranges::find\_if\_not](ranges/find "cpp/algorithm/ranges/find") (C++20)(C++20)(C++20) | finds the first element satisfying specific criteria (niebloid) | | [ranges::find\_lastranges::find\_last\_ifranges::find\_last\_if\_not](ranges/find_last "cpp/algorithm/ranges/find last") (C++23)(C++23)(C++23) | finds the last element satisfying specific criteria (niebloid) | | [ranges::find\_end](ranges/find_end "cpp/algorithm/ranges/find end") (C++20) | finds the last sequence of elements in a certain range (niebloid) | | [ranges::find\_first\_of](ranges/find_first_of "cpp/algorithm/ranges/find first of") (C++20) | searches for any one of a set of elements (niebloid) | | [ranges::adjacent\_find](ranges/adjacent_find "cpp/algorithm/ranges/adjacent find") (C++20) | finds the first two adjacent items that are equal (or satisfy a given predicate) (niebloid) | | [ranges::search](ranges/search "cpp/algorithm/ranges/search") (C++20) | searches for a range of elements (niebloid) | | [ranges::search\_n](ranges/search_n "cpp/algorithm/ranges/search n") (C++20) | searches for a number consecutive copies of an element in a range (niebloid) | | [ranges::containsranges::contains\_subrange](ranges/contains "cpp/algorithm/ranges/contains") (C++23)(C++23) | checks if the range contains the given element or subrange (niebloid) | | [ranges::starts\_with](ranges/starts_with "cpp/algorithm/ranges/starts with") (C++23) | checks whether a range starts with another range (niebloid) | | [ranges::ends\_with](ranges/ends_with "cpp/algorithm/ranges/ends with") (C++23) | checks whether a range ends with another range (niebloid) | | Modifying sequence operations | | [ranges::copyranges::copy\_if](ranges/copy "cpp/algorithm/ranges/copy") (C++20)(C++20) | copies a range of elements to a new location (niebloid) | | [ranges::copy\_n](ranges/copy_n "cpp/algorithm/ranges/copy n") (C++20) | copies a number of elements to a new location (niebloid) | | [ranges::copy\_backward](ranges/copy_backward "cpp/algorithm/ranges/copy backward") (C++20) | copies a range of elements in backwards order (niebloid) | | [ranges::move](ranges/move "cpp/algorithm/ranges/move") (C++20) | moves a range of elements to a new location (niebloid) | | [ranges::move\_backward](ranges/move_backward "cpp/algorithm/ranges/move backward") (C++20) | moves a range of elements to a new location in backwards order (niebloid) | | [ranges::fill](ranges/fill "cpp/algorithm/ranges/fill") (C++20) | assigns a range of elements a certain value (niebloid) | | [ranges::fill\_n](ranges/fill_n "cpp/algorithm/ranges/fill n") (C++20) | assigns a value to a number of elements (niebloid) | | [ranges::transform](ranges/transform "cpp/algorithm/ranges/transform") (C++20) | applies a function to a range of elements (niebloid) | | [ranges::generate](ranges/generate "cpp/algorithm/ranges/generate") (C++20) | saves the result of a function in a range (niebloid) | | [ranges::generate\_n](ranges/generate_n "cpp/algorithm/ranges/generate n") (C++20) | saves the result of N applications of a function (niebloid) | | [ranges::removeranges::remove\_if](ranges/remove "cpp/algorithm/ranges/remove") (C++20)(C++20) | removes elements satisfying specific criteria (niebloid) | | [ranges::remove\_copyranges::remove\_copy\_if](ranges/remove_copy "cpp/algorithm/ranges/remove copy") (C++20)(C++20) | copies a range of elements omitting those that satisfy specific criteria (niebloid) | | [ranges::replaceranges::replace\_if](ranges/replace "cpp/algorithm/ranges/replace") (C++20)(C++20) | replaces all values satisfying specific criteria with another value (niebloid) | | [ranges::replace\_copyranges::replace\_copy\_if](ranges/replace_copy "cpp/algorithm/ranges/replace copy") (C++20)(C++20) | copies a range, replacing elements satisfying specific criteria with another value (niebloid) | | [ranges::swap\_ranges](ranges/swap_ranges "cpp/algorithm/ranges/swap ranges") (C++20) | swaps two ranges of elements (niebloid) | | [ranges::reverse](ranges/reverse "cpp/algorithm/ranges/reverse") (C++20) | reverses the order of elements in a range (niebloid) | | [ranges::reverse\_copy](ranges/reverse_copy "cpp/algorithm/ranges/reverse copy") (C++20) | creates a copy of a range that is reversed (niebloid) | | [ranges::rotate](ranges/rotate "cpp/algorithm/ranges/rotate") (C++20) | rotates the order of elements in a range (niebloid) | | [ranges::rotate\_copy](ranges/rotate_copy "cpp/algorithm/ranges/rotate copy") (C++20) | copies and rotate a range of elements (niebloid) | | [ranges::shuffle](ranges/shuffle "cpp/algorithm/ranges/shuffle") (C++20) | randomly re-orders elements in a range (niebloid) | | [ranges::shift\_leftranges::shift\_right](ranges/shift "cpp/algorithm/ranges/shift") (C++23) | shifts elements in a range (niebloid) | | [ranges::sample](ranges/sample "cpp/algorithm/ranges/sample") (C++20) | selects n random elements from a sequence (niebloid) | | [ranges::unique](ranges/unique "cpp/algorithm/ranges/unique") (C++20) | removes consecutive duplicate elements in a range (niebloid) | | [ranges::unique\_copy](ranges/unique_copy "cpp/algorithm/ranges/unique copy") (C++20) | creates a copy of some range of elements that contains no consecutive duplicates (niebloid) | | Partitioning operations | | [ranges::is\_partitioned](ranges/is_partitioned "cpp/algorithm/ranges/is partitioned") (C++20) | determines if the range is partitioned by the given predicate (niebloid) | | [ranges::partition](ranges/partition "cpp/algorithm/ranges/partition") (C++20) | divides a range of elements into two groups (niebloid) | | [ranges::partition\_copy](ranges/partition_copy "cpp/algorithm/ranges/partition copy") (C++20) | copies a range dividing the elements into two groups (niebloid) | | [ranges::stable\_partition](ranges/stable_partition "cpp/algorithm/ranges/stable partition") (C++20) | divides elements into two groups while preserving their relative order (niebloid) | | [ranges::partition\_point](ranges/partition_point "cpp/algorithm/ranges/partition point") (C++20) | locates the partition point of a partitioned range (niebloid) | | Sorting operations | | [ranges::is\_sorted](ranges/is_sorted "cpp/algorithm/ranges/is sorted") (C++20) | checks whether a range is sorted into ascending order (niebloid) | | [ranges::is\_sorted\_until](ranges/is_sorted_until "cpp/algorithm/ranges/is sorted until") (C++20) | finds the largest sorted subrange (niebloid) | | [ranges::sort](ranges/sort "cpp/algorithm/ranges/sort") (C++20) | sorts a range into ascending order (niebloid) | | [ranges::partial\_sort](ranges/partial_sort "cpp/algorithm/ranges/partial sort") (C++20) | sorts the first N elements of a range (niebloid) | | [ranges::partial\_sort\_copy](ranges/partial_sort_copy "cpp/algorithm/ranges/partial sort copy") (C++20) | copies and partially sorts a range of elements (niebloid) | | [ranges::stable\_sort](ranges/stable_sort "cpp/algorithm/ranges/stable sort") (C++20) | sorts a range of elements while preserving order between equal elements (niebloid) | | [ranges::nth\_element](ranges/nth_element "cpp/algorithm/ranges/nth element") (C++20) | partially sorts the given range making sure that it is partitioned by the given element (niebloid) | | Binary search operations (on sorted ranges) | | [ranges::lower\_bound](ranges/lower_bound "cpp/algorithm/ranges/lower bound") (C++20) | returns an iterator to the first element *not less* than the given value (niebloid) | | [ranges::upper\_bound](ranges/upper_bound "cpp/algorithm/ranges/upper bound") (C++20) | returns an iterator to the first element *greater* than a certain value (niebloid) | | [ranges::binary\_search](ranges/binary_search "cpp/algorithm/ranges/binary search") (C++20) | determines if an element exists in a partially-ordered range (niebloid) | | [ranges::equal\_range](ranges/equal_range "cpp/algorithm/ranges/equal range") (C++20) | returns range of elements matching a specific key (niebloid) | | Set operations (on sorted ranges) | | [ranges::merge](ranges/merge "cpp/algorithm/ranges/merge") (C++20) | merges two sorted ranges (niebloid) | | [ranges::inplace\_merge](ranges/inplace_merge "cpp/algorithm/ranges/inplace merge") (C++20) | merges two ordered ranges in-place (niebloid) | | [ranges::includes](ranges/includes "cpp/algorithm/ranges/includes") (C++20) | returns true if one sequence is a subsequence of another (niebloid) | | [ranges::set\_difference](ranges/set_difference "cpp/algorithm/ranges/set difference") (C++20) | computes the difference between two sets (niebloid) | | [ranges::set\_intersection](ranges/set_intersection "cpp/algorithm/ranges/set intersection") (C++20) | computes the intersection of two sets (niebloid) | | [ranges::set\_symmetric\_difference](ranges/set_symmetric_difference "cpp/algorithm/ranges/set symmetric difference") (C++20) | computes the symmetric difference between two sets (niebloid) | | [ranges::set\_union](ranges/set_union "cpp/algorithm/ranges/set union") (C++20) | computes the union of two sets (niebloid) | | Heap operations | | [ranges::is\_heap](ranges/is_heap "cpp/algorithm/ranges/is heap") (C++20) | checks if the given range is a max heap (niebloid) | | [ranges::is\_heap\_until](ranges/is_heap_until "cpp/algorithm/ranges/is heap until") (C++20) | finds the largest subrange that is a max heap (niebloid) | | [ranges::make\_heap](ranges/make_heap "cpp/algorithm/ranges/make heap") (C++20) | creates a max heap out of a range of elements (niebloid) | | [ranges::push\_heap](ranges/push_heap "cpp/algorithm/ranges/push heap") (C++20) | adds an element to a max heap (niebloid) | | [ranges::pop\_heap](ranges/pop_heap "cpp/algorithm/ranges/pop heap") (C++20) | removes the largest element from a max heap (niebloid) | | [ranges::sort\_heap](ranges/sort_heap "cpp/algorithm/ranges/sort heap") (C++20) | turns a max heap into a range of elements sorted in ascending order (niebloid) | | Minimum/maximum operations | | [ranges::max](ranges/max "cpp/algorithm/ranges/max") (C++20) | returns the greater of the given values (niebloid) | | [ranges::max\_element](ranges/max_element "cpp/algorithm/ranges/max element") (C++20) | returns the largest element in a range (niebloid) | | [ranges::min](ranges/min "cpp/algorithm/ranges/min") (C++20) | returns the smaller of the given values (niebloid) | | [ranges::min\_element](ranges/min_element "cpp/algorithm/ranges/min element") (C++20) | returns the smallest element in a range (niebloid) | | [ranges::minmax](ranges/minmax "cpp/algorithm/ranges/minmax") (C++20) | returns the smaller and larger of two elements (niebloid) | | [ranges::minmax\_element](ranges/minmax_element "cpp/algorithm/ranges/minmax element") (C++20) | returns the smallest and the largest elements in a range (niebloid) | | [ranges::clamp](ranges/clamp "cpp/algorithm/ranges/clamp") (C++20) | clamps a value between a pair of boundary values (niebloid) | | Permutation operations | | [ranges::is\_permutation](ranges/is_permutation "cpp/algorithm/ranges/is permutation") (C++20) | determines if a sequence is a permutation of another sequence (niebloid) | | [ranges::next\_permutation](ranges/next_permutation "cpp/algorithm/ranges/next permutation") (C++20) | generates the next greater lexicographic permutation of a range of elements (niebloid) | | [ranges::prev\_permutation](ranges/prev_permutation "cpp/algorithm/ranges/prev permutation") (C++20) | generates the next smaller lexicographic permutation of a range of elements (niebloid) | ### Constrained numeric operations | Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | --- | | Defined in namespace `std::ranges` | | [ranges::iota](ranges/iota "cpp/algorithm/ranges/iota") (C++23) | fills a range with successive increments of the starting value (niebloid) | ### Constrained uninitialized memory algorithms | Defined in header `[<memory>](../header/memory "cpp/header/memory")` | | --- | | Defined in namespace `std::ranges` | | [ranges::uninitialized\_copy](../memory/ranges/uninitialized_copy "cpp/memory/ranges/uninitialized copy") (C++20) | copies a range of objects to an uninitialized area of memory (niebloid) | | [ranges::uninitialized\_copy\_n](../memory/ranges/uninitialized_copy_n "cpp/memory/ranges/uninitialized copy n") (C++20) | copies a number of objects to an uninitialized area of memory (niebloid) | | [ranges::uninitialized\_fill](../memory/ranges/uninitialized_fill "cpp/memory/ranges/uninitialized fill") (C++20) | copies an object to an uninitialized area of memory, defined by a range (niebloid) | | [ranges::uninitialized\_fill\_n](../memory/ranges/uninitialized_fill_n "cpp/memory/ranges/uninitialized fill n") (C++20) | copies an object to an uninitialized area of memory, defined by a start and a count (niebloid) | | [ranges::uninitialized\_move](../memory/ranges/uninitialized_move "cpp/memory/ranges/uninitialized move") (C++20) | moves a range of objects to an uninitialized area of memory (niebloid) | | [ranges::uninitialized\_move\_n](../memory/ranges/uninitialized_move_n "cpp/memory/ranges/uninitialized move n") (C++20) | moves a number of objects to an uninitialized area of memory (niebloid) | | [ranges::uninitialized\_default\_construct](../memory/ranges/uninitialized_default_construct "cpp/memory/ranges/uninitialized default construct") (C++20) | constructs objects by [default-initialization](../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a range (niebloid) | | [ranges::uninitialized\_default\_construct\_n](../memory/ranges/uninitialized_default_construct_n "cpp/memory/ranges/uninitialized default construct n") (C++20) | constructs objects by [default-initialization](../language/default_initialization "cpp/language/default initialization") in an uninitialized area of memory, defined by a start and count (niebloid) | | [ranges::uninitialized\_value\_construct](../memory/ranges/uninitialized_value_construct "cpp/memory/ranges/uninitialized value construct") (C++20) | constructs objects by [value-initialization](../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a range (niebloid) | | [ranges::uninitialized\_value\_construct\_n](../memory/ranges/uninitialized_value_construct_n "cpp/memory/ranges/uninitialized value construct n") (C++20) | constructs objects by [value-initialization](../language/value_initialization "cpp/language/value initialization") in an uninitialized area of memory, defined by a start and a count (niebloid) | | [ranges::destroy](../memory/ranges/destroy "cpp/memory/ranges/destroy") (C++20) | destroys a range of objects (niebloid) | | [ranges::destroy\_n](../memory/ranges/destroy_n "cpp/memory/ranges/destroy n") (C++20) | destroys a number of objects in a range (niebloid) | | [ranges::destroy\_at](../memory/ranges/destroy_at "cpp/memory/ranges/destroy at") (C++20) | destroys an object at a given address (niebloid) | | [ranges::construct\_at](../memory/ranges/construct_at "cpp/memory/ranges/construct at") (C++20) | creates an object at a given address (niebloid) | ### Return types | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | --- | | Defined in namespace `std::ranges` | | [ranges::in\_fun\_result](ranges/return_types/in_fun_result "cpp/algorithm/ranges/return types/in fun result") (C++20) | provides a way to store an iterator and a function object as a single unit (class template) | | [ranges::in\_in\_result](ranges/return_types/in_in_result "cpp/algorithm/ranges/return types/in in result") (C++20) | provides a way to store two iterators as a single unit (class template) | | [ranges::in\_out\_result](ranges/return_types/in_out_result "cpp/algorithm/ranges/return types/in out result") (C++20) | provides a way to store two iterators as a single unit (class template) | | [ranges::in\_in\_out\_result](ranges/return_types/in_in_out_result "cpp/algorithm/ranges/return types/in in out result") (C++20) | provides a way to store three iterators as a single unit (class template) | | [ranges::in\_out\_out\_result](ranges/return_types/in_out_out_result "cpp/algorithm/ranges/return types/in out out result") (C++20) | provides a way to store three iterators as a single unit (class template) | | [ranges::min\_max\_result](ranges/return_types/min_max_result "cpp/algorithm/ranges/return types/min max result") (C++20) | provides a way to store two objects or references of the same type as a single unit (class template) | | [ranges::in\_found\_result](ranges/return_types/in_found_result "cpp/algorithm/ranges/return types/in found result") (C++20) | provides a way to store an iterator and a boolean flag as a single unit (class template) | | [ranges::in\_value\_result](ranges/return_types/in_value_result "cpp/algorithm/ranges/return types/in value result") (C++23) | provides a way to store an iterator and a value as a single unit (class template) | | [ranges::out\_value\_result](ranges/return_types/out_value_result "cpp/algorithm/ranges/return types/out value result") (C++23) | provides a way to store an iterator and a value as a single unit (class template) | ### Notes | [Feature-test](../utility/feature_test "cpp/utility/feature test") macro | Value | Std | | --- | --- | --- | | [`__cpp_lib_find_last`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | | [`__cpp_lib_ranges`](../feature_test#Library_features "cpp/feature test") | `201911L` | (C++20) | | [`__cpp_lib_ranges`](../feature_test#Library_features "cpp/feature test") | `202106L` | (C++20) | | [`__cpp_lib_ranges`](../feature_test#Library_features "cpp/feature test") | `202110L` | (C++20) | | [`__cpp_lib_ranges`](../feature_test#Library_features "cpp/feature test") | `202202L` | (C++23) | | [`__cpp_lib_ranges_contains`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | | [`__cpp_lib_ranges_fold`](../feature_test#Library_features "cpp/feature test") | `202207L` | (C++23) | | [`__cpp_lib_ranges_iota`](../feature_test#Library_features "cpp/feature test") | `202202L` | (C++23) | | [`__cpp_lib_ranges_starts_ends_with`](../feature_test#Library_features "cpp/feature test") | `202106L` | (C++23) | | [`__cpp_lib_shift`](../feature_test#Library_features "cpp/feature test") | `201806L` | (C++20) | | [`__cpp_lib_shift`](../feature_test#Library_features "cpp/feature test") | `202202L` | (C++23) |
programming_docs
cpp std::set_intersection std::set\_intersection ====================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt1, class InputIt2, class OutputIt > OutputIt set_intersection( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class OutputIt > constexpr OutputIt set_intersection( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class ForwardIt3 > ForwardIt3 set_intersection( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, ForwardIt3 d_first ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt1, class InputIt2, class OutputIt, class Compare > OutputIt set_intersection( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp ); ``` | (until C++20) | | ``` template< class InputIt1, class InputIt2, class OutputIt, class Compare > constexpr OutputIt set_intersection( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class ForwardIt3, class Compare > ForwardIt3 set_intersection( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2, ForwardIt3 d_first, Compare comp ); ``` | (4) | (since C++17) | Constructs a sorted range beginning at `d_first` consisting of elements that are found in both sorted ranges `[first1, last1)` and `[first2, last2)`. If some element is found `m` times in `[first1, last1)` and `n` times in `[first2, last2)`, the first `[std::min](http://en.cppreference.com/w/cpp/algorithm/min)(m, n)` elements will be copied from the first range to the destination range. The order of equivalent elements is preserved. The resulting range cannot overlap with either of the input ranges. 1) Elements are compared using `operator<` and the ranges must be sorted with respect to the same. 3) Elements are compared using the given binary comparison function `comp` and the ranges must be sorted with respect to the same. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first1, last1 | - | the first range of elements to examine | | first2, last2 | - | the second range of elements to examine | | d\_first | - | the beginning of the destination range | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that objects of types `InputIt1` and `InputIt2` can be dereferenced and then implicitly converted to both `Type1` and `Type2`. ​ | | Type requirements | | -`InputIt1, InputIt2` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1, ForwardIt2, ForwardIt3` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value Iterator past the end of the constructed range. ### Complexity At most \(\scriptsize 2\cdot(N\_1+N\_2)-1\)2·(N 1+N 2)-1 comparisons, where \(\scriptsize N\_1\)N 1 and \(\scriptsize N\_2\)N 2 are `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first1, last1)` and `[std::distance](http://en.cppreference.com/w/cpp/iterator/distance)(first2, last2)`, respectively. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class InputIt1, class InputIt2, class OutputIt> OutputIt set_intersection(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first) { while (first1 != last1 && first2 != last2) { if (*first1 < *first2) { ++first1; } else { if (!(*first2 < *first1)) { *d_first++ = *first1++; // *first1 and *first2 are equivalent. } ++first2; } } return d_first; } ``` | | Second version | | ``` template<class InputIt1, class InputIt2, class OutputIt, class Compare> OutputIt set_intersection(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp) { while (first1 != last1 && first2 != last2) { if (comp(*first1, *first2)) { ++first1; } else { if (!comp(*first2, *first1)) { *d_first++ = *first1++; // *first1 and *first2 are equivalent. } ++first2; } } return d_first; } ``` | ### Example ``` #include <iostream> #include <vector> #include <algorithm> #include <iterator> int main() { std::vector<int> v1{1,2,3,4,5,6,7,8}; std::vector<int> v2{ 5, 7, 9,10}; std::sort(v1.begin(), v1.end()); std::sort(v2.begin(), v2.end()); std::vector<int> v_intersection; std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v_intersection)); for(int n : v_intersection) std::cout << n << ' '; } ``` Output: ``` 5 7 ``` ### See also | | | | --- | --- | | [set\_union](set_union "cpp/algorithm/set union") | computes the union of two sets (function template) | | [ranges::set\_intersection](ranges/set_intersection "cpp/algorithm/ranges/set intersection") (C++20) | computes the intersection of two sets (niebloid) | cpp std::rotate std::rotate =========== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt > void rotate( ForwardIt first, ForwardIt n_first, ForwardIt last ); ``` | (until C++11) | | ``` template< class ForwardIt > ForwardIt rotate( ForwardIt first, ForwardIt n_first, ForwardIt last ); ``` | (since C++11) (until C++20) | | ``` template< class ForwardIt > constexpr ForwardIt rotate( ForwardIt first, ForwardIt n_first, ForwardIt last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt > ForwardIt rotate( ExecutionPolicy&& policy, ForwardIt first, ForwardIt n_first, ForwardIt last ); ``` | (2) | (since C++17) | 1) Performs a left rotation on a range of elements. Specifically, `std::rotate` swaps the elements in the range `[first, last)` in such a way that the element `n_first` becomes the first element of the new range and `n_first - 1` becomes the last element. A precondition of this function is that `[first, n_first)` and `[n_first, last)` are valid ranges. 2) Same as (1), but executed according to `policy`. This overload does not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first | - | the beginning of the original range | | n\_first | - | the element that should appear at the beginning of the rotated range | | last | - | the end of the original range | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | Type requirements | | -`ForwardIt` must meet the requirements of [ValueSwappable](../named_req/valueswappable "cpp/named req/ValueSwappable") and [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -The type of dereferenced `ForwardIt` must meet the requirements of [MoveAssignable](../named_req/moveassignable "cpp/named req/MoveAssignable") and [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). | ### Return value | | | | --- | --- | | (none). | (until C++11) | | Iterator to the new location of the element pointed by `first`. Equal to `first + (last - n_first)`. | (since C++11) | ### Complexity Linear in the distance between `first` and `last`. ### Exceptions The overload with a template parameter named `ExecutionPolicy` reports errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes `std::rotate` has better efficiency on common implementations if `ForwardIt` statisfies [LegacyBidirectionalIterator](../named_req/bidirectionaliterator "cpp/named req/BidirectionalIterator") or (better) [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). Implementations (e.g. [MSVC STL](https://github.com/microsoft/STL/blob/main/stl/src/vector_algorithms.cpp)) may enable vectorization when the iterator type satisfies [LegacyContiguousIterator](../named_req/contiguousiterator "cpp/named req/ContiguousIterator") and swapping its value type calls neither non-trivial special member function nor [ADL](../language/adl "cpp/language/adl")-found `swap`. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/14d8a5ae472ca5743016f37da2dd4770d83dea21/libstdc%2B%2B-v3/include/bits/stl_algo.h#L1213-L1416), [libc++](https://github.com/llvm/llvm-project/tree/6adbc83ee9e46b476e0f75d5671c3a21f675a936/libcxx/include/__algorithm/rotate.h), and [MSVC STL](https://github.com/microsoft/STL/blob/472161105d596192194d4715ccad307c6c163b4a/stl/inc/xutility#L5392-L5446). | | | --- | | ``` template<class ForwardIt> constexpr // since C++20 ForwardIt // void until C++11 rotate(ForwardIt first, ForwardIt n_first, ForwardIt last) { if(first == n_first) return last; if(n_first == last) return first; ForwardIt read = n_first; ForwardIt write = first; ForwardIt next_read = first; // read position for when "read" hits "last" while(read != last) { if(write == next_read) next_read = read; // track where "first" went std::iter_swap(write++, read++); } // rotate the remaining sequence into place (rotate)(write, next_read, last); return write; } ``` | ### Example `std::rotate` is a common building block in many algorithms. This example demonstrates [insertion sort](https://en.wikipedia.org/wiki/insertion_sort "enwiki:insertion sort"). ``` #include <vector> #include <iostream> #include <algorithm> auto print = [](auto const& remark, auto const& v) { std::cout << remark; for (int n: v) std::cout << n << ' '; std::cout << '\n'; }; int main() { std::vector<int> v{2, 4, 2, 0, 5, 10, 7, 3, 7, 1}; print("before sort:\t\t", v); // insertion sort for (auto i = v.begin(); i != v.end(); ++i) { std::rotate(std::upper_bound(v.begin(), i, *i), i, i+1); } print("after sort:\t\t", v); // simple rotation to the left std::rotate(v.begin(), v.begin() + 1, v.end()); print("simple rotate left:\t", v); // simple rotation to the right std::rotate(v.rbegin(), v.rbegin() + 1, v.rend()); print("simple rotate right:\t", v); } ``` Output: ``` before sort: 2 4 2 0 5 10 7 3 7 1 after sort: 0 1 2 2 3 4 5 7 7 10 simple rotate left: 1 2 2 3 4 5 7 7 10 0 simple rotate right: 0 1 2 2 3 4 5 7 7 10 ``` ### See also | | | | --- | --- | | [rotate\_copy](rotate_copy "cpp/algorithm/rotate copy") | copies and rotate a range of elements (function template) | | [ranges::rotate](ranges/rotate "cpp/algorithm/ranges/rotate") (C++20) | rotates the order of elements in a range (niebloid) | cpp std::replace_copy, std::replace_copy_if std::replace\_copy, std::replace\_copy\_if ========================================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt, class OutputIt, class T > OutputIt replace_copy( InputIt first, InputIt last, OutputIt d_first, const T& old_value, const T& new_value ); ``` | (until C++20) | | ``` template< class InputIt, class OutputIt, class T > constexpr OutputIt replace_copy( InputIt first, InputIt last, OutputIt d_first, const T& old_value, const T& new_value ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T > ForwardIt2 replace_copy( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, const T& old_value, const T& new_value ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt, class OutputIt, class UnaryPredicate, class T > OutputIt replace_copy_if( InputIt first, InputIt last, OutputIt d_first, UnaryPredicate p, const T& new_value ); ``` | (until C++20) | | ``` template< class InputIt, class OutputIt, class UnaryPredicate, class T > constexpr OutputIt replace_copy_if( InputIt first, InputIt last, OutputIt d_first, UnaryPredicate p, const T& new_value ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class UnaryPredicate, class T > ForwardIt2 replace_copy_if( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first, UnaryPredicate p, const T& new_value ); ``` | (4) | (since C++17) | Copies the elements from the range `[first, last)` to another range beginning at `d_first` replacing all elements satisfying specific criteria with `new_value`. The source and destination ranges cannot overlap. 1) Replaces all elements that are equal to `old_value`. 3) Replaces all elements for which predicate `p` returns `true`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to copy | | d\_first | - | the beginning of the destination range | | old\_value | - | the value of elements to replace | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | p | - | unary predicate which returns ​`true` if the element value should be replaced. The expression `p(v)` must be convertible to `bool` for every argument `v` of type (possibly const) `VT`, where `VT` is the value type of `InputIt`, regardless of [value category](../language/value_category "cpp/language/value category"), and must not modify `v`. Thus, a parameter type of `VT&`is not allowed, nor is `VT` unless for `VT` a move is equivalent to a copy (since C++11). ​ | | new\_value | - | the value to use as replacement | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`OutputIt` must meet the requirements of [LegacyOutputIterator](../named_req/outputiterator "cpp/named req/OutputIterator"). | | -`ForwardIt1, ForwardIt2` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value Iterator to the element past the last element copied. ### Complexity Exactly `last - first` applications of the predicate. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation | First version | | --- | | ``` template<class InputIt, class OutputIt, class T> OutputIt replace_copy(InputIt first, InputIt last, OutputIt d_first, const T& old_value, const T& new_value) { for (; first != last; ++first) { *d_first++ = (*first == old_value) ? new_value : *first; } return d_first; } ``` | | Second version | | ``` template<class InputIt, class OutputIt, class UnaryPredicate, class T> OutputIt replace_copy_if(InputIt first, InputIt last, OutputIt d_first, UnaryPredicate p, const T& new_value) { for (; first != last; ++first) { *d_first++ = p( *first ) ? new_value : *first; } return d_first; } ``` | ### Example The following copy prints a vector, replacing all values over 5 with 99 on the fly. ``` #include <algorithm> #include <vector> #include <iostream> #include <iterator> #include <functional> int main() { std::vector<int> v{5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; std::replace_copy_if(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "), [](int n){return n > 5;}, 99); std::cout << '\n'; } ``` Output: ``` 5 99 4 2 99 99 1 99 0 3 ``` ### See also | | | | --- | --- | | [replacereplace\_if](replace "cpp/algorithm/replace") | replaces all values satisfying specific criteria with another value (function template) | | [removeremove\_if](remove "cpp/algorithm/remove") | removes elements satisfying specific criteria (function template) | | [ranges::replace\_copyranges::replace\_copy\_if](ranges/replace_copy "cpp/algorithm/ranges/replace copy") (C++20)(C++20) | copies a range, replacing elements satisfying specific criteria with another value (niebloid) |
programming_docs
cpp std::reduce std::reduce =========== | Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | | | --- | --- | --- | | | (1) | | | ``` template< class InputIt > typename std::iterator_traits<InputIt>::value_type reduce( InputIt first, InputIt last ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt > constexpr typename std::iterator_traits<InputIt>::value_type reduce( InputIt first, InputIt last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt > typename std::iterator_traits<ForwardIt>::value_type reduce( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class InputIt, class T > T reduce( InputIt first, InputIt last, T init ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt, class T > constexpr T reduce( InputIt first, InputIt last, T init ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class T > T reduce( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, T init ); ``` | (4) | (since C++17) | | | (5) | | | ``` template< class InputIt, class T, class BinaryOp > T reduce( InputIt first, InputIt last, T init, BinaryOp binary_op ); ``` | (since C++17) (until C++20) | | ``` template< class InputIt, class T, class BinaryOp > constexpr T reduce( InputIt first, InputIt last, T init, BinaryOp binary_op ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class T, class BinaryOp > T reduce( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, T init, BinaryOp binary_op ); ``` | (6) | (since C++17) | 1) same as `reduce(first, last, typename [std::iterator\_traits](http://en.cppreference.com/w/cpp/iterator/iterator_traits)<InputIt>::value\_type{})` 3) same as `reduce(first, last, init, [std::plus](http://en.cppreference.com/w/cpp/utility/functional/plus)<>())` 5) Reduces the range [first; last), possibly permuted and aggregated in unspecified manner, along with the initial value `init` over `binary_op`. 2,4,6) Same as (1,3,5), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. The behavior is non-deterministic if `binary_op` is not associative or not commutative. The behavior is undefined if `binary_op` modifies any element or invalidates any iterator in [first; last], including the end iterator. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to apply the algorithm to | | init | - | the initial value of the generalized sum | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | binary\_op | - | binary [FunctionObject](../named_req/functionobject "cpp/named req/FunctionObject") that will be applied in unspecified order to the result of dereferencing the input iterators, the results of other `binary_op` and `init`. | | Type requirements | | -`InputIt` must meet the requirements of [LegacyInputIterator](../named_req/inputiterator "cpp/named req/InputIterator"). | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | | -`T` must meet the requirements of [MoveConstructible](../named_req/moveconstructible "cpp/named req/MoveConstructible"). and `binary_op(init, *first)`, `binary_op(*first, init)`, `binary_op(init, init)`, and `binary_op(*first, *first)` must be convertible to `T`. | ### Return value Generalized sum of `init` and `*first`, `*(first+1)`, ... `*(last-1)` over `binary_op`, where generalized sum GSUM(op, a 1, ..., a N) is defined as follows: * if N=1, a 1 * if N > 1, op(GSUM(op, b 1, ..., b K), GSUM(op, b M, ..., b N)) where + b 1, ..., b N may be any permutation of a1, ..., aN and + 1 < K+1 = M ≤ N in other words, `reduce` behaves like `[std::accumulate](accumulate "cpp/algorithm/accumulate")` except the elements of the range may be grouped and rearranged in arbitrary order. ### Complexity O(last - first) applications of `binary_op`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes If the range is empty, `init` is returned, unmodified. ### Example side-by-side comparison between reduce and `[std::accumulate](accumulate "cpp/algorithm/accumulate")`: ``` #include <chrono> #include <execution> #include <iomanip> #include <iostream> #include <numeric> #include <utility> #include <vector> int main() { auto eval = [](auto fun) { const auto t1 = std::chrono::high_resolution_clock::now(); const auto [name, result] = fun(); const auto t2 = std::chrono::high_resolution_clock::now(); const std::chrono::duration<double, std::milli> ms = t2 - t1; std::cout << std::fixed << std::setprecision(1) << name << " result " << result << " took " << ms.count() << " ms\n"; }; { const std::vector<double> v(100'000'007, 0.1); eval([&v]{ return std::pair{"std::accumulate (double)", std::accumulate(v.cbegin(), v.cend(), 0.0)}; } ); eval([&v]{ return std::pair{"std::reduce (seq, double)", std::reduce(std::execution::seq, v.cbegin(), v.cend())}; } ); eval([&v]{ return std::pair{"std::reduce (par, double)", std::reduce(std::execution::par, v.cbegin(), v.cend())}; } ); }{ const std::vector<long> v(100'000'007, 1); eval([&v]{ return std::pair{"std::accumulate (long)", std::accumulate(v.cbegin(), v.cend(), 0)}; } ); eval([&v]{ return std::pair{"std::reduce (seq, long)", std::reduce(std::execution::seq, v.cbegin(), v.cend())}; } ); eval([&v]{ return std::pair{"std::reduce (par, long)", std::reduce(std::execution::par, v.cbegin(), v.cend())}; } ); } } ``` Possible output: ``` std::accumulate (double) result 10000000.7 took 163.6 ms std::reduce (seq, double) result 10000000.7 took 162.9 ms std::reduce (par, double) result 10000000.7 took 97.5 ms std::accumulate (long) result 100000007 took 62.3 ms std::reduce (seq, long) result 100000007 took 64.3 ms std::reduce (par, long) result 100000007 took 49.0 ms ``` ### See also | | | | --- | --- | | [accumulate](accumulate "cpp/algorithm/accumulate") | sums up a range of elements (function template) | | [transform](transform "cpp/algorithm/transform") | applies a function to a range of elements, storing results in a destination range (function template) | | [transform\_reduce](transform_reduce "cpp/algorithm/transform reduce") (C++17) | applies an invocable, then reduces out of order (function template) | cpp std::is_heap_until std::is\_heap\_until ==================== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class RandomIt > RandomIt is_heap_until( RandomIt first, RandomIt last ); ``` | (since C++11) (until C++20) | | ``` template< class RandomIt > constexpr RandomIt is_heap_until( RandomIt first, RandomIt last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class RandomIt > RandomIt is_heap_until( ExecutionPolicy&& policy, RandomIt first, RandomIt last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class RandomIt, class Compare > RandomIt is_heap_until( RandomIt first, RandomIt last, Compare comp ); ``` | (since C++11) (until C++20) | | ``` template< class RandomIt, class Compare > constexpr RandomIt is_heap_until( RandomIt first, RandomIt last, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class RandomIt, class Compare > RandomIt is_heap_until( ExecutionPolicy&& policy, RandomIt first, RandomIt last, Compare comp ); ``` | (4) | (since C++17) | Examines the range `[first, last)` and finds the largest range beginning at `first` which is a [*max heap*](https://en.wikipedia.org/wiki/Binary_heap "enwiki:Binary heap"). 1) Elements are compared using `operator<`. 3) Elements are compared using the given binary comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `RandomIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`RandomIt` must meet the requirements of [LegacyRandomAccessIterator](../named_req/randomaccessiterator "cpp/named req/RandomAccessIterator"). | ### Return value The upper bound of the largest range beginning at `first` which is a *max heap*. That is, the last iterator `it` for which range `[first, it)` is a *max heap*. ### Complexity Linear in the distance between `first` and `last`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Notes A *max heap* is a range of elements `[f,l)` that has the following properties: * With `N = l-f`, for all `0 < i < N`, `f[(i-1)/2]` does not compare less than `f[i]`. * A new element can be added using `[std::push\_heap](push_heap "cpp/algorithm/push heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. * The first element can be removed using `[std::pop\_heap](pop_heap "cpp/algorithm/pop heap")`, in \(\scriptsize \mathcal{O}(\log N)\)𝓞(log N) time. ### Example ``` #include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> v { 3, 1, 4, 1, 5, 9 }; std::make_heap(v.begin(), v.end()); // probably mess up the heap v.push_back(2); v.push_back(6); auto heap_end = std::is_heap_until(v.begin(), v.end()); std::cout << "all of v: "; for (auto i : v) std::cout << i << ' '; std::cout << '\n'; std::cout << "only heap: "; for (auto i = v.begin(); i != heap_end; ++i) std::cout << *i << ' '; std::cout << '\n'; } ``` Output: ``` all of v: 9 5 4 1 1 3 2 6 only heap: 9 5 4 1 1 3 2 ``` ### See also | | | | --- | --- | | [is\_heap](is_heap "cpp/algorithm/is heap") (C++11) | checks if the given range is a max heap (function template) | | [make\_heap](make_heap "cpp/algorithm/make heap") | creates a max heap out of a range of elements (function template) | | [push\_heap](push_heap "cpp/algorithm/push heap") | adds an element to a max heap (function template) | | [pop\_heap](pop_heap "cpp/algorithm/pop heap") | removes the largest element from a max heap (function template) | | [sort\_heap](sort_heap "cpp/algorithm/sort heap") | turns a max heap into a range of elements sorted in ascending order (function template) | | [ranges::is\_heap\_until](ranges/is_heap_until "cpp/algorithm/ranges/is heap until") (C++20) | finds the largest subrange that is a max heap (niebloid) | cpp std::iota std::iota ========= | Defined in header `[<numeric>](../header/numeric "cpp/header/numeric")` | | | | --- | --- | --- | | ``` template< class ForwardIt, class T > void iota( ForwardIt first, ForwardIt last, T value ); ``` | | (since C++11) (until C++20) | | ``` template< class ForwardIt, class T > constexpr void iota( ForwardIt first, ForwardIt last, T value ); ``` | | (since C++20) | Fills the range `[first, last)` with sequentially increasing values, starting with `value` and repetitively evaluating `++value`. Equivalent operation: ``` *(first) = value; *(first+1) = ++value; *(first+2) = ++value; *(first+3) = ++value; ... ``` ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to fill with sequentially increasing values starting with `value` | | value | - | initial value to store; the expression `++value` must be well-formed | ### Return value (none). ### Complexity Exactly `last - first` increments and assignments. ### Possible implementation | | | --- | | ``` template<class ForwardIt, class T> constexpr // since C++20 void iota(ForwardIt first, ForwardIt last, T value) { while(first != last) { *first++ = value; ++value; } } ``` | ### Notes The function is named after the integer function ⍳ from the programming language [APL](https://en.wikipedia.org/wiki/APL_(programming_language) "enwiki:APL (programming language)"). It was one of the [STL components](http://www.martinbroadhurst.com/stl/iota.html) that were not included in C++98, but made it into the standard library in C++11. ### Example The following example applies `[std::shuffle](random_shuffle "cpp/algorithm/random shuffle")` to a `[vector](../container/vector "cpp/container/vector")` of `[std::list](../container/list "cpp/container/list")`s' iterators. `std::iota` is used to populate containers. ``` #include <algorithm> #include <iomanip> #include <iostream> #include <list> #include <numeric> #include <random> #include <vector> class BigData // inefficient to copy { int data[1024]; /* some raw data */ public: explicit BigData(int i = 0) { data[0] = i; /* ... */ } operator int () const { return data[0]; } BigData& operator=(int i) { data[0] = i; return *this; } /* ... */ }; int main() { std::list<BigData> l(10); std::iota(l.begin(), l.end(), -4); std::vector<std::list<BigData>::iterator> v(l.size()); std::iota(v.begin(), v.end(), l.begin()); // Vector of iterators (to original data) is used to avoid expensive copying, // and because std::shuffle (below) cannot be applied to a std::list directly. std::shuffle(v.begin(), v.end(), std::mt19937{std::random_device{}()}); std::cout << "Original contents of the list l:\t"; for(auto const& n: l) std::cout << std::setw(2) << n << ' '; std::cout << '\n'; std::cout << "Contents of l, viewed via shuffled v:\t"; for(auto const i: v) std::cout << std::setw(2) << *i << ' '; std::cout << '\n'; } ``` Possible output: ``` Original contents of the list l: -4 -3 -2 -1 0 1 2 3 4 5 Contents of l, viewed via shuffled v: -1 5 -4 0 2 1 4 -2 3 -3 ``` ### See also | | | | --- | --- | | [ranges::iota\_viewviews::iota](../ranges/iota_view "cpp/ranges/iota view") (C++20) | a [`view`](../ranges/view "cpp/ranges/view") consisting of a sequence generated by repeatedly incrementing an initial value (class template) (customization point object) | | [fill](fill "cpp/algorithm/fill") | copy-assigns the given value to every element in a range (function template) | | [ranges::fill](ranges/fill "cpp/algorithm/ranges/fill") (C++20) | assigns a range of elements a certain value (niebloid) | | [generate](generate "cpp/algorithm/generate") | assigns the results of successive function calls to every element in a range (function template) | | [ranges::generate](ranges/generate "cpp/algorithm/ranges/generate") (C++20) | saves the result of a function in a range (niebloid) | | [ranges::iota](ranges/iota "cpp/algorithm/ranges/iota") (C++23) | fills a range with successive increments of the starting value (niebloid) | cpp std::is_sorted std::is\_sorted =============== | Defined in header `[<algorithm>](../header/algorithm "cpp/header/algorithm")` | | | | --- | --- | --- | | | (1) | | | ``` template< class ForwardIt > bool is_sorted( ForwardIt first, ForwardIt last ); ``` | (since C++11) (until C++20) | | ``` template< class ForwardIt > constexpr bool is_sorted( ForwardIt first, ForwardIt last ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt > bool is_sorted( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last ); ``` | (2) | (since C++17) | | | (3) | | | ``` template< class ForwardIt, class Compare > bool is_sorted( ForwardIt first, ForwardIt last, Compare comp ); ``` | (since C++11) (until C++20) | | ``` template< class ForwardIt, class Compare > constexpr bool is_sorted( ForwardIt first, ForwardIt last, Compare comp ); ``` | (since C++20) | | ``` template< class ExecutionPolicy, class ForwardIt, class Compare > bool is_sorted( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, Compare comp ); ``` | (4) | (since C++17) | Checks if the elements in range `[first, last)` are sorted in non-descending order. A sequence is sorted with respect to a comparator `comp` if for any iterator `it` pointing to the sequence and any non-negative integer `n` such that `it + n` is a valid iterator pointing to an element of the sequence, `comp(*(it + n), *it)` evaluates to `false`. 1) Elements are compared using `operator<`. 3) Elements are compared using the given binary comparison function `comp`. 2,4) Same as (1,3), but executed according to `policy`. These overloads do not participate in overload resolution unless `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::decay\_t](http://en.cppreference.com/w/cpp/types/decay)<ExecutionPolicy>>` (until C++20) `[std::is\_execution\_policy\_v](http://en.cppreference.com/w/cpp/algorithm/is_execution_policy)<[std::remove\_cvref\_t](http://en.cppreference.com/w/cpp/types/remove_cvref)<ExecutionPolicy>>` (since C++20) is true. ### Parameters | | | | | --- | --- | --- | | first, last | - | the range of elements to examine. | | policy | - | the execution policy to use. See [execution policy](execution_policy_tag_t "cpp/algorithm/execution policy tag t") for details. | | comp | - | comparison function object (i.e. an object that satisfies the requirements of [Compare](../named_req/compare "cpp/named req/Compare")) which returns ​`true` if the first argument is *less* than (i.e. is ordered *before*) the second. The signature of the comparison function should be equivalent to the following: `bool cmp(const Type1 &a, const Type2 &b);` While the signature does not need to have `const &`, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) `Type1` and `Type2` regardless of [value category](../language/value_category "cpp/language/value category") (thus, `Type1 &` is not allowed, nor is `Type1` unless for `Type1` a move is equivalent to a copy (since C++11)). The types `Type1` and `Type2` must be such that an object of type `ForwardIt` can be dereferenced and then implicitly converted to both of them. ​ | | Type requirements | | -`ForwardIt` must meet the requirements of [LegacyForwardIterator](../named_req/forwarditerator "cpp/named req/ForwardIterator"). | ### Return value `true` if the elements in the range are sorted in non-descending order. ### Complexity Linear in the distance between `first` and `last`. ### Exceptions The overloads with a template parameter named `ExecutionPolicy` report errors as follows: * If execution of a function invoked as part of the algorithm throws an exception and `ExecutionPolicy` is one of the [standard policies](execution_policy_tag_t "cpp/algorithm/execution policy tag t"), `[std::terminate](../error/terminate "cpp/error/terminate")` is called. For any other `ExecutionPolicy`, the behavior is implementation-defined. * If the algorithm fails to allocate memory, `[std::bad\_alloc](../memory/new/bad_alloc "cpp/memory/new/bad alloc")` is thrown. ### Possible implementation See also the implementations in [libstdc++](https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L3184) and [libc++](https://github.com/llvm-mirror/libcxx/blob/a12cb9d211019d99b5875b6d8034617cbc24c2cc/include/algorithm#L3642). | First version | | --- | | ``` template<class ForwardIt> bool is_sorted(ForwardIt first, ForwardIt last) { return std::is_sorted_until(first, last) == last; } ``` | | Second version | | ``` template<class ForwardIt, class Compare> bool is_sorted(ForwardIt first, ForwardIt last, Compare comp) { return std::is_sorted_until(first, last, comp) == last; } ``` | ### Notes `std::is_sorted` returns `true` for empty ranges and ranges of length one. ### Example ``` #include <iostream> #include <algorithm> #include <iterator> int main() { int digits[] = {3, 1, 4, 1, 5}; for (auto i : digits) std::cout << i << ' '; std::cout << ": is_sorted: " << std::boolalpha << std::is_sorted(std::begin(digits), std::end(digits)) << '\n'; std::sort(std::begin(digits), std::end(digits)); for (auto i : digits) std::cout << i << ' '; std::cout << ": is_sorted: " << std::is_sorted(std::begin(digits), std::end(digits)) << '\n'; } ``` Output: ``` 3 1 4 1 5 : is_sorted: false 1 1 3 4 5 : is_sorted: true ``` ### See also | | | | --- | --- | | [is\_sorted\_until](is_sorted_until "cpp/algorithm/is sorted until") (C++11) | finds the largest sorted subrange (function template) | | [ranges::is\_sorted](ranges/is_sorted "cpp/algorithm/ranges/is sorted") (C++20) | checks whether a range is sorted into ascending order (niebloid) |
programming_docs