This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
for some P 0 and the argument is an initializer list (8.5.4), then deduction is performed instead for each element of the initializer list, taking P 0 as a function template parameter type and the initializer element as its argument. Otherwise, an initializer list argument causes the parameter to be considered a non-deduced context (14.8.2.5). [ Example: template void f(std::initializer_list); f({1,2,3}); // T deduced to int f({1,"asdf"}); // error: T deduced to both int and const char* template void g(T); g({1,2,3}); // error: no argument deduced for T
— end example ] For a function parameter pack that occurs at the end of the parameter-declaration-list, the type A of each remaining argument of the call 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. For a function parameter pack that does not occur at the end of the parameter-declaration-list, the type of the parameter pack is a non-deduced context. [ Example: template void f(Types& ...); template void g(T1, Types ...); void h(int x, float& y) { const int z = x; f(x, y, z); // Types is deduced to int, float, const int g(x, y, z); // T1 is deduced to int; Types is deduced to float, int }
§ 14.8.2.1
363
c ISO/IEC
2
N3376
— end example ] If P is not a reference type: — If A is an array type, the pointer type produced by the array-to-pointer standard conversion (4.2) is used in place of A for type deduction; otherwise, — If A is a function type, the pointer type produced by the function-to-pointer standard conversion (4.3) is used in place of A for type deduction; otherwise, — If A is a cv-qualified type, the top level cv-qualifiers of A’s type are ignored for type deduction.
3
If P is a cv-qualified type, the top level cv-qualifiers of P’s type are ignored for type deduction. If P is a reference type, the type referred to by P is used for type deduction. If P is an rvalue reference to a cvunqualified template parameter and the argument is an lvalue, the type “lvalue reference to A” is used in place of A for type deduction. [ Example: template template int i; int n1 = int n2 = int n3 =
4
int f(T&&); int g(const T&&); f(i); f(0); g(i);
// // // //
calls f(int&) calls f(int&&) error: would call g(const int&&), which would bind an rvalue reference to an lvalue
— end example ] In general, the deduction process attempts to find template argument values that will make the deduced A identical to A (after the type A is transformed as described above). However, there are three cases that allow a difference: — If the original P is a reference type, the deduced A (i.e., the type referred to by the reference) can be more cv-qualified than the transformed A. — The transformed A can be another pointer or pointer to member type that can be converted to the deduced A via a qualification conversion (4.4). — If P is a class and P has the form simple-template-id, then the transformed A can be a derived class of the deduced A. Likewise, if P is a pointer to a class of the form simple-template-id, the transformed A can be a pointer to a derived class pointed to by the deduced A.
5
6
[ Note: as specified in 14.8.1, implicit conversions will be performed on a function argument to convert it to the type of the corresponding function parameter if the parameter contains no template-parameters that participate in template argument deduction. Such conversions are also allowed, in addition to the ones described in the preceding list. — end note ] These alternatives are considered only if type deduction would otherwise fail. If they yield more than one possible deduced A, the type deduction fails. [ Note: If a template-parameter is not used in any of the function parameters of a function template, or is used only in a non-deduced context, its corresponding template-argument cannot be deduced from a function call and the template-argument must be explicitly specified. — end note ] When P is a function type, pointer to function type, or pointer to member function type: — If the argument is an overload set containing one or more function templates, the parameter is treated as a non-deduced context. — If the argument is an overload set (not containing function templates), trial argument deduction is attempted using each of the members of the set. If deduction succeeds for only one of the overload
§ 14.8.2.1
364
c ISO/IEC
N3376
set members, that member is used as the argument value for the deduction. If deduction succeeds for more than one member of the overload set the parameter is treated as a non-deduced context. 7
[ Example: // Only one function of an overload set matches the call so the function // parameter is a deduced context. template int f(T (*p)(T)); int g(int); int g(char); int i = f(g); // calls f(int (*)(int))
— end example ] 8
[ Example: // Ambiguous deduction causes the second function parameter to be a // non-deduced context. template int f(T, T (*p)(T)); int g(int); char g(char); int i = f(1, g); // calls f(int, int (*)(int))
— end example ] 9
[ Example: // The overload set contains a template, causing the second function // parameter to be a non-deduced context. template int f(T, T (*p)(T)); char g(char); template T g(T); int i = f(1, g); // calls f(int, int (*)(int))
— end example ] 14.8.2.2
Deducing template arguments taking the address of a function template [temp.deduct.funcaddr]
1
Template arguments can be deduced from the type specified when taking the address of an overloaded function (13.4). The function template’s function type and the specified type are used as the types of P and A, and the deduction is done as described in 14.8.2.5. 14.8.2.3 Deducing conversion function template arguments [temp.deduct.conv]
1
Template argument deduction is done by comparing the return type of the conversion function template (call it P; see 8.5, 13.3.1.5, and 13.3.1.6 for the determination of that type) with the type that is required as the result of the conversion (call it A) as described in 14.8.2.5. If P is a reference type, the type referred to by P is used in place of P for type deduction and for any further references to or transformations of P in the remainder of this section. If A is not a reference type: — If P is an array type, the pointer type produced by the array-to-pointer standard conversion (4.2) is used in place of P for type deduction; otherwise,
2
3
— If P is a function type, the pointer type produced by the function-to-pointer standard conversion (4.3) is used in place of P for type deduction; otherwise, — If P is a cv-qualified type, the top level cv-qualifiers of P’s type are ignored for type deduction.
§ 14.8.2.3
365
c ISO/IEC
4
5
N3376
If A is a cv-qualified type, the top level cv-qualifiers of A’s type are ignored for type deduction. If A is a reference type, the type referred to by A is used for type deduction. In general, the deduction process attempts to find template argument values that will make the deduced A identical to A. However, there are two cases that allow a difference: — If the original A is a reference type, A can be more cv-qualified than the deduced A (i.e., the type referred to by the reference) — The deduced A can be another pointer or pointer to member type that can be converted to A via a qualification conversion.
6
7
These alternatives are considered only if type deduction would otherwise fail. If they yield more than one possible deduced A, the type deduction fails. When the deduction process requires a qualification conversion for a pointer or pointer to member type as described above, the following process is used to determine the deduced template argument values: If A is a type cv 1,0 “pointer to . . .” cv 1,n−1 “pointer to” cv 1,n T1 and P is a type cv 2,0 “pointer to . . .” cv 2,n−1 “pointer to” cv 2,n T2 The cv-unqualified T1 and T2 are used as the types of A and P respectively for type deduction. [ Example: struct A { template operator T***(); }; A a; const int * const * const * p1 = a;
// T is deduced as int, not const int
— end example ] 14.8.2.4 1
2
3
Deducing template arguments during partial ordering
[temp.deduct.partial]
Template argument deduction is done by comparing certain types associated with the two function templates being compared. Two sets of types are used to determine the partial ordering. For each of the templates involved there is the original function type and the transformed function type. [ Note: The creation of the transformed type is described in 14.5.6.2. — end note ] The deduction process uses the transformed type as the argument template and the original type of the other template as the parameter template. This process is done twice for each type involved in the partial ordering comparison: once using the transformed template-1 as the argument template and template-2 as the parameter template and again using the transformed template-2 as the argument template and template-1 as the parameter template. The types used to determine the ordering depend on the context in which the partial ordering is done: — In the context of a function call, the types used are those function parameter types for which the function call has arguments.142 — In the context of a call to a conversion operator, the return types of the conversion function templates are used. — In other contexts (14.5.6.2) the function template’s function type is used. 142) Default arguments are not considered to be arguments in this context; they only become arguments after a function has been selected.
§ 14.8.2.4
366
c ISO/IEC
4
5
N3376
Each type nominated above from the parameter template and the corresponding type from the argument template are used as the types of P and A. Before the partial ordering is done, certain transformations are performed on the types used for partial ordering: — If P is a reference type, P is replaced by the type referred to. — If A is a reference type, A is replaced by the type referred to.
6
7
If both P and A were reference types (before being replaced with the type referred to above), determine which of the two types (if any) is more cv-qualified than the other; otherwise the types are considered to be equally cv-qualified for partial ordering purposes. The result of this determination will be used below. Remove any top-level cv-qualifiers: — If P is a cv-qualified type, P is replaced by the cv-unqualified version of P. — If A is a cv-qualified type, A is replaced by the cv-unqualified version of A.
8
If A was transformed from a function parameter pack and P is not a parameter pack, type deduction fails. Otherwise, using the resulting types P and A, the deduction is then done as described in 14.8.2.5. 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 deduction succeeds for a given type, the type from the argument template is considered to be at least as specialized as the type from the parameter template. [ Example: template void f(Args... args); template void f(T1 a1, Args... args); template void f(T1 a1, T2 a2); f(); f(1, 2, 3); f(1, 2);
9
// // // //
// #1 // #2 // #3
calls #1 calls #2 calls #3; non-variadic template #3 is more specialized than the variadic templates #1 and #2
— end example ] If, for a given type, deduction succeeds in both directions (i.e., the types are identical after the transformations above) and both P and A were reference types (before being replaced with the type referred to above): — if the type from the argument template was an lvalue reference and the type from the parameter template was not, the argument type is considered to be more specialized than the other; otherwise, — if the type from the argument template is more cv-qualified than the type from the parameter template (as described above), the argument type is considered to be more specialized than the other; otherwise, — neither type is more specialized than the other.
10
11
If for each type being considered a given template is at least as specialized for all types and more specialized for some set of types and the other template is not more specialized for any types or is not at least as specialized for any types, then the given template is more specialized than the other template. Otherwise, neither template is more specialized than the other. In most cases, all template parameters must have values in order for deduction to succeed, but for partial ordering purposes a template parameter may remain without a value provided it is not used in the types being used for partial ordering. [ Note: A template parameter used in a non-deduced context is considered used. — end note ] [ Example: § 14.8.2.4
367
c ISO/IEC
N3376
template T f(int); // #1 template T f(U); // #2 void g() { f(1); // calls #1 } 12
— end example ] [ Note: Partial ordering of function templates containing template parameter packs is independent of the number of deduced arguments for those template parameter packs. — end note ] [ Example: template void g(Tuple);
g(Tuple()); g(Tuple()); g(Tuple()); g(Tuple());
// // // //
calls calls calls calls
// #1 // #2 // #3
#1 #2 #3 #3
— end example ] 14.8.2.5 1
2
3
Deducing template arguments from a type
[temp.deduct.type]
Template arguments can be deduced in several different contexts, but in each case a type that is specified in terms of template parameters (call it P) is compared with an actual type (call it A), and an attempt is made to find template argument values (a type for a type parameter, a value for a non-type parameter, or a template for a template parameter) that will make P, after substitution of the deduced values (call it the deduced A), compatible with A. In some cases, the deduction is done using a single set of types P and A, in other cases, there will be a set of corresponding types P and A. Type deduction is done independently for each P/A pair, and the deduced template argument values are then combined. If type deduction cannot be done for any P/A pair, or if for any pair the deduction leads to more than one possible set of deduced values, or if different pairs yield different deduced values, or if any template argument remains neither deduced nor explicitly specified, template argument deduction fails. A given type P can be composed from a number of other types, templates, and non-type values: — A function type includes the types of each of the function parameters and the return type. — A pointer to member type includes the type of the class object pointed to and the type of the member pointed to. — A type that is a specialization of a class template (e.g., A) includes the types, templates, and non-type values referenced by the template argument list of the specialization. — An array type includes the array element type and the value of the array bound.
4
5
In most cases, the types, templates, and non-type values that are used to compose P participate in template argument deduction. That is, they may be used to determine the value of a template argument, and the value so determined must be consistent with the values determined elsewhere. In certain contexts, however, the value does not participate in type deduction, but instead uses the values of template arguments that were either deduced elsewhere or explicitly specified. If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails. The non-deduced contexts are: — The nested-name-specifier of a type that was specified using a qualified-id.
§ 14.8.2.5
368
c ISO/IEC
N3376
— A non-type template argument or an array bound in which a subexpression references a template parameter. — A template parameter used in the parameter type of a function parameter that has a default argument that is being used in the call for which argument deduction is being done. — A function parameter for which argument deduction cannot be done because the associated function argument is a function, or a set of overloaded functions (13.4), and one or more of the following apply: — more than one function matches the function parameter type (resulting in an ambiguous deduction), or — no function matches the function parameter type, or — the set of functions supplied as an argument contains one or more function templates. — A function parameter for which the associated argument is an initializer list (8.5.4) but the parameter does not have std::initializer_list or reference to possibly cv-qualified std::initializer_list type. [ Example: template void g(T); g({1,2,3}); // error: no argument deduced for T
— end example ] — A function parameter pack that does not occur at the end of the parameter-declaration-clause. 6
7
When a type name is specified in a way that includes a non-deduced context, all of the types that comprise that type name are also non-deduced. However, a compound type can include both deduced and non-deduced types. [ Example: If a type is specified as A::B, both T and T2 are non-deduced. Likewise, if a type is specified as A::X, I, J, and T are non-deduced. If a type is specified as void f(typename A::B, A), the T in A::B is non-deduced but the T in A is deduced. — end example ] [ Example: Here is an example in which different parameter/argument pairs produce inconsistent template argument deductions: template void f(T x, T y) { /∗ ... ∗/ } struct A { /∗ ... ∗/ }; struct B : A { /∗ ... ∗/ }; void g(A a, B b) { f(a,b); // error: T could be A or B f(b,a); // error: T could be A or B f(a,a); // OK: T is A f(b,b); // OK: T is B }
Here is an example where two template arguments are deduced from a single function parameter/argument pair. This can lead to conflicts that cause type deduction to fail: template void f(
T (*)( T, U, U )
);
int g1( int, float, float); char g2( int, float, float); int g3( int, char, float); void r() { f(g1); f(g2); f(g3); }
§ 14.8.2.5
// OK: T is int and U is float // error: T could be char or int // error: U could be char or float
369
c ISO/IEC
N3376
Here is an example where a qualification conversion applies between the argument type on the function call and the deduced template argument type: template void f(const T*) { } int *p; void s() { f(p); // f(const int*) }
Here is an example where the template argument is used to instantiate a derived class type of the corresponding function parameter type: template template struct D2 : public template void t() { D d; D2 d2; f(d); f(d2); } 8
struct B { }; struct D : public B {}; B {}; void f(B&){}
// calls f(B&) // calls f(B&)
— end example ] A template type argument T, a template template argument TT or a template non-type argument i can be deduced if P and A have one of the following forms: T cv-list T T* T& T&& T[integer-constant ] template-name (where template-name type (T) T() T(T) T type ::* type T::* T T::* T (type ::*)() type (T::*)() type (type ::*)(T) type (T::*)(T) T (type ::*)(T) T (T::*)() T (T::*)(T) type [i] template-name (where template-name TT TT TT
refers to a class template)
refers to a class template)
where (T) represents a parameter-type-list where at least one parameter type contains a T, and () represents a parameter-type-list where no parameter type contains a T. Similarly, represents template argument lists where at least one argument contains a T, represents template argument lists where at least one argument contains an i and represents template argument lists where no argument contains a T or an i. § 14.8.2.5
370
c ISO/IEC
9
N3376
If P has a form that contains or , then each argument Pi of the respective template argument list P is compared with the corresponding argument Ai of the corresponding template argument list of A. If the template argument list of P contains a pack expansion that is not the last template argument, the entire template argument list is a non-deduced context. If Pi is a pack expansion, then the pattern of Pi is compared with each remaining argument in the template argument list of A. Each comparison deduces template arguments for subsequent positions in the template parameter packs expanded by Pi . During partial ordering (14.8.2.4), if Ai was originally a pack expansion: — if P does not contain a template argument corresponding to Ai then Ai is ignored; — otherwise, if Pi is not a pack expansion, template argument deduction fails. [ Example: template class s; // both
S; // #1 S { }; // #2 S { }; // #3 #2 and #3 match; #3 is more specialized
template struct A { }; // #1 template struct A { }; // #2 template struct A { }; // #3 template struct A; // selects #2 10
— end example ] Similarly, if P has a form that contains (T), then each parameter type Pi of the respective parameter-typelist of P is compared with the corresponding parameter type Ai of the corresponding parameter-type-list of A. If P and A are function types that originated from deduction when taking the address of a function template (14.8.2.2) or when deducing template arguments from a function declaration (14.8.2.6) and Pi and Ai are parameters of the top-level parameter-type-list of P and A, respectively, Pi is adjusted if it is an rvalue reference to a cv-unqualified template parameter and Ai is an lvalue reference, in which case the type of Pi is changed to be the template parameter type (i.e., T&& is changed to simply T). [ Note: As a result, when Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be deduced as X&. — end note ] [ Example: template void f(T&&); template void f(int&) { } // template void f(int&&) { } // void g(int i) { f(i); // f(0); // }
#1 #2 calls f(int&), i.e., #1 calls f(int&&), i.e., #2
— end example ] If the parameter-declaration corresponding to Pi is a function parameter pack, then the type of its declarator-id is compared with each remaining parameter type in the parameter-type-list of A. Each comparison deduces template arguments for subsequent positions in the template parameter packs expanded by the function parameter pack. During partial ordering (14.8.2.4), if Ai was originally a function parameter pack: — if P does not contain a function parameter type corresponding to Ai then Ai is ignored; — otherwise, if Pi is not a function parameter pack, template argument deduction fails. [ Example: template void f(T*, U...) { } template void f(T) { } template void f(int*); // selects #1
§ 14.8.2.5
// #1 // #2
371
c ISO/IEC
11
N3376
— end example ] These forms can be used in the same way as T is for further composition of types. [ Example: X (*)(char[6])
is of the form template-name (*)(type [i])
which is a variant of type 12
13 14
(*)(T)
where type is X and T is char[6]. — end example ] Template arguments cannot be deduced from function arguments involving constructs other than the ones specified above. A template type argument cannot be deduced from the type of a non-type template-argument. [ Example: template void f(double a[10][i]); int v[10][20]; f(v); // error: argument for template-parameter T cannot be deduced
15
— end example ] [ Note: Except for reference and pointer types, a major array bound is not part of a function parameter type and cannot be deduced from an argument: template void f1(int a[10][i]); template void f2(int a[i][20]); template void f3(int (&a)[i][20]); void g() { int v[10][20]; f1(v); f1(v); f2(v); f2(v); f3(v); }
16
// // // // //
OK: i deduced to be 20 OK error: cannot deduce template-argument i OK OK: i deduced to be 10
If, in the declaration of a function template with a non-type template parameter, the non-type template parameter is used in a subexpression in the function parameter list, the expression is a non-deduced context as specified above. [ Example: template class A { /∗ ... ∗/ }; template void g(A); template void f(A, A); void k() { A a1; A a2; g(a1); // error: deduction fails for expression i+1 g(a1); // OK f(a1, a2); // OK }
— end example ] — end note ] [ Note: Template parameters do not participate in template argument deduction if they are used only in non-deduced contexts. For example, template T deduce(typename A::X x,
§ 14.8.2.5
// T is not deduced here
372
c ISO/IEC
T t, typename B::Y y); A a; B b;
N3376
// but T is deduced here // i is not deduced here
int x = deduce(a.xm, 62, b.ym); // T is deduced to be int, a.xm must be convertible to // A::X // i is explicitly specified to be 77, b.ym must be convertible // to B::Y 17
— end note ] If, in the declaration of a function template with a non-type template-parameter, the non-type templateparameter is used in an expression in the function parameter-list and, if the corresponding template-argument is deduced, the template-argument type shall match the type of the template-parameter exactly, except that a template-argument deduced from an array bound may be of any integral type.143 [ Example: template class A { /∗ ... ∗/ }; template<short s> void f(A<s>); void k1() { A a; f(a); // error: deduction fails for conversion from int to short f(a); // OK } template class B { }; template<short s> void g(B<s>); void k2() { B b; g(b); // OK: cv-qualifiers are ignored on template parameter types }
18
— end example ] A template-argument can be deduced from a function, pointer to function, or pointer to member function type. [ Example: template void f(void(*)(T,int)); template void foo(T,int); void g(int,int); void g(char,int); void h(int,int,int); void h(char,int); int m() { f(&g); // error: ambiguous f(&h); // OK: void h(char,int) is a unique match f(&foo); // error: type deduction fails because foo is a template }
19
— end example ] A template type-parameter cannot be deduced from the type of a function default argument. [ Example: template void f(T = 5, T = 7); 143) Although the template-argument corresponding to a template-parameter of type bool may be deduced from an array bound, the resulting value will always be true because the array bound will be non-zero.
§ 14.8.2.5
373
c ISO/IEC
void g() { f(1); f(); f(); } 20
N3376
// OK: call f(1,7) // error: cannot deduce T // OK: call f(5,7)
— end example ] The template-argument corresponding to a template template-parameter is deduced from the type of the template-argument of a class template specialization used in the argument list of a function call. [ Example: template struct A { }; template void f(A<X>) { } template struct B { }; A ab; f(ab); // calls f(A)
21
— end example ] [ Note: Template argument deduction involving parameter packs (14.5.3) can deduce zero or more arguments for each parameter pack. — end note ] [ Example: template struct X { }; template struct X { }; template struct Y { }; template struct Y { }; template int f(void (*)(Types ...)); void g(int, float); X x1; X x2; X x3; Y y1; Y y2; Y y3; int fv = f(g);
// // // // // // //
uses primary template uses partial specialization; ArgTypes contains float, double uses primary template use primary template; Types is empty uses partial specialization; T is int&, Types contains float, double uses primary template; Types contains int, float, double OK; Types contains int, float
— end example ] 14.8.2.6 1
2
[temp.deduct.decl]
In a declaration whose declarator-id refers to a specialization of a function template, template argument deduction is performed to identify the specialization to which the declaration refers. Specifically, this is done for explicit instantiations (14.7.2), explicit specializations (14.7.3), and certain friend declarations (14.5.4). This is also done to determine whether a deallocation function template specialization matches a placement operator new (3.7.4.2, 5.3.4). In all these cases, P is the type of the function template being considered as a potential match and A is either the function type from the declaration or the type of the deallocation function that would match the placement operator new as described in 5.3.4. The deduction is done as described in 14.8.2.5. If, for the set of function templates so considered, there is either no match or more than one match after partial ordering has been considered (14.5.6.2), deduction fails and, in the declaration cases, the program is ill-formed.
14.8.3 1
Deducing template arguments from a function declaration
Overload resolution
[temp.over]
A function template can be overloaded either by (non-template) functions of its name or by (other) function templates of the same name. When a call to that name is written (explicitly, or implicitly using the operator notation), template argument deduction (14.8.2) and checking of any explicit template arguments (14.3) are performed for each function template to find the template argument values (if any) that can be used with § 14.8.3
374
c ISO/IEC
N3376
that function template to instantiate a function template specialization that can be invoked with the call arguments. For each function template, if the argument deduction and checking succeeds, the templatearguments (deduced and/or explicit) are used to synthesize the declaration of a single function template specialization which is added to the candidate functions set to be used in overload resolution. If, for a given function template, argument deduction fails, no such function is added to the set of candidate functions for that template. The complete set of candidate functions includes all the synthesized declarations and all of the non-template overloaded functions of the same name. The synthesized declarations are treated like any other functions in the remainder of overload resolution, except as explicitly noted in 13.3.3.144 [ Example: template T max(T a, T b) { return a>b?a:b; } void f(int a, int b, char c, char d) { int m1 = max(a,b); // max(int a, int b) char m2 = max(c,d); // max(char a, char b) int m3 = max(a,c); // error: cannot generate max(int,char) } 2
Adding the non-template function int max(int,int);
3
to the example above would resolve the third call, by providing a function that could be called for max(a,c) after using the standard conversion of char to int for c. Here is an example involving conversions on a function argument involved in template-argument deduction: template struct B { /∗ ... ∗/ }; template struct D : public B { /∗ ... ∗/ }; template void f(B&); void g(B& bi, D& di) { f(bi); // f(bi) f(di); // f((B&)di) }
4
Here is an example involving conversions on a function argument not involved in template-parameter deduction: template void f(T*,int); template void f(T,char);
// #1 // #2
void h(int* pi, int i, char c) { f(pi,i); // #1: f(pi,i) f(pi,c); // #2: f(pi,c) f(i,c); f(i,i);
// #2: f(i,c); // #2: f(i,char(i))
} 5
— end example ] Only the signature of a function template specialization is needed to enter the specialization in a set of candidate functions. Therefore only the function template declaration is needed to resolve a call for which a template specialization is a candidate. [ Example: 144) The parameters of function template specializations contain no template parameter types. The set of conversions allowed on deduced arguments is limited, because the argument deduction process produces function templates with parameters that either match the call arguments exactly or differ only in ways that can be bridged by the allowed limited conversions. Nondeduced arguments allow the full range of conversions. Note also that 13.3.3 specifies that a non-template function will be given preference over a template specialization if the two functions are otherwise equally good candidates for an overload match.
§ 14.8.3
375
c ISO/IEC
6
N3376
template void f(T);
// declaration
void g() { f("Annemarie"); }
// call of f
The call of f is well-formed even if the template f is only declared and not defined at the point of the call. The program will be ill-formed unless a specialization for f, either implicitly or explicitly generated, is present in some translation unit. — end example ]
§ 14.8.3
376
c ISO/IEC
15 1
N3376
Exception handling
[except]
Exception handling provides a way of transferring control and information from a point in the execution of a thread to an exception handler associated with a point previously passed by the execution. A handler will be invoked only by a throw-expression invoked in code executed in the handler’s try block or in functions called from the handler’s try block . try-block: try compound-statement handler-seq function-try-block: try ctor-initializeropt compound-statement handler-seq handler-seq: handler handler-seqopt handler: catch ( exception-declaration ) compound-statement exception-declaration: attribute-specifier-seqopt type-specifier-seq declarator attribute-specifier-seqopt type-specifier-seq abstract-declaratoropt ... throw-expression: throw assignment-expressionopt
2
3
The optional attribute-specifier-seq in an exception-declaration appertains to the formal parameter of the catch clause (15.3). A try-block is a statement (Clause 6). A throw-expression is of type void. Code that executes a throwexpression is said to “throw an exception;” code that subsequently gets control is called a “handler.” [ Note: Within this Clause “try block” is taken to mean both try-block and function-try-block. — end note ] A goto or switch statement shall not be used to transfer control into a try block or into a handler. [ Example: void f() { goto l1; goto l2; try { goto l1; goto l2; l1: ; } catch (...) { l2: ; goto l1; goto l2; } }
// Ill-formed // Ill-formed // OK // Ill-formed
// Ill-formed // OK
— end example ] A goto, break, return, or continue statement can be used to transfer control out of a try block or handler. When this happens, each variable declared in the try block will be destroyed in the context that directly contains its declaration. [ Example: lab: try { T1 t1; try { T2 t2; if (condition )
Exception handling
377
c ISO/IEC
N3376
goto lab; } catch(...) { /∗ handler 2 ∗/ } } catch(...) { /∗ handler 1 ∗/ }
4
Here, executing goto lab; will destroy first t2, then t1, assuming the condition does not declare a variable. Any exception raised while destroying t2 will result in executing handler 2 ; any exception raised while destroying t1 will result in executing handler 1. — end example ] A function-try-block associates a handler-seq with the ctor-initializer, if present, and the compound-statement. An exception thrown during the execution of the compound-statement or, for constructors and destructors, during the initialization or destruction, respectively, of the class’s subobjects, transfers control to a handler in a function-try-block in the same way as an exception thrown during the execution of a try-block transfers control to other handlers. [ Example: int f(int); class C { int i; double d; public: C(int, double); }; C::C(int ii, double id) try : i(f(ii)), d(id) { // constructor statements } catch (...) { // handles exceptions thrown from the ctor-initializer // and from the constructor statements }
— end example ]
15.1 1
Throwing an exception
[except.throw]
Throwing an exception transfers control to a handler. An object is passed and the type of that object determines which handlers can catch it. [ Example: throw "Help!";
can be caught by a handler of const char* type: try { // ... } catch(const char* p) { // handle character string exceptions here }
and class Overflow { public: Overflow(char,double,double); }; void f(double x) { throw Overflow(’+’,x,3.45e107); }
can be caught by a handler for exceptions of type Overflow § 15.1
378
c ISO/IEC
N3376
try { f(1.2); } catch(Overflow& oo) { // handle exceptions of type Overflow here } 2
3
4
5
6
7
— end example ] When an exception is thrown, control is transferred to the nearest handler with a matching type (15.3); “nearest” means the handler for which the compound-statement or ctor-initializer following the try keyword was most recently entered by the thread of control and not yet exited. A throw-expression copy-initializes (8.5) a temporary object, called the exception object, the type of which is determined by removing any top-level cv-qualifiers from the static type of the operand of throw and adjusting the type from “array of T” or “function returning T” to “pointer to T” or “pointer to function returning T”, respectively. The temporary is an lvalue and is used to initialize the variable named in the matching handler (15.3). If the type of the exception object would be an incomplete type or a pointer to an incomplete type other than (possibly cv-qualified) void the program is ill-formed. Except for these restrictions and the restrictions on type matching mentioned in 15.3, the operand of throw is treated exactly as a function argument in a call (5.2.2) or the operand of a return statement. The memory for the exception object is allocated in an unspecified way, except as noted in 3.7.4.1. If a handler exits by rethrowing, control is passed to another handler for the same exception. The exception object is destroyed after either the last remaining active handler for the exception exits by any means other than rethrowing, or the last object of type std::exception_ptr (18.8.5) that refers to the exception object is destroyed, whichever is later. In the former case, the destruction occurs when the handler exits, immediately after the destruction of the object declared in the exception-declaration in the handler, if any. In the latter case, the destruction occurs before the destructor of std::exception_ptr returns. The implementation may then deallocate the memory for the exception object; any such deallocation is done in an unspecified way. [ Note: an exception thrown by a throw-expression does not propagate to other threads unless caught, stored, and rethrown using appropriate library functions; see 18.8.5 and 30.6. — end note ] When the thrown object is a class object, the constructor selected for the copy-initialization and the destructor shall be accessible, even if the copy/move operation is elided (12.8). An exception is considered caught when a handler for that exception becomes active (15.3). [ Note: An exception can have active handlers and still be considered uncaught if it is rethrown. — end note ] If the exception handling mechanism, after completing evaluation of the expression to be thrown but before the exception is caught, calls a function that exits via an exception, std::terminate is called (15.5.1). [ Example: struct C { C() { } C(const C&) { throw 0; } }; int main() { try { throw C(); } catch(C) { } }
8
// calls std::terminate()
— end example ] A throw-expression with no operand rethrows the currently handled exception (15.3). The exception is reactivated with the existing temporary; no new temporary exception object is created. The exception is no longer considered to be caught; therefore, the value of std::uncaught_exception() will again be true. [ Example: code that must be executed because of an exception yet cannot completely handle the exception can be written like this: § 15.1
379
c ISO/IEC
N3376
try { // ... } catch (...) { // catch all exceptions // respond (partially) to exception throw; // pass the exception to some // other handler } 9
— end example ] If no exception is presently being handled, executing a throw-expression with no operand calls std:: terminate() (15.5.1).
15.2 1
2
3
2
3
[except.ctor]
As control passes from a throw-expression to a handler, destructors are invoked for all automatic objects constructed since the try block was entered. The automatic objects are destroyed in the reverse order of the completion of their construction. An object of any storage duration whose initialization or destruction is terminated by an exception will have destructors executed for all of its fully constructed subobjects (excluding the variant members of a union-like class), that is, for subobjects for which the principal constructor (12.6.2) has completed execution and the destructor has not yet begun execution. Similarly, if the non-delegating constructor for an object has completed execution and a delegating constructor for that object exits with an exception, the object’s destructor will be invoked. If the object was allocated in a new-expression, the matching deallocation function (3.7.4.2, 5.3.4, 12.5), if any, is called to free the storage occupied by the object. The process of calling destructors for automatic objects constructed on the path from a try block to a throw-expression is called “stack unwinding.” If a destructor called during stack unwinding exits with an exception, std::terminate is called (15.5.1). [ Note: So destructors should generally catch exceptions and not let them propagate out of the destructor. — end note ]
15.3 1
Constructors and destructors
Handling an exception
[except.handle]
The exception-declaration in a handler describes the type(s) of exceptions that can cause that handler to be entered. The exception-declaration shall not denote an incomplete type, an abstract class type, or an rvalue reference type. The exception-declaration shall not denote a pointer or reference to an incomplete type, other than void*, const void*, volatile void*, or const volatile void*. A handler of type “array of T” or “function returning T” is adjusted to be of type “pointer to T” or “pointer to function returning T”, respectively. A handler is a match for an exception object of type E if — The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or — the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or — the handler is of type cv T or const T& where T is a pointer type and E is a pointer type that can be converted to T by either or both of — a standard pointer conversion (4.10) not involving conversions to pointers to private or protected or ambiguous classes — a qualification conversion — the handler is of type cv T or const T& where T is a pointer or pointer to member type and E is std::nullptr_t. [ Note: A throw-expression whose operand is an integral constant expression of integer type that evaluates to zero does not match a handler of pointer or pointer to member type. — end note ] [ Example: § 15.3
380
c ISO/IEC
class class class class
N3376
Matherr { /∗ ... ∗/ virtual void vf(); }; Overflow: public Matherr { /∗ ... ∗/ }; Underflow: public Matherr { /∗ ... ∗/ }; Zerodivide: public Matherr { /∗ ... ∗/ };
void f() { try { g(); } catch (Overflow oo) { // ... } catch (Matherr mm) { // ... } }
4
5
6
7
8
9
10
11
12
13
14 15
Here, the Overflow handler will catch exceptions of type Overflow and the Matherr handler will catch exceptions of type Matherr and of all types publicly derived from Matherr including exceptions of type Underflow and Zerodivide. — end example ] The handlers for a try block are tried in order of appearance. That makes it possible to write handlers that can never be executed, for example by placing a handler for a derived class after a handler for a corresponding base class. A ... in a handler’s exception-declaration functions similarly to ... in a function parameter declaration; it specifies a match for any exception. If present, a ... handler shall be the last handler for its try block. If no match is found among the handlers for a try block, the search for a matching handler continues in a dynamically surrounding try block of the same thread. A handler is considered active when initialization is complete for the formal parameter (if any) of the catch clause. [ Note: The stack will have been unwound at that point. — end note ] Also, an implicit handler is considered active when std::terminate() or std::unexpected() is entered due to a throw. A handler is no longer considered active when the catch clause exits or when std::unexpected() exits after being entered due to a throw. The exception with the most recently activated handler that is still active is called the currently handled exception. If no matching handler is found, the function std::terminate() is called; whether or not the stack is unwound before this call to std::terminate() is implementation-defined (15.5.1). Referring to any non-static member or base class of an object in the handler for a function-try-block of a constructor or destructor for that object results in undefined behavior. The fully constructed base classes and members of an object shall be destroyed before entering the handler of a function-try-block of a constructor for that object. Similarly, if a delegating constructor for an object exits with an exception after the non-delegating constructor for that object has completed execution, the object’s destructor shall be executed before entering the handler of a function-try-block of a constructor for that object. The base classes and non-variant members of an object shall be destroyed before entering the handler of a function-try-block of a destructor for that object (12.4). The scope and lifetime of the parameters of a function or constructor extend into the handlers of a functiontry-block. Exceptions thrown in destructors of objects with static storage duration or in constructors of namespacescope objects with static storage duration are not caught by a function-try-block on main(). Exceptions thrown in destructors of objects with thread storage duration or in constructors of namespace-scope objects with thread storage duration are not caught by a function-try-block on the initial function of the thread. If a return statement appears in a handler of the function-try-block of a constructor, the program is ill-formed. The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor. Otherwise, a function returns when control reaches the end of a handler for
§ 15.3
381
c ISO/IEC
16
17
the function-try-block (6.6.3). Flowing off the end of a function-try-block is equivalent to a return with no value; this results in undefined behavior in a value-returning function (6.6.3). If the exception-declaration specifies a name, it declares a variable which is copy-initialized (8.5) from the exception object. If the exception-declaration denotes an object type but does not specify a name, a temporary (12.2) is copy-initialized (8.5) from the exception object. The lifetime of the variable or temporary ends when the handler exits, after the destruction of any automatic objects initialized within the handler. When the handler declares a non-constant object, any changes to that object will not affect the temporary object that was initialized by execution of the throw-expression. When the handler declares a reference to a non-constant object, any changes to the referenced object are changes to the temporary object initialized when the throw-expression was executed and will have effect should that object be rethrown.
15.4 1
N3376
Exception specifications
[except.spec]
A function declaration lists exceptions that its function might directly or indirectly throw by using an exception-specification as a suffix of its declarator. exception-specification: dynamic-exception-specification noexcept-specification dynamic-exception-specification: throw ( type-id-listopt ) type-id-list: type-id ...opt type-id-list , type-id ...opt noexcept-specification: noexcept ( constant-expression ) noexcept
2
In a noexcept-specification, the constant-expression, if supplied, shall be a constant expression (5.19) that is contextually converted to bool (Clause 4). A noexcept-specification noexcept is equivalent to noexcept( true). An 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. An exception-specification shall not appear in a typedef declaration or alias-declaration. [ Example: void f() throw(int); void (*fp)() throw (int); void g(void pfa() throw(int)); typedef int (*pf)() throw(int);
3
// // // //
OK OK OK ill-formed
— end example ] A type denoted in an exception-specification shall not denote an incomplete type other than a class currently being defined. A type denoted in an exception-specification shall not denote a pointer or reference to an incomplete type, other than cv void* or a pointer or reference to a class currently being defined. A type cv T, “array of T”, or “function returning T” denoted in an exception-specification is adjusted to type T, “pointer to T”, or “pointer to function returning T”, respectively. Two exception-specifications are compatible if: — both are non-throwing (see below), regardless of their form, — both have the form noexcept(constant-expression) and the constant-expressions are equivalent, or — both are dynamic-exception-specifications that have the same set of adjusted types.
4
If any declaration of a function has an exception-specification that is not a noexcept-specification allowing all exceptions, all declarations, including the definition and any explicit specialization, of that function shall § 15.4
382
c ISO/IEC
5
N3376
have a compatible exception-specification. If any declaration of a pointer to function, reference to function, or pointer to member function has an exception-specification, all occurrences of that declaration shall have a compatible exception-specification In an explicit instantiation an exception-specification may be specified, but is not required. If an exception-specification is specified in an explicit instantiation directive, it shall be compatible with the exception-specifications of other declarations of that function. A diagnostic is required only if the exception-specifications are not compatible within a single translation unit. If a virtual function has an exception-specification, all declarations, including the definition, of any function that overrides that virtual function in any derived class shall only allow exceptions that are allowed by the exception-specification of the base class virtual function. [ Example: struct B { virtual void f() throw (int, double); virtual void g(); }; struct D: B { void f(); void g() throw (int); };
// ill-formed // OK
The declaration of D::f is ill-formed because it allows all exceptions, whereas B::f allows only int and double. — end example ] A similar restriction applies to assignment to and initialization of pointers to functions, pointers to member functions, and references to functions: the target entity shall allow at least the exceptions allowed by the source value in the assignment or initialization. [ Example: class A { /∗ ... ∗/ }; void (*pf1)(); // no exception specification void (*pf2)() throw(A); void f() { pf1 = pf2; pf2 = pf1; } 6
7
8
9
// OK: pf1 is less restrictive // error: pf2 is more restrictive
— end example ] In such an assignment or initialization, exception-specifications on return types and parameter types shall be compatible. In other assignments or initializations, exception-specifications shall be compatible. An exception-specification can include the same type more than once and can include classes that are related by inheritance, even though doing so is redundant. [ Note: An exception-specification can also include the class std::bad_exception (18.8.2). — end note ] A function is said to allow an exception of type E if the constant-expression in its noexcept-specification evaluates to false or its dynamic-exception-specification contains a type T for which a handler of type T would be a match (15.3) for an exception of type E. Whenever an exception is thrown and the search for a handler (15.3) encounters the outermost block of a function with an exception-specification that does not allow the exception, then, — if the exception-specification is a dynamic-exception-specification, the function std::unexpected() is called (15.5.2), — otherwise, the function std::terminate() is called (15.5.1). [ Example: class X { }; class Y { }; class Z: public X { };
§ 15.4
383
c ISO/IEC
N3376
class W { }; void f() throw (X, Y) { int n = 0; if (n) throw X(); if (n) throw Z(); throw W(); }
10
11
// OK // also OK // will call std::unexpected()
— end example ] [ Note: A function can have multiple declarations with different non-throwing exception-specifications; for this purpose, the one on the function definition is used. — end note ] The function unexpected() may throw an exception that will satisfy the exception-specification for which it was invoked, and in this case the search for another handler will continue at the call of the function with this exception-specification (see 15.5.2), or it may call std::terminate(). An implementation shall not reject an expression merely because when executed it throws or might throw an exception that the containing function does not allow. [ Example: extern void f() throw(X, Y); void g() throw(X) { f(); }
12
13 14
// OK
the call to f is well-formed even though when called, f might throw exception Y that g does not allow. — end example ] A function with no exception-specification or with an exception-specification of the form noexcept(constantexpression ) where the constant-expression yields false allows all exceptions. An exception-specification is non-throwing if it is of the form throw(), noexcept, or noexcept(constant-expression ) where the constantexpression yields true. A function with a non-throwing exception-specification does not allow any exceptions. An exception-specification is not considered part of a function’s type. An inheriting constructor (12.9) and an implicitly declared special member function (Clause 12) have an exception-specification. If f is an inheriting constructor or an implicitly declared default constructor, copy constructor, move constructor, destructor, copy assignment operator, or move assignment operator, its implicit exception-specification specifies the type-id T if and only if T is allowed by the exception-specification of a function directly invoked by f’s implicit definition; f allows all exceptions if any function it directly invokes allows all exceptions, and f has the exception-specification noexcept(true) if every function it directly invokes allows no exceptions. [ Note: An instantiation of an inheriting constructor template has an implied exception-specification as if it were a non-template inheriting constructor. — end note ] [ Example: struct A { A(); A(const A&) throw(); A(A&&) throw(); ~A() throw(X); }; struct B { B() throw(); B(const B&) throw(); B(B&&) throw(Y); ~B() throw(Y); }; struct D : public A, public B { // Implicit declaration of D::D(); // Implicit declaration of D::D(const D&) noexcept(true);
§ 15.4
384
c ISO/IEC
N3376
// Implicit declaration of D::D(D&&) throw(Y); // Implicit declaration of D::∼D() throw(X, Y); };
15
16 17
Furthermore, if A::˜A() or B::˜B() were virtual, D::˜D() would not be as restrictive as that of A::˜A, and the program would be ill-formed since a function that overrides a virtual function from a base class shall have an exception-specification at least as restrictive as that in the base class. — end example ] A deallocation function (3.7.4.2) with no explicit exception-specification is treated as if it were specified with noexcept(true). In a dynamic-exception-specification, a type-id followed by an ellipsis is a pack expansion (14.5.3). [ Note: The use of dynamic-exception-specifications is deprecated (see Annex D). — end note ]
15.5
Special functions
[except.special]
1
The functions std::terminate() (15.5.1) and std::unexpected() (15.5.2) are used by the exception handling mechanism for coping with errors related to the exception handling mechanism itself. The function std::current_exception() (18.8.5) and the class std::nested_exception (18.8.6) can be used by a program to capture the currently handled exception.
1
In some situations exception handling must be abandoned for less subtle error handling techniques. [ Note: These situations are: — when the exception handling mechanism, after completing the initialization of the exception object but before activation of a handler for the exception (15.1), calls a function that exits via an exception, or
15.5.1
The std::terminate() function
[except.terminate]
— when the exception handling mechanism cannot find a handler for a thrown exception (15.3), or — when the search for a handler (15.3) encounters the outermost block of a function with a noexceptspecification that does not allow the exception (15.4), or — when the destruction of an object during stack unwinding (15.2) terminates by throwing an exception, or — when initialization of a non-local variable with static or thread storage duration (3.6.2) exits via an exception, or — when destruction of an object with static or thread storage duration exits via an exception (3.6.3), or — when execution of a function registered with std::atexit or std::at_quick_exit exits via an exception (18.5), or — when a throw-expression with no operand attempts to rethrow an exception and no exception is being handled (15.1), or — when std::unexpected throws an exception which is not allowed by the previously violated dynamicexception-specification, and std::bad_exception is not included in that dynamic-exception-specification (15.5.2), or — when the implementation’s default unexpected exception handler is called (D.11.1), or — when the function std::nested_exception::rethrow_nested is called for an object that has captured no exception (18.8.6), or — when execution of the initial function of a thread exits via an exception (30.3.1.2), or
§ 15.5.1
385
c ISO/IEC
N3376
— when the destructor or the copy assignment operator is invoked on an object of type std::thread that refers to a joinable thread (30.3.1.3, 30.3.1.4).
2
— end note ] In such cases, std::terminate() is called (18.8.3). In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before std::terminate() is called. In the situation where the search for a handler (15.3) encounters the outermost block of a function with a noexcept-specification that does not allow the exception (15.4), it is implementation-defined whether the stack is unwound, unwound partially, or not unwound at all before std::terminate() is called. In all other situations, the stack shall not be unwound before std::terminate() is called. An implementation is not permitted to finish stack unwinding prematurely based on a determination that the unwind process will eventually cause a call to std::terminate().
15.5.2 1
2
3
4
[except.unexpected]
If a function with a dynamic-exception-specification throws an exception that is not listed in the dynamicexception-specification, the function std::unexpected() is called (D.11) immediately after completing the stack unwinding for the former function. [ Note: By default, std::unexpected() calls std::terminate(), but a program can install its own handler function (D.11.2). In either case, the constraints in the following paragraph apply. — end note ] The std::unexpected() function shall not return, but it can throw (or re-throw) an exception. If it throws a new exception which is allowed by the exception specification which previously was violated, then the search for another handler will continue at the call of the function whose exception specification was violated. If it throws or rethrows an exception that the dynamic-exception-specification does not allow then the following happens: If the dynamic-exception-specification does not include the class std::bad_exception (18.8.2) then the function std::terminate() is called, otherwise the thrown exception is replaced by an implementation-defined object of the type std::bad_exception and the search for another handler will continue at the call of the function whose dynamic-exception-specification was violated. Thus, a dynamic-exception-specification guarantees that only the listed exceptions will be thrown. If the dynamic-exception-specification includes the type std::bad_exception then any exception not on the list may be replaced by std::bad_exception within the function std::unexpected().
15.5.3 1
The std::unexpected() function
The std::uncaught_exception() function
[except.uncaught]
The function std::uncaught_exception() returns true after completing the initialization of the exception object (15.1) until completing the activation of a handler for the exception (15.3, 18.8.4). This includes stack unwinding. If the exception is rethrown (15.1), std::uncaught_exception() returns true from the point of rethrow until the rethrown exception is caught again.
§ 15.5.3
386
c ISO/IEC
16 1
Preprocessing directives
N3376
[cpp]
A preprocessing directive consists of a sequence of preprocessing tokens that satisfies the following constraints: The first token in the sequence is a # preprocessing token that (at the start of translation phase 4) is either the first character in the source file (optionally after white space containing no new-line characters) or that follows white space containing at least one new-line character. The last token in the sequence is the first newline character that follows the first token in the sequence.145 A new-line character ends the preprocessing directive even if it occurs within what would otherwise be an invocation of a function-like macro. preprocessing-file: groupopt group: group-part group group-part group-part: if-section control-line text-line # non-directive if-section: if-group elif-groupsopt else-groupopt endif-line if-group: # if constant-expression new-line groupopt # ifdef identifier new-line groupopt # ifndef identifier new-line groupopt elif-groups: elif-group elif-groups elif-group elif-group: # elif constant-expression new-line groupopt else-group: # else new-line groupopt endif-line: # endif new-line control-line: # include pp-tokens new-line # define identifier replacement-list new-line # define identifier lparen identifier-listopt ) replacement-list new-line # define identifier lparen ... ) replacement-list new-line # define identifier lparen identifier-list, ... ) replacement-list new-line # undef identifier new-line # line pp-tokens new-line # error pp-tokensopt new-line # pragma pp-tokensopt new-line # new-line text-line: pp-tokensopt new-line 145) Thus, preprocessing directives are commonly called “lines.” These “lines” have no other syntactic significance, as all white space is equivalent except in certain situations during preprocessing (see the # character string literal creation operator in 16.3.2, for example).
Preprocessing directives
387
c ISO/IEC
2
3
4
5
6
N3376
non-directive: pp-tokens new-line lparen: a ( character not immediately preceded by white-space identifier-list: identifier identifier-list , identifier replacement-list: pp-tokensopt pp-tokens: preprocessing-token pp-tokens preprocessing-token new-line: the new-line character
A text line shall not begin with a # preprocessing token. A non-directive shall not begin with any of the directive names appearing in the syntax. When in a group that is skipped (16.1), the directive syntax is relaxed to allow any sequence of preprocessing tokens to occur between the directive name and the following new-line character. The only white-space characters that shall appear between preprocessing tokens within a preprocessing directive (from just after the introducing # preprocessing token through just before the terminating new-line character) are space and horizontal-tab (including spaces that have replaced comments or possibly other white-space characters in translation phase 3). The implementation can process and skip sections of source files conditionally, include other source files, and replace macros. These capabilities are called preprocessing, because conceptually they occur before translation of the resulting translation unit. The preprocessing tokens within a preprocessing directive are not subject to macro expansion unless otherwise stated. [ Example: In: #define EMPTY EMPTY # include
the sequence of preprocessing tokens on the second line is not a preprocessing directive, because it does not begin with a # at the start of translation phase 4, even though it will do so after the macro EMPTY has been replaced. — end example ]
16.1 1
Conditional inclusion
[cpp.cond]
The expression that controls conditional inclusion shall be an integral constant expression except that identifiers (including those lexically identical to keywords) are interpreted as described below146 and it may contain unary operator expressions of the form defined identifier
or defined ( identifier )
2
3
which evaluate to 1 if the identifier is currently defined as a macro name (that is, if it is predefined or if it has been the subject of a #define preprocessing directive without an intervening #undef directive with the same subject identifier), 0 if it is not. Each preprocessing token that remains (in the list of preprocessing tokens that will become the controlling expression) after all macro replacements have occurred shall be in the lexical form of a token (2.7). Preprocessing directives of the forms # if # elif
constant-expression new-line groupopt constant-expression new-line groupopt
146) Because the controlling constant expression is evaluated during translation phase 4, all identifiers either are or are not macro names — there simply are no keywords, enumeration constants, etc.
§ 16.1
388
c ISO/IEC
4
5
check whether the controlling constant expression evaluates to nonzero. Prior to evaluation, macro invocations in the list of preprocessing tokens that will become the controlling constant expression are replaced (except for those macro names modified by the defined unary operator), just as in normal text. If the token defined is generated as a result of this replacement process or use of the defined unary operator does not match one of the two specified forms prior to macro replacement, the behavior is undefined. After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers and keywords147 , except for true and false, are replaced with the pp-number 0, and then each preprocessing token is converted into a token. The resulting tokens comprise the controlling constant expression which is evaluated according to the rules of 5.19 using arithmetic that has at least the ranges specified in 18.3. For the purposes of this token conversion and evaluation all signed and unsigned integer types act as if they have the same representation as, respectively, intmax_t or uintmax_t (18.4).148 This includes interpreting character literals, which may involve converting escape sequences into execution character set members. Whether the numeric value for these character literals matches the value obtained when an identical character literal occurs in an expression (other than within a #if or #elif directive) is implementation-defined.149 Also, whether a single-character character literal may have a negative value is implementation-defined. Each subexpression with type bool is subjected to integral promotion before processing continues. Preprocessing directives of the forms # ifdef # ifndef
6
identifier new-line groupopt identifier new-line groupopt
check whether the identifier is or is not currently defined as a macro name. Their conditions are equivalent to #if defined identifier and #if !defined identifier respectively. Each directive’s condition is checked in order. If it evaluates to false (zero), the group that it controls is skipped: directives are processed only through the name that determines the directive in order to keep track of the level of nested conditionals; the rest of the directives’ preprocessing tokens are ignored, as are the other preprocessing tokens in the group. Only the first group whose control condition evaluates to true (nonzero) is processed. If none of the conditions evaluates to true, and there is a #else directive, the group controlled by the #else is processed; lacking a #else directive, all the groups until the #endif are skipped.150
16.2 1
N3376
Source file inclusion
[cpp.include]
2
A #include directive shall identify a header or source file that can be processed by the implementation. A preprocessing directive of the form
3
searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined. A preprocessing directive of the form
# include < h-char-sequence> new-line
# include " q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read 147) An alternative token (2.6) is not an identifier, even when its spelling consists entirely of letters and underscores. Therefore it is not subject to this replacement. 148) Thus on an implementation where std::numeric_limits::max() is 0x7FFF and std::numeric_limits::max() is 0xFFFF, the integer literal 0x8000 is signed and positive within a #if expression even though it is unsigned in translation phase 7 (2.2). 149) Thus, the constant expression in the following #if directive and if statement is not guaranteed to evaluate to the same value in these two contexts.
#if ’z’ - ’a’ == 25 if (’z’ - ’a’ == 25) 150) As indicated by the syntax, a preprocessing token shall not follow a #else or #endif directive before the terminating new-line character. However, comments may appear anywhere in a source file, including within a preprocessing directive.
§ 16.2
389
c ISO/IEC
N3376
# include < h-char-sequence> new-line 4
with the identical contained sequence (including > characters, if any) from the original directive. A preprocessing directive of the form # include pp-tokens new-line
5
6
7
(that does not match one of the two previous forms) is permitted. The preprocessing tokens after include in the directive are processed just as in normal text (Each identifier currently defined as a macro name is replaced by its replacement list of preprocessing tokens.). If the directive resulting after all replacements does not match one of the two previous forms, the behavior is undefined.151 The method by which a sequence of preprocessing tokens between a < and a > preprocessing token pair or a pair of " characters is combined into a single header name preprocessing token is implementation-defined. The implementation shall provide unique mappings for sequences consisting of one or more nondigits or digits (2.11) followed by a period (.) and a single nondigit. The first character shall not be a digit. The implementation may ignore distinctions of alphabetical case. A #include preprocessing directive may appear in a source file that has been read because of a #include directive in another file, up to an implementation-defined nesting limit. [ Note: Although an implementation may provide a mechanism for making arbitrary source files available to the < > search, in general programmers should use the < > form for headers provided with the implementation, and the " " form for sources outside the control of the implementation. For instance: #include #include #include #include
8
<stdio.h> "usefullib.h" "myprog.h"
— end note ] [ Example: This illustrates macro-replaced #include directives: #if VERSION == 1 #define INCFILE #elif VERSION == 2 #define INCFILE #else #define INCFILE #endif #include INCFILE
"vers1.h" "vers2.h"
// and so on
"versN.h"
— end example ]
16.3 1
2
3
4
Macro replacement
[cpp.replace]
Two replacement lists are identical if and only if the preprocessing tokens in both have the same number, ordering, spelling, and white-space separation, where all white-space separations are considered identical. An identifier currently defined as an object-like macro may be redefined by another #define preprocessing directive provided that the second definition is an object-like macro definition and the two replacement lists are identical, otherwise the program is ill-formed. Likewise, an identifier currently defined as a function-like macro may be redefined by another #define preprocessing directive provided that the second definition is a function-like macro definition that has the same number and spelling of parameters, and the two replacement lists are identical, otherwise the program is ill-formed. There shall be white-space between the identifier and the replacement list in the definition of an object-like macro. If the identifier-list in the macro definition does not end with an ellipsis, the number of arguments (including those arguments consisting of no preprocessing tokens) in an invocation of a function-like macro shall equal the number of parameters in the macro definition. Otherwise, there shall be more arguments in the invocation 151) Note that adjacent string literals are not concatenated into a single string literal (see the translation phases in 2.2); thus, an expansion that results in two string literals is an invalid directive.
§ 16.3
390
c ISO/IEC
N3376
9
than there are parameters in the macro definition (excluding the ...). There shall exist a ) preprocessing token that terminates the invocation. The identifier _ _ VA_ARGS _ _ shall occur only in the replacement-list of a function-like macro that uses the ellipsis notation in the parameters. A parameter identifier in a function-like macro shall be uniquely declared within its scope. The identifier immediately following the define is called the macro name. There is one name space for macro names. Any white-space characters preceding or following the replacement list of preprocessing tokens are not considered part of the replacement list for either form of macro. If a # preprocessing token, followed by an identifier, occurs lexically at the point at which a preprocessing directive could begin, the identifier is not subject to macro replacement. A preprocessing directive of the form
10
defines an object-like macro that causes each subsequent instance of the macro name152 to be replaced by the replacement list of preprocessing tokens that constitute the remainder of the directive.153 The replacement list is then rescanned for more macro names as specified below. A preprocessing directive of the form
5
6 7
8
# define identifier replacement-list new-line
# define identifier lparen identifier-listopt ) replacement-list new-line # define identifier lparen ... ) replacement-list new-line # define identifier lparen identifier-list , ... ) replacement-list new-line
11
12
defines a function-like macro with parameters, whose use is similar syntactically to a function call. The parameters are specified by the optional list of identifiers, whose scope extends from their declaration in the identifier list until the new-line character that terminates the #define preprocessing directive. Each subsequent instance of the function-like macro name followed by a ( as the next preprocessing token introduces the sequence of preprocessing tokens that is replaced by the replacement list in the definition (an invocation of the macro). The replaced sequence of preprocessing tokens is terminated by the matching ) preprocessing token, skipping intervening matched pairs of left and right parenthesis preprocessing tokens. Within the sequence of preprocessing tokens making up an invocation of a function-like macro, new-line is considered a normal white-space character. The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the list of arguments for the function-like macro. The individual arguments within the list are separated by comma preprocessing tokens, but comma preprocessing tokens between matching inner parentheses do not separate arguments. If there are sequences of preprocessing tokens within the list of arguments that would otherwise act as preprocessing directives,154 the behavior is undefined. If there is a ... in the identifier-list in the macro definition, then the trailing arguments, including any separating comma preprocessing tokens, are merged to form a single item: the variable arguments. The number of arguments so combined is such that, following merger, the number of arguments is one more than the number of parameters in the macro definition (excluding the ...).
16.3.1 1
Argument substitution
[cpp.subst]
After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded. Before being substituted, each argument’s preprocessing tokens are completely macro replaced as if they formed the rest of the preprocessing file; no other preprocessing tokens are available. 152) Since, by macro-replacement time, all character literals and string literals are preprocessing tokens, not sequences possibly containing identifier-like subsequences (see 2.2, translation phases), they are never scanned for macro names or parameters. 153) An alternative token (2.6) is not an identifier, even when its spelling consists entirely of letters and underscores. Therefore it is not possible to define a macro whose name is the same as that of an alternative token. 154) Despite the name, a non-directive is a preprocessing directive.
§ 16.3.1
391
c ISO/IEC
2
An identifier _ _ VA_ARGS _ _ that occurs in the replacement list shall be treated as if it were a parameter, and the variable arguments shall form the preprocessing tokens used to replace it.
16.3.2 1
2
2
3
The # operator
[cpp.stringize]
Each # preprocessing token in the replacement list for a function-like macro shall be followed by a parameter as the next preprocessing token in the replacement list. A character string literal is a string-literal with no prefix. If, in the replacement list, a parameter is immediately preceded by a # preprocessing token, both are replaced by a single character string literal preprocessing token that contains the spelling of the preprocessing token sequence for the corresponding argument. Each occurrence of white space between the argument’s preprocessing tokens becomes a single space character in the character string literal. White space before the first preprocessing token and after the last preprocessing token comprising the argument is deleted. Otherwise, the original spelling of each preprocessing token in the argument is retained in the character string literal, except for special handling for producing the spelling of string literals and character literals: a \ character is inserted before each " and \ character of a character literal or string literal (including the delimiting " characters). If the replacement that results is not a valid character string literal, the behavior is undefined. The character string literal corresponding to an empty argument is "". The order of evaluation of # and ## operators is unspecified.
16.3.3 1
N3376
The ## operator
[cpp.concat]
A ## preprocessing token shall not occur at the beginning or at the end of a replacement list for either form of macro definition. If, in the replacement list of a function-like macro, a parameter is immediately preceded or followed by a ## preprocessing token, the parameter is replaced by the corresponding argument’s preprocessing token sequence; however, if an argument consists of no preprocessing tokens, the parameter is replaced by a placemarker preprocessing token instead.155 For both object-like and function-like macro invocations, before the replacement list is reexamined for more macro names to replace, each instance of a ## preprocessing token in the replacement list (not from an argument) is deleted and the preceding preprocessing token is concatenated with the following preprocessing token. Placemarker preprocessing tokens are handled specially: concatenation of two placemarkers results in a single placemarker preprocessing token, and concatenation of a placemarker with a non-placemarker preprocessing token results in the non-placemarker preprocessing token. If the result is not a valid preprocessing token, the behavior is undefined. The resulting token is available for further macro replacement. The order of evaluation of ## operators is unspecified. [ Example: In the following fragment: #define hash_hash # ## # #define mkstr(a) # a #define in_between(a) mkstr(a) #define join(c, d) in_between(c hash_hash d) char p[] = join(x, y); // equivalent to // char p[] = "x ## y";
The expansion produces, at various stages: join(x, y) in_between(x hash_hash y) in_between(x ## y) mkstr(x ## y) "x ## y" 155) Placemarker preprocessing tokens do not appear in the syntax because they are temporary entities that exist only within translation phase 4.
§ 16.3.3
392
c ISO/IEC
N3376
In other words, expanding hash_hash produces a new token, consisting of two adjacent sharp signs, but this new token is not the ## operator. — end example ]
16.3.4 1
2
3
Rescanning and further replacement
After all parameters in the replacement list have been substituted and # and ## processing has taken place, all placemarker preprocessing tokens are removed. Then the resulting preprocessing token sequence is rescanned, along with all subsequent preprocessing tokens of the source file, for more macro names to replace. If the name of the macro being replaced is found during this scan of the replacement list (not including the rest of the source file’s preprocessing tokens), it is not replaced. Furthermore, if any nested replacements encounter the name of the macro being replaced, it is not replaced. These nonreplaced macro name preprocessing tokens are no longer available for further replacement even if they are later (re)examined in contexts in which that macro name preprocessing token would otherwise have been replaced. The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one, but all pragma unary operator expressions within it are then processed as specified in 16.9 below.
16.3.5 1
[cpp.rescan]
Scope of macro definitions
[cpp.scope]
2
A macro definition lasts (independent of block structure) until a corresponding #undef directive is encountered or (if none is encountered) until the end of the translation unit. Macro definitions have no significance after translation phase 4. A preprocessing directive of the form
3
causes the specified identifier no longer to be defined as a macro name. It is ignored if the specified identifier is not currently defined as a macro name. [ Note: The simplest use of this facility is to define a “manifest constant,” as in
# undef identifier new-line
#define TABSIZE 100 int table[TABSIZE]; 4
— end note ] The following defines a function-like macro whose value is the maximum of its arguments. It has the advantages of working for any compatible types of the arguments and of generating in-line code without the overhead of function calling. It has the disadvantages of evaluating one or the other of its arguments a second time (including side effects) and generating more code than a function if invoked several times. It also cannot have its address taken, as it has none. #define max(a, b) ((a) > (b) ? (a) : (b))
5
The parentheses ensure that the arguments and the resulting expression are bound properly. To illustrate the rules for redefinition and reexamination, the sequence #define #define #undef #define #define #define #define #define #define #define #define #define #define #define
§ 16.3.5
x f(a) x x g z h m(a) w t(a) p() q(x) r(x,y) str(x)
3 f(x * (a)) 2 f z[0] g(∼ a(w) 0,1 a int x x ## y # x
393
c ISO/IEC
N3376
f(y+1) + f(f(z)) % t(t(g)(0) + t)(1); g(x+(3,4)-w) | h 5) & m (f)^m(m); p() i[q()] = { q(1), r(2,3), r(4,), r(,5), r(,) }; char c[2][6] = { str(hello), str() };
results in f(2 * (y+1)) + f(2 * (f(2 * (z[0])))) % f(2 * (0)) + t(1); f(2 * (2+(3,4)-0,1)) | f(2 * (∼ 5)) & f(2 * (0,1))^m(0,1); int i[] = { 1, 23, 4, 5, }; char c[2][6] = { "hello", "" }; 6
To illustrate the rules for creating character string literals and concatenating tokens, the sequence #define str(s) #define xstr(s) #define debug(s, t) x ## #define INCFILE(n) #define glue(a, b) #define xglue(a, b) #define HIGHLOW #define LOW
# s str(s) printf("x" # s "= %d, x" # t "= %s", \ s, x ## t) vers ## n a ## b glue(a, b) "hello" LOW ", world"
debug(1, 2); fputs(str(strncmp("abc\0d", "abc", ’\4’) == 0) str(: @\n), s); #include xstr(INCFILE(2).h) glue(HIGH, LOW); xglue(HIGH, LOW)
// this goes away
results in printf("x" "1" "= %d, x" "2" "= %s", x1, x2); fputs("strncmp(\"abc\\0d\", \"abc\", ’\\4’) == 0" ": @\n", s); #include "vers2.h" (after macro replacement, before file access) "hello"; "hello" ", world"
or, after concatenation of the character string literals, printf("x1= %d, x2= %s", x1, x2); fputs("strncmp(\"abc\\0d\", \"abc\", ’\\4’) == 0: @\n", s); #include "vers2.h" (after macro replacement, before file access) "hello"; "hello, world" 7
Space around the # and ## tokens in the macro definition is optional. To illustrate the rules for placemarker preprocessing tokens, the sequence #define t(x,y,z) x ## y ## z int j[] = { t(1,2,3), t(,4,5), t(6,,7), t(8,9,), t(10,,), t(,11,), t(,,12), t(,,) };
results in int j[] = { 123, 45, 67, 89, 10, 11, 12, };
§ 16.3.5
394
c ISO/IEC
8
N3376
To demonstrate the redefinition rules, the following sequence is valid. #define #define #define #define
OBJ_LIKE (1-1) OBJ_LIKE /* white space */ (1-1) /* other */ FUNC_LIKE(a) ( a ) FUNC_LIKE( a )( /* note the white space */ \ a /* other stuff on this line */ )
But the following redefinitions are invalid: #define #define #define #define 9
OBJ_LIKE (0) OBJ_LIKE (1 - 1) FUNC_LIKE(b) ( a ) FUNC_LIKE(b) ( b )
// // // //
different different different different
token sequence white space parameter usage parameter spelling
Finally, to show the variable argument list macro facilities: #define debug(...) fprintf(stderr, _ _ VA_ARGS _ _) #define showlist(...) puts(#_ _ VA_ARGS _ _) #define report(test, ...) ((test) ? puts(#test) : printf(_ _ VA_ARGS _ _)) debug("Flag"); debug("X = %d\n", x); showlist(The first, second, and third items.); report(x>y, "x is %d but y is %d", x, y);
results in fprintf(stderr, "Flag"); fprintf(stderr, "X = %d\n", x); puts("The first, second, and third items."); ((x>y) ? puts("x>y") : printf("x is %d but y is %d", x, y));
— end note ]
16.4 1
Line control
[cpp.line]
3
The string literal of a #line directive, if present, shall be a character string literal. The line number of the current source line is one greater than the number of new-line characters read or introduced in translation phase 1 (2.2) while processing the source file to the current token. A preprocessing directive of the form
4
causes the implementation to behave as if the following sequence of source lines begins with a source line that has a line number as specified by the digit sequence (interpreted as a decimal integer). If the digit sequence specifies zero or a number greater than 2147483647, the behavior is undefined. A preprocessing directive of the form
5
sets the presumed line number similarly and changes the presumed name of the source file to be the contents of the character string literal. A preprocessing directive of the form
2
# line digit-sequence new-line
# line digit-sequence " s-char-sequenceopt " new-line
# line pp-tokens new-line
(that does not match one of the two previous forms) is permitted. The preprocessing tokens after line on the directive are processed just as in normal text (each identifier currently defined as a macro name is replaced by its replacement list of preprocessing tokens). If the directive resulting after all replacements does not match one of the two previous forms, the behavior is undefined; otherwise, the result is processed as appropriate.
16.5 1
Error directive
[cpp.error]
A preprocessing directive of the form § 16.5
395
c ISO/IEC
N3376
# error pp-tokensopt new-line
causes the implementation to produce a diagnostic message that includes the specified sequence of preprocessing tokens, and renders the program ill-formed.
16.6 1
Pragma directive
[cpp.pragma]
A preprocessing directive of the form # pragma pp-tokensopt new-line
causes the implementation to behave in an implementation-defined manner. The behavior might cause translation to fail or cause the translator or the resulting program to behave in a non-conforming manner. Any pragma that is not recognized by the implementation is ignored.
16.7 1
Null directive
[cpp.null]
A preprocessing directive of the form # new-line
has no effect.
16.8 1
Predefined macro names
[cpp.predefined]
The following macro names shall be defined by the implementation: _ _ cplusplus The name _ _ cplusplus is defined to the value 201103L when compiling a C++ translation unit.156 _ _ DATE _ _ The date of translation of the source file: a character string literal of the form "Mmm dd yyyy", where the names of the months are the same as those generated by the asctime function, and the first character of dd is a space character if the value is less than 10. If the date of translation is not available, an implementation-defined valid date shall be supplied. _ _ FILE _ _ The presumed name of the current source file (a character string literal).157 _ _ LINE _ _ The presumed line number (within the current source file) of the current source line (an integer constant).157 _ _ STDC_HOSTED _ _ The integer constant 1 if the implementation is a hosted implementation or the integer constant 0 if it is not. _ _ TIME _ _ The time of translation of the source file: a character string literal of the form "hh:mm:ss" as in the time generated by the asctime function. If the time of translation is not available, an implementationdefined valid time shall be supplied.
2
The following macro names are conditionally defined by the implementation: _ _ STDC _ _ Whether _ _ STDC _ _ is predefined and if so, what its value is, are implementation-defined. _ _ STDC_MB_MIGHT_NEQ_WC _ _ The integer constant 1, intended to indicate that, in the encoding for wchar_t, a member of the basic character set need not have a code value equal to its value when used as the lone character in an ordinary character literal. 156) It is intended that future versions of this standard will replace the value of this macro with a greater value. Non-conforming compilers should use a value with at most five decimal digits. 157) The presumed source file name and line number can be changed by the #line directive.
§ 16.8
396
c ISO/IEC
N3376
_ _ STDC_VERSION _ _ Whether _ _ STDC_VERSION _ _ is predefined and if so, what its value is, are implementation-defined. _ _ STDC_ISO_10646 _ _ An integer constant of the form yyyymmL (for example, 199712L). If this symbol is defined, then every character in the Unicode required set, when stored in an object of type wchar_t, has the same value as the short identifier of that character. The Unicode required set consists of all the characters that are defined by ISO/IEC 10646, along with all amendments and technical corrigenda as of the specified year and month. _ _ STDCPP_STRICT_POINTER_SAFETY _ _ Defined, and has the value integer constant 1, if and only if the implementation has strict pointer safety (3.7.4.3). _ _ STDCPP_THREADS _ _ Defined, and has the value integer constant 1, if and only if a program can have more than one thread of execution (1.10). 3
4
The values of the predefined macros (except for _ _ FILE _ _ and _ _ LINE _ _) remain constant throughout the translation unit. If any of the pre-defined macro names in this subclause, or the identifier defined, is the subject of a #define or a #undef preprocessing directive, the behavior is undefined. Any other predefined macro names shall begin with a leading underscore followed by an uppercase letter or a second underscore.
16.9
Pragma operator
[cpp.pragma.op]
A unary operator expression of the form: _Pragma ( string-literal )
is processed as follows: The string literal is destringized by deleting the L prefix, if present, deleting the leading and trailing double-quotes, replacing each escape sequence \" by a double-quote, and replacing each escape sequence \\ by a single backslash. The resulting sequence of characters is processed through translation phase 3 to produce preprocessing tokens that are executed as if they were the pp-tokens in a pragma directive. The original four preprocessing tokens in the unary operator expression are removed. [ Example: #pragma listing on "..\listing.dir"
can also be expressed as: _Pragma ( "listing on \"..\\listing.dir\"" )
The latter form is processed in the same way whether it appears literally as shown, or results from macro replacement, as in: #define LISTING(x) PRAGMA(listing on #x) #define PRAGMA(x) _Pragma(#x) LISTING( ..\listing.dir )
— end example ]
§ 16.9
397
c ISO/IEC
17 17.1 1
2
3
N3376
Library introduction General
[library] [library.general]
This Clause describes the contents of the C++ standard library, how a well-formed C++ program makes use of the library, and how a conforming implementation may provide the entities in the library. The following subclauses describe the definitions (17.3), method of description (17.5), and organization (17.6.1) of the library. Clause 17.6, Clauses 18 through 30, and Annex D specify the contents of the library, as well as library requirements and constraints on both well-formed C++ programs and conforming implementations. Detailed specifications for each of the components in the library are in Clauses 18–30, as shown in Table 13. Table 13 — Library categories Clause 18 19 20 21 22 23 24 25 26 27 28 29 30
4
5
6
7
8 9
10
11
Category Language support library Diagnostics library General utilities library Strings library Localization library Containers library Iterators library Algorithms library Numerics library Input/output library Regular expressions library Atomic operations library Thread support library
The language support library (Clause 18) provides components that are required by certain parts of the C++ language, such as memory allocation (5.3.4, 5.3.5) and exception processing (Clause 15). The diagnostics library (Clause 19) provides a consistent framework for reporting errors in a C++ program, including predefined exception classes. The general utilities library (Clause 20) includes components used by other library elements, such as a predefined storage allocator for dynamic storage management (3.7.4), and components used as infrastructure in C++ programs, such as a tuples, function wrappers, and time facilities. The strings library (Clause 21) provides support for manipulating text represented as sequences of type char, sequences of type char16_t, sequences of type char32_t, sequences of type wchar_t, and sequences of any other character-like type. The localization library (Clause 22) provides extended internationalization support for text processing. The containers (Clause 23), iterators (Clause 24), and algorithms (Clause 25) libraries provide a C++ program with access to a subset of the most widely used algorithms and data structures. The numerics library (Clause 26) provides numeric algorithms and complex number components that extend support for numeric processing. The valarray component provides support for n-at-a-time processing, potentially implemented as parallel operations on platforms that support such processing. The random number component provides facilities for generating pseudo-random numbers. The input/output library (Clause 27) provides the iostream components that are the primary mechanism for C++ program input and output. They can be used with other elements of the library, particularly strings, § 17.1
398
c ISO/IEC
12 13
14
locales, and iterators. The regular expressions library (Clause 28) provides regular expression matching and searching. The atomic operations library (Clause 29) allows more fine-grained concurrent access to shared data than is possible with locks. The thread support library (Clause 30) provides components to create and manage threads, including mutual exclusion and interthread communication.
17.2 1
2
N3376
The C standard library
[library.c]
The C++ standard library also makes available the facilities of the C standard library, suitably adjusted to ensure static type safety. The descriptions of many library functions rely on the C standard library for the signatures and semantics of those functions. In all such cases, any use of the restrict qualifier shall be omitted.
17.3
Definitions
[definitions]
17.3.1 [defns.arbitrary.stream] arbitrary-positional stream a stream (described in Clause 27) that can seek to any integral position within the length of the stream [ Note: Every arbitrary-positional stream is also a repositional stream. — end note ] 17.3.2 block place a thread in the blocked state
[defns.block]
17.3.3 [defns.blocked] blocked thread a thread that is waiting for some condition (other than the availability of a processor) to be satisfied before it can continue execution158 17.3.4 [defns.character] character any object which, when treated sequentially, can represent text [ Note: The term does not mean only char, char16_t, char32_t, and wchar_t objects, but any value that can be represented by a type that provides the definitions specified in these Clauses. — end note ] 17.3.5 [defns.character.container] character container type a class or a type used to represent a character [ Note: It is used for one of the template parameters of the string, iostream, and regular expression class templates. A character container type is a POD (3.9) type. — end note ] 17.3.6 [defns.comparison] comparison function an operator function (13.5) for any of the equality (5.10) or relational (5.9) operators 17.3.7 component a group of library entities directly related as members, parameters, or return types
[defns.component]
158) This definition is taken from POSIX.
§ 17.3
399
c ISO/IEC
N3376
[ Note: For example, the class template basic_string and the non-member function templates that operate on strings are referred to as the string component. — end note ] 17.3.8 [defns.deadlock] deadlock one or more threads are unable to continue execution because each is blocked waiting for one or more of the others to satisfy some condition 17.3.9 [defns.default.behavior.impl] default behavior any specific behavior provided by the implementation, within the scope of the required behavior 17.3.10 [defns.default.behavior.func] default behavior <specification> a description of replacement function and handler function semantics 17.3.11 [defns.handler] handler function a non-reserved function whose definition may be provided by a C++ program [ Note: A C++ program may designate a handler function at various points in its execution by supplying a pointer to the function when calling any of the library functions that install handler functions (Clause 18). — end note ] 17.3.12 [defns.iostream.templates] iostream class templates templates, defined in Clause 27, that take two template arguments [ Note: The arguments are named charT and traits. The argument charT is a character container class, and the argument traits is a class which defines additional characteristics and functions of the character type represented by charT necessary to implement the iostream class templates. — end note ] 17.3.13 [defns.modifier] modifier function a class member function (9.3) other than a constructor, assignment operator, or destructor that alters the state of an object of the class 17.3.14 move construction direct-initialization of an object of some type with an rvalue of the same type
[defns.move.constr]
17.3.15 [defns.move.assign] move assignment assignment of an rvalue of some object type to a modifiable lvalue of the same type 17.3.16 [defns.obj.state] object state the current value of all non-static class members of an object (9.2) [ Note: The state of an object can be obtained by using one or more observer functions. — end note ] 17.3.17 § 17.3
[defns.ntcts] 400
c ISO/IEC
N3376
NTCTS a sequence of values that have character type that precede the terminating null character type value charT() 17.3.18 [defns.observer] observer function a class member function (9.3) that accesses the state of an object of the class but does not alter that state [ Note: Observer functions are specified as const member functions (9.3.2). — end note ] 17.3.19 [defns.replacement] replacement function a non-reserved function whose definition is provided by a C++ program [ Note: Only one definition for such a function is in effect for the duration of the program’s execution, as the result of creating the program (2.2) and resolving the definitions of all translation units (3.5). — end note ] 17.3.20 [defns.repositional.stream] repositional stream a stream (described in Clause 27) that can seek to a position that was previously encountered 17.3.21 [defns.required.behavior] required behavior a description of replacement function and handler function semantics applicable to both the behavior provided by the implementation and the behavior of any such function definition in the program [ Note: If such a function defined in a C++ program fails to meet the required behavior when it executes, the behavior is undefined. — end note ] 17.3.22 [defns.reserved.function] reserved function a function, specified as part of the C++ standard library, that must be defined by the implementation [ Note: If a C++ program provides a definition for any reserved function, the results are undefined. — end note ] 17.3.23 [defns.stable] stable algorithm an algorithm that preserves, as appropriate to the particular algorithm, the order of elements [ Note: Requirements for stable algorithms are given in 17.6.5.7. — end note ] 17.3.24 [defns.traits] traits class a class that encapsulates a set of types and functions necessary for class templates and function templates to manipulate objects of types for which they are instantiated [ Note: Traits classes defined in Clauses 21, 22 and 27 are character traits, which provide the character handling support needed by the string and iostream classes. — end note ] 17.3.25 unblock place a thread in the unblocked state
[defns.unblock]
17.3.26 [defns.valid] valid but unspecified state an object state that is not specified except that the object’s invariants are met and operations on the object § 17.3
401
c ISO/IEC
N3376
behave as specified for its type [ Example: If an object x of type std::vector is in a valid but unspecified state, x.empty() can be called unconditionally, and x.front() can be called only if x.empty() returns false. — end example ]
17.4 1
Method of description (Informative)
[description]
This subclause describes the conventions used to specify the C++ standard library. 17.5.1 describes the structure of the normative Clauses 18 through 30 and Annex D. 17.5.2 describes other editorial conventions.
17.5.1
Structure of each clause
17.5.1.1 1
[defns.additional]
1.3 defines additional terms used elsewhere in this International Standard.
17.5 1
Additional definitions
[structure]
Elements
[structure.elements]
Each library clause contains the following elements, as applicable:159 — Summary — Requirements — Detailed specifications — References to the Standard C library 17.5.1.2
1
2 3
Summary
[structure.summary]
The Summary provides a synopsis of the category, and introduces the first-level subclauses. Each subclause also provides a summary, listing the headers specified in the subclause and the library entities provided in each header. Paragraphs labeled “Note(s):” or “Example(s):” are informative, other paragraphs are normative. The contents of the summary and the detailed specifications include: — macros — values — types — classes and class templates — functions and function templates — objects 17.5.1.3
1
Requirements
Requirements describe constraints that shall be met by a Such extensions are generally one of the following: — Template arguments
[structure.requirements] C++
program that extends the standard library.
— Derived classes — Containers, iterators, and algorithms that meet an interface convention 2
3
The string and iostream components use an explicit representation of operations required of template arguments. They use a class template char_traits to define these constraints. Interface convention requirements are stated as generally as possible. Instead of stating “class X has to define a member function operator++(),” the interface requires “for any object x of class X, ++x is defined.” That is, whether the operator is a member is unspecified. 159) To save space, items that do not apply to a Clause are omitted. For example, if a Clause does not specify any requirements, there will be no “Requirements” subclause.
§ 17.5.1.3
402
c ISO/IEC
4
5 6
Requirements are stated in terms of well-defined expressions that define valid terms of the types that satisfy the requirements. For every set of well-defined expression requirements there is a table that specifies an initial set of the valid expressions and their semantics. Any generic algorithm (Clause 25) that uses the well-defined expression requirements is described in terms of the valid expressions for its formal type parameters. Template argument requirements are sometimes referenced by name. See 17.5.2.1. In some cases the semantic requirements are presented as C++ code. Such code is intended as a specification of equivalence of a construct to another construct, not necessarily as the way the construct must be implemented.160 17.5.1.4
1
N3376
Detailed specifications
[structure.specifications]
The detailed specifications each contain the following elements: — name and brief description — synopsis (class definition or function prototype, as appropriate) — restrictions on template arguments, if any — description of class invariants — description of function semantics
2
Descriptions of class member functions follow the order (as appropriate):161 — constructor(s) and destructor — copying, moving & assignment functions — comparison functions — modifier functions — observer functions — operators and other non-member functions
3
Descriptions of function semantics contain the following elements (as appropriate):162 — Requires: the preconditions for calling the function — Effects: the actions performed by the function — Synchronization: the synchronization operations (1.10) applicable to the function — Postconditions: the observable results established by the function — Returns: a description of the value(s) returned by the function — Throws: any exceptions thrown by the function, and the conditions that would cause the exception — Complexity: the time and/or space complexity of the function — Remarks: additional semantic constraints on the function 160) Although in some cases the code given is unambiguously the optimum implementation. 161) To save space, items that do not apply to a class are omitted. For example, if a class does not specify any comparison
functions, there will be no “Comparison functions” subclause. 162) To save space, items that do not apply to a function are omitted. For example, if a function does not specify any further preconditions, there will be no “Requires” paragraph.
§ 17.5.1.4
403
c ISO/IEC
N3376
— Error conditions: the error conditions for error codes reported by the function. — Notes: non-normative comments about the function 4
5
6
7
8
Whenever the Effects: element specifies that the semantics of some function F are Equivalent to some code sequence, then the various elements are interpreted as follows. If F’s semantics specifies a Requires: element, then that requirement is logically imposed prior to the equivalent-to semantics. Next, the semantics of the code sequence are determined by the Requires:, Effects:, Postconditions:, Returns:, Throws:, Complexity:, Remarks:, Error conditions:, and Notes: specified for the function invocations contained in the code sequence. The value returned from F is specified by F’s Returns: element, or if F has no Returns: element, a non-void return from F is specified by the Returns: elements in the code sequence. If F’s semantics contains a Throws:, Postconditions:, or Complexity: element, then that supersedes any occurrences of that element in the code sequence. For non-reserved replacement and handler functions, Clause 18 specifies two behaviors for the functions in question: their required and default behavior. The default behavior describes a function definition provided by the implementation. The required behavior describes the semantics of a function definition provided by either the implementation or a C++ program. Where no distinction is explicitly made in the description, the behavior described is the required behavior. If the formulation of a complexity requirement calls for a negative number of operations, the actual requirement is zero operations.163 Complexity requirements specified in the library clauses are upper bounds, and implementations that provide better complexity guarantees satisfy the requirements. Error conditions specify conditions where a function may fail. The conditions are listed, together with a suitable explanation, as the enum class errc constants (19.5). 17.5.1.5
1
Other conventions
2
1
2
[conventions]
This subclause describes several editorial conventions used to describe the contents of the C++ standard library. These conventions are for describing implementation-defined types (17.5.2.1), and member functions (17.5.2.2). 17.5.2.1 Type descriptions [type.descriptions] 17.5.2.1.1
1
[structure.see.also]
Paragraphs labeled “See also:” contain cross-references to the relevant portions of this International Standard and the ISO C standard, which is incorporated into this International Standard by reference.
17.5.2 1
C library
General
[type.descriptions.general]
The Requirements subclauses may describe names that are used to specify constraints on template arguments.164 These names are used in library Clauses to describe the types that may be supplied as arguments by a C++ program when instantiating template components from the library. Certain types defined in Clause 27 are used to describe implementation-defined types. They are based on other types, but with added constraints. 17.5.2.1.2 Enumerated types [enumerated.types] Several types defined in Clause 27 are enumerated types. Each enumerated type may be implemented as an enumeration or as a synonym for an enumeration.165 The enumerated type enumerated can be written: enum enumerated
{ V0 , V1 , V2 , V3 , ..... };
static const enumerated C0
(V0 );
163) This simplifies the presentation of complexity requirements in some cases. 164) Examples from 17.6.3 include: EqualityComparable, LessThanComparable, CopyConstructible. Examples from 24.2 in-
clude: InputIterator, ForwardIterator, Function, Predicate. 165) Such as an integer type, with constant integer values (3.9.1).
§ 17.5.2.1.2
404
c ISO/IEC
N3376
static const enumerated C1 static const enumerated C2 static const enumerated C3 .....
(V1 ); (V2 ); (V3 );
3
Here, the names C0 , C1 , etc. represent enumerated elements for this particular enumerated type. All such elements have distinct values. 17.5.2.1.3 Bitmask types [bitmask.types]
1
Several types defined in Clauses 18 through 30 and Annex D are bitmask types. Each bitmask type can be implemented as an enumerated type that overloads certain operators, as an integer type, or as a bitset (20.5).
2
The bitmask type bitmask can be written: // For exposition only. // int_type is an integral type capable of // representing all values of the bitmask type. enum bitmask : int_type { V0 = 1
<list> <map> <memory> <mutex>
<scoped_allocator> <set> <sstream> <stack> <stdexcept> <streambuf> <string> <strstream> <system_error>
Table 15 — C++ headers for C library facilities
6 7
8
1
2
3
<cuchar>
Names that are defined as functions in C shall be defined as functions in the C++ standard library.174 Identifiers that are keywords or operators in C++ shall not be defined as macros in C++ standard library headers.175 D.5, C standard library headers, describes the effects of using the name.h (C header) form in a C++ program.176 17.6.1.3 Freestanding implementations [compliance] Two kinds of implementations are defined: hosted and freestanding (1.4). For a hosted implementation, this International Standard describes the set of available headers. A freestanding implementation has an implementation-defined set of headers. This set shall include at least the headers shown in Table 16. The supplied version of the header shall declare at least the functions abort, atexit, at_quick_exit, exit, and quick_exit (18.5). The other headers listed in this table shall meet the same requirements as for a hosted implementation.
17.6.2 17.6.2.1 1
Using the library Overview
[using] [using.overview]
This section describes how a C++ program gains access to the facilities of the C++ standard library. 17.6.2.2 174) This disallows the practice, allowed in C, of providing a masking macro in addition to the function prototype. The only way to achieve equivalent inline behavior in C++ is to provide a definition as an extern inline function. 175) In particular, including the standard header or has no effect. 176) The ".h" headers dump all their names into the global namespace, whereas the newer forms keep their names in namespace std. Therefore, the newer forms are the preferred forms for all uses except for C++ programs which are intended to be strictly compatible with C.
§ 17.6.2.1
408
c ISO/IEC
N3376
Table 16 — C++ headers for freestanding implementations Subclause 18.2 18.3 18.4 18.5 18.6 18.7 18.8 18.9 18.10 20.9 29
Types Implementation properties Integer types Start and termination Dynamic memory management Type identification Exception handling Initializer lists Other runtime support Type traits Atomics
Header(s) <exception>
describes effects during translation phase 4, while 17.6.2.3 describes effects during phase 8 (2.2). 17.6.2.2 Headers [using.headers] 1
2
3
1
2
3
The entities in the C++ standard library are defined in headers, whose contents are made available to a translation unit when it contains the appropriate #include preprocessing directive (16.2). A translation unit may include library headers in any order (Clause 2). Each may be included more than once, with no effect different from being included exactly once, except that the effect of including either or depends each time on the lexically current definition of NDEBUG.177 A translation unit shall include a header only outside of any external declaration or definition, and shall include the header lexically before the first reference in that translation unit to any of the entities declared in that header. 17.6.2.3 Linkage [using.linkage] Entities in the C++ standard library have external linkage (3.5). Unless otherwise specified, objects and functions have the default extern "C++" linkage (7.5). Whether a name from the C standard library declared with external linkage has extern "C" or extern "C++" linkage is implementation-defined. It is recommended that an implementation use extern "C++" linkage for this purpose.178 Objects and functions defined in the library and required by a C++ program are included in the program prior to program startup. See also: replacement functions (17.6.4.6), run-time changes (17.6.4.7).
17.6.3
Requirements on types and expressions
[utility.requirements]
1
17.6.3.1 describes requirements on types and expressions used to instantiate templates defined in the C++ standard library. 17.6.3.2 describes the requirements on swappable types and swappable expressions. 17.6.3.3 describes the requirements on pointer-like types that support null values. 17.6.3.4 describes the requirements on hash function objects. 17.6.3.5 describes the requirements on storage allocators. 17.6.3.1 Template argument requirements [utility.arg.requirements]
1
The template definitions in the C++ standard library refer to various named requirements whose details are set out in tables 17–24. In these tables, T is an object or reference type to be supplied by a C++ program instantiating a template; a, b, and c are values of type (possibly const) T; s and t are modifiable lvalues of 177) This is the same as the Standard C library. 178) The only reliable way to declare an object or function signature from the Standard C library is by including the header
that declares it, notwithstanding the latitude granted in 7.1.7 of the C Standard.
§ 17.6.3.1
409
c ISO/IEC
2
N3376
type T; u denotes an identifier; rv is an rvalue of type T; and v is an lvalue of type (possibly const) T or an rvalue of type const T. In general, a default constructor is not required. Certain container class member function signatures specify T() as a default argument. T() shall be a well-defined expression (8.5) if one of those signatures is called using the default argument (8.3.6). Table 17 — EqualityComparable requirements [equalitycomparable] Expression a == b
Return type convertible to bool
Requirement == is an equivalence relation, that is, it has the following properties: — For all a, a == a. — If a == b, then b == a. — If a == b and b == c, then a == c.
Table 18 — LessThanComparable requirements [lessthancomparable] Expression a < b
Return type convertible to bool
Requirement < is a strict weak ordering relation (25.4)
Table 19 — DefaultConstructible requirements [defaultconstructible] Expression T t; T u{}; T() T{}
Post-condition object t is default-initialized object u is value-initialized a temporary object of type T is value-initialized
Table 20 — MoveConstructible requirements [moveconstructible] Expression Post-condition T u = rv; u is equivalent to the value of rv before the construction T(rv) T(rv) is equivalent to the value of rv before the construction rv’s state is unspecified [ Note:rv must still meet the requirements of the library component that is using it. The operations listed in those requirements must work as specified whether rv has been moved from or not. — end note ]
§ 17.6.3.1
410
c ISO/IEC
N3376
Table 21 — CopyConstructible requirements (in addition to MoveConstructible) [copyconstructible] Expression T u = v; T(v)
Post-condition the value of v is unchanged and is equivalent to u the value of v is unchanged and is equivalent to T(v)
Table 22 — MoveAssignable requirements [moveassignable] Expression t = rv
Return type T&
Return value t
Post-condition t is equivalent to the value of rv before the assignment rv’s state is unspecified. [ Note: rv must still meet the requirements of the library component that is using it. The operations listed in those requirements must work as specified whether rv has been moved from or not. — end note ]
Table 23 — CopyAssignable requirements (in addition to MoveAssignable) [copyassignable] Expression t = v
Return type T&
Return value t
Post-condition t is equivalent to v, the value of v is unchanged
Table 24 — Destructible requirements [destructible] Expression u.∼T()
17.6.3.2 1
2
Post-condition All resources owned by u are reclaimed, no exception is propagated.
Swappable requirements
[swappable.requirements]
This subclause provides definitions for swappable types and expressions. In these definitions, let t denote an expression of type T, and let u denote an expression of type U. An object t is swappable with an object u if and only if: — the expressions swap(t, u) and swap(u, t) are valid when evaluated in the context described below, and — these expressions have the following effects: — the object referred to by t has the value originally held by u and — the object referred to by u has the value originally held by t.
3
The context in which swap(t, u) and swap(u, t) are evaluated shall ensure that a binary non-member function named “swap” is selected via overload resolution (13.3) on a candidate set that includes: — the two swap function templates defined in (20.2) and — the lookup set produced by argument-dependent lookup (3.4.2).
§ 17.6.3.2
411
c ISO/IEC
4
5
N3376
[ Note: If T and U are both fundamental types or arrays of fundamental types and the declarations from the header are in scope, the overall lookup set described above is equivalent to that of the qualified name lookup applied to the expression std::swap(t, u) or std::swap(u, t) as appropriate. — end note ] [ Note: It is unspecified whether a library component that has a swappable requirement includes the header to ensure an appropriate evaluation context. — end note ] An rvalue or lvalue t is swappable if and only if t is swappable with any rvalue or lvalue, respectively, of type T. A type X satisfying any of the iterator requirements (24.2) satisfies the requirements of ValueSwappable if, for any dereferenceable object x of type X, *x is swappable. [ Example: User code can ensure that the evaluation of swap calls is performed in an appropriate context under the various conditions as follows: #include // Requires: std::forward(t) shall be swappable with std::forward(u). template void value_swap(T&& t, U&& u) { using std::swap; swap(std::forward(t), std::forward(u)); // OK: uses “swappable with” conditions // for rvalues and lvalues } // Requires: lvalues of T shall be swappable. template void lv_swap(T& t1 T& t2) { using std::swap; swap(t1, t2); }
// OK: uses swappable conditions for // lvalues of type T
namespace N { struct A { int m; }; struct Proxy { A *a; }; Proxy proxy(A& a) { return Proxy{ &a }; } void swap(A& x, Proxy p) { std::swap(x.m, p.a->m); } void swap(Proxy p, A& x) { swap(x, p); }
// OK: uses context equivalent to swappable // conditions for fundamental types // satisfy symmetry constraint
} int main() { int i = 1, j = 2; lv_swap(i, j); assert(i == 2 && j == 1); N::A a1 = { 5 }, a2 = { -5 }; value_swap(a1, proxy(a2)); assert(a1.m == -5 && a2.m == 5); }
— end example ] 17.6.3.3 1
NullablePointer requirements
[nullablepointer.requirements]
A NullablePointer type is a pointer-like type that supports null values. A type P meets the requirements § 17.6.3.3
412
c ISO/IEC
N3376
of NullablePointer if: — P satisfies the requirements of EqualityComparable, DefaultConstructible, CopyConstructible, CopyAssignable, and Destructible, — lvalues of type P are swappable (17.6.3.2), — the expressions shown in Table 25 are valid and have the indicated semantics, and — P satisfies all the other requirements of this subclause. 2
3
4 5
A value-initialized object of type P produces the null value of the type. The null value shall be equivalent only to itself. A default-initialized object of type P may have an indeterminate value. [ Note: Operations involving indeterminate values may cause undefined behavior. — end note ] An object p of type P can be contextually converted to bool (Clause 4). The effect shall be as if p != nullptr had been evaluated in place of p. No operation which is part of the NullablePointer requirements shall exit via an exception. In Table 25, u denotes an identifier, t denotes a non-const lvalue of type P, a and b denote values of type (possibly const) P, and np denotes a value of type (possibly const) std::nullptr_t. Table 25 — NullablePointer requirements [nullablepointer] Expression P u(np); P u = np; P(np) t = np a != b a == np np == a a != np np != a
17.6.3.4 1
Return type
Operational semantics post: u == nullptr
P& contextually convertible to bool contextually convertible to bool
post: P(np) == nullptr post: t == nullptr !(a == b) a == P()
contextually convertible to bool
!(a == np)
Hash requirements
[hash.requirements]
A type H meets the Hash requirements if: — it is a function object type (20.8), — it satisfies the requirements of CopyConstructible and Destructible (17.6.3.1), and — the expressions shown in Table 26 are valid and have the indicated semantics.
2
Given Key is an argument type for function objects of type H, in Table 26 h is a value of type (possibly const) H, u is an lvalue of type Key, and k is a value of a type convertible to (possibly const) Key. 17.6.3.5
1
Allocator requirements
[allocator.requirements]
The library describes a standard set of requirements for allocators, which are class-type objects that encapsulate the information about an allocation model. This information includes the knowledge of pointer types, the type of their difference, the type of the size of objects in this allocation model, as well as the memory allocation and deallocation primitives for it. All of the string types (Clause 21), containers (Clause 23) (except array), string buffers and string streams (Clause 27), and match_results (Clause 28) are parameterized in terms of allocators. § 17.6.3.5
413
c ISO/IEC
N3376
Table 26 — Hash requirements [hash]
2
Expression h(k)
Return type size_t
h(u)
size_t
Requirement The value returned shall depend only on the argument k. [ Note: Thus all evaluations of the expression h(k) with the same value for k yield the same result. — end note ] [ Note: For two different values t1 and t2, the probability that h(t1) and h(t2) compare equal should be very small, approaching 1.0 / numeric_limits<size_t>::max(). — end note ] Shall not modify u.
The template struct allocator_traits (20.6.8) supplies a uniform interface to all allocator types. Table 27 describes the types manipulated through allocators. Table 28 describes the requirements on allocator types and thus on types used to instantiate allocator_traits. A requirement is optional if the last column of Table 28 specifies a default for a given expression. Within the standard library allocator_traits template, an optional requirement that is not supplied by an allocator is replaced by the specified default expression. A user specialization of allocator_traits may provide different defaults and may provide defaults for different requirements than the primary template. Within Tables 27 and 28, the use of move and forward always refers to std::move and std::forward, respectively. Table 27 — Descriptive variable definitions Variable T, U, C V X Y XX YY t a, a1, a2 a3 b c p q w z r s u
§ 17.6.3.5
Definition any non-const object type (3.9) a type convertible to T an Allocator class for type T the corresponding Allocator class for type U the type allocator_traits<X> the type allocator_traits a value of type const T& values of type X& an rvalue of type X a value of type Y a dereferenceable pointer of type C* a value of type XX::pointer, obtained by calling a1.allocate, where a1 == a a value of type XX::const_pointer obtained by conversion from a value p. a value of type XX::void_pointer obtained by conversion from a value p a value of type XX::const_void_pointer obtained by conversion from a value q or a value w a value of type T& obtained by the expression *p. a value of type const T& obtained by the expression *q or by conversion from a value r. a value of type YY::const_pointer obtained by calling YY::allocate, or else nullptr. 414
c ISO/IEC
N3376
Table 27 — Descriptive variable definitions (continued) Variable v n Args args
Definition a a a a
value of type V value of type XX::size_type. template parameter pack function parameter pack with the pattern Args&&
Table 28 — Allocator requirements Expression
Return type
X::pointer X::const_pointer
Assertion/note pre-/post-condition X::pointer is convertible to X::const_pointer
X::pointer is convertible to X::void_pointer. X::void_pointer and Y::void_pointer are the same type. X::pointer, X::const_pointer, and X::void_pointer are convertible to X::const_void_pointer. X::const_void_pointer and Y::const_void_pointer are the same type.
X::void_pointer Y::void_pointer
X::const_void_pointer Y::const_void_pointer
X::value_type X::size_type
Identical to T unsigned integer type
X::difference_type
signed integer type
a type that can represent the difference between any two pointers in the allocation model.
typename X::template rebind::other *p *q
Y
For all U (including T), Y::template rebind::other is X.
T& const T&
p->m
type of T::m
§ 17.6.3.5
a type that can represent the size of the largest object in the allocation model.
Default T* pointer_traits<X:: pointer>:: rebind pointer_traits<X:: pointer>:: rebind pointer_traits<X:: pointer>:: rebind
make_unsigned<X:: difference_type>::type pointer_traits<X:: pointer>:: difference_type See Note A, below.
*q refers to the same object as *p pre: (*p).m is well-defined. equivalent to (*p).m 415
c ISO/IEC
N3376
Table 28 — Allocator requirements (continued) Expression
Return type
q->m
type of T::m
static_cast<X::pointer>(w) static_cast<X ::const_pointer>(z) a.allocate(n)
X::pointer
X::pointer
a.allocate(n, u)
X::pointer
a.deallocate(p,n)
(not used)
a.max_size()
X::size_type
a1 == a2
bool
a1 != a2 a == b
bool bool
a != b X a1(a);
bool
X a(b); X a1(move(a));
§ 17.6.3.5
X::const_pointer
Assertion/note pre-/post-condition pre: (*q).m is well-defined. equivalent to (*q).m static_cast<X::pointer>(w) == p static_cast<X ::const_pointer>(z) == q Memory is allocated for n objects of type T but objects are not constructed. allocate may raise an appropriate exception.179 [ Note: If n == 0, the return value is unspecified. — end note ] Same as a.allocate(n). The use of u is unspecified, but it is intended as an aid to locality. All n T objects in the area pointed to by p shall be destroyed prior to this call. n shall match the value passed to allocate to obtain this memory. Does not throw exceptions. [ Note:p shall not be singular. — end note ] the largest value that can meaningfully be passed to X::allocate() returns true only if storage allocated from each can be deallocated via the other. operator== shall be reflexive, symmetric, and transitive, and shall not exit via an exception. same as !(a1 == a2) same as a == Y::rebind::other(b) same as !(a == b) Shall not exit via an exception. post: a1 == a Shall not exit via an exception. post: Y(a) == b, a == X(b) Shall not exit via an exception. post: a1 equals the prior value of a.
Default
a.allocate(n)
numeric_limits<size_type>::max()
416
c ISO/IEC
N3376
Table 28 — Allocator requirements (continued) Expression
Return type
X a(move(b));
3
4
5
Assertion/note pre-/post-condition Shall not exit via an exception. post: a equals the prior value of X(b). Effect: Constructs an object of type C at c
a.construct(c, args)
(not used)
a.destroy(c) a.select_on_container_copy_construction() X::propagate_on_container_copy_assignment
(not used) X
Effect: Destroys the object at c Typically returns either a or X()
Identical to or derived from true_type or false_type
X::propagate_on_container_move_assignment
Identical to or derived from true_type or false_type
X::propagate_on_container_swap
Identical to or derived from true_type or false_type
true_type only if an allocator of type X should be copied when the client container is copy-assigned. true_type only if an allocator of type X should be moved when the client container is move-assigned. true_type only if an allocator of type X should be swapped when the client container is swapped.
Default
::new ((void*)c) C(forward< Args> (args)...) c->˜C() return a;
false_type
false_type
false_type
Note A: The member class template rebind in the table above is effectively a typedef template. [ Note: In general, if the name Allocator is bound to SomeAllocator, then Allocator::rebind::other is the same type as SomeAllocator, where SomeAllocator::value_type is T and SomeAllocator:: value_type is U. — end note ] If Allocator is a class template instantiation of the form SomeAllocator, where Args is zero or more type arguments, and Allocator does not supply a rebind member template, the standard allocator_traits template uses SomeAllocator in place of Allocator:: rebind::other by default. For allocator types that are not template instantiations of the above form, no default is provided. The X::pointer, X::const_pointer, X::void_pointer, and X::const_void_pointer types shall satisfy the requirements of NullablePointer (17.6.3.3). No constructor, comparison operator, copy operation, move operation, or swap operation on these types shall exit via an exception. X::pointer and X::const_pointer shall also satisfy the requirements for a random access iterator (24.2). An allocator may constrain the types on which it can be instantiated and the arguments for which its construct member may be called. If a type cannot be used with a particular allocator, the allocator class or the call to construct may fail to instantiate. [ Example: the following is an allocator class template supporting the minimal interface that satisfies the requirements of Table 28: template 179) It is intended that a.allocate be an efficient means of allocating a single object of type T, even when sizeof(T) is small. That is, there is no need for a container to maintain its own free list.
§ 17.6.3.5
417
c ISO/IEC
N3376
struct SimpleAllocator { typedef Tp value_type; SimpleAllocator(ctor args ); template SimpleAllocator(const SimpleAllocator& other); Tp *allocate(std::size_t n); void deallocate(Tp *p, std::size_t n); }; template bool operator==(const SimpleAllocator&, const SimpleAllocator&); template bool operator!=(const SimpleAllocator&, const SimpleAllocator&); 6
— end example ] If the alignment associated with a specific over-aligned type is not supported by an allocator, instantiation of the allocator for that type may fail. The allocator also may silently ignore the requested alignment. [ Note: Additionally, the member function allocate for that type may fail by throwing an object of type std::bad_alloc. — end note ]
17.6.4
Constraints on programs
17.6.4.1 1
2
[constraints.overview]
This section describes restrictions on C++ programs that use the facilities of the C++ standard library. The following subclauses specify constraints on the program’s use of namespaces (17.6.4.2.1), its use of various reserved names (17.6.4.3), its use of headers (17.6.4.4), its use of standard library classes as base classes (17.6.4.5), its definitions of replacement functions (17.6.4.6), and its installation of handler functions during execution (17.6.4.7). 17.6.4.2 Namespace use [namespace.constraints] 17.6.4.2.1
1
Overview
[constraints]
Namespace std
[namespace.std]
The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.180 The behavior of a C++ program is undefined if it declares — an explicit specialization of any member function of a standard library class template, or — an explicit specialization of any member function template of a standard library class or class template, or — an explicit or partial specialization of any member class template of a standard library class or class template.
3
A program may explicitly instantiate a template defined in the standard library only if the declaration depends on the name of a user-defined type and the instantiation meets the standard library requirements for the original template. A translation unit shall not declare namespace std to be an inline namespace (7.3.1). 180) Any library code that instantiates other library templates must be prepared to work adequately with any user-supplied specialization that meets the minimum requirements of the Standard.
§ 17.6.4.2.1
418
c ISO/IEC
17.6.4.2.2
N3376
Namespace posix
[namespace.posix]
1
The behavior of a program is undefined if it adds declarations or definitions to namespace posix or to a namespace within namespace posix unless otherwise specified. The namespace posix is reserved for use by ISO/IEC 9945 and other POSIX standards. 17.6.4.3 Reserved names [reserved.names]
1
The C++ standard library reserves the following kinds of names: — macros
C++
— global names — names with external linkage 2
If a program declares or defines a name in a context where it is reserved, other than as explicitly allowed by this Clause, its behavior is undefined. 17.6.4.3.1
1
2
1
Macro names
[macro.names]
A translation unit that includes a standard library header shall not #define or #undef names declared in any standard library header. A translation unit shall not #define or #undef names lexically identical to keywords, to the identifiers listed in Table 3, or to the attribute-tokens described in 7.6. 17.6.4.3.2 Global names [global.names] Certain sets of names and function signatures are always reserved to the implementation: — Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use. — Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace. 17.6.4.3.3
1
2
3
4
External linkage
[extern.names]
Each name declared as an object with external linkage in a header is reserved to the implementation to designate that library object with external linkage,181 both in namespace std and in the global namespace. Each global function signature declared with external linkage in a header is reserved to the implementation to designate that function signature with external linkage. 182 Each name from the Standard C library declared with external linkage is reserved to the implementation for use as a name with extern "C" linkage, both in namespace std and in the global namespace. Each function signature from the Standard C library declared with external linkage is reserved to the implementation for use as a function signature with both extern "C" and extern "C++" linkage, 183 or as a name of namespace scope in the global namespace. 17.6.4.3.4 Types [extern.types]
1
For each type T from the Standard C library,184 the types ::T and std::T are reserved to the implementation and, when defined, ::T shall be identical to std::T. 17.6.4.3.5 User-defined literal suffixes [usrlit.suffix]
1
Literal suffix identifiers that do not start with an underscore are reserved for future standardization. 17.6.4.4 Headers [alt.headers]
1
If a file with a name equivalent to the derived file name for one of the C++ standard library headers is not 181) The list of such reserved names includes errno, declared or defined in . 182) The list of such reserved function signatures with external linkage includes setjmp(jmp_buf), declared or defined in
, and va_end(va_list), declared or defined in . 183) The function signatures declared in <cuchar>, , and are always reserved, notwithstanding the restrictions imposed in subclause 4.5.1 of Amendment 1 to the C Standard for these headers. 184) These types are clock_t, div_t, FILE, fpos_t, lconv, ldiv_t, mbstate_t, ptrdiff_t, sig_atomic_t, size_t, time_t, tm, va_list, wctrans_t, wctype_t, and wint_t.
§ 17.6.4.4
419
c ISO/IEC
N3376
provided as part of the implementation, and a file with that name is placed in any of the standard places for a source file to be included (16.2), the behavior is undefined. 17.6.4.5 Derived classes [derived.classes] 1
Virtual member function signatures defined for a base class in the C++ standard library may be overridden in a derived class defined in the program (10.3). 17.6.4.6 Replacement functions [replacement.functions]
1
Clauses 18 through 30 and Annex D describe the behavior of numerous functions defined by the C++ standard library. Under some circumstances, however, certain of these function descriptions also apply to replacement functions defined in the program (17.3). A C++ program may provide the definition for any of eight dynamic memory allocation function signatures declared in header (3.7.4, 18.6): — operator new(std::size_t)
2
— operator new(std::size_t, const std::nothrow_t&) — operator new[](std::size_t) — operator new[](std::size_t, const std::nothrow_t&) — operator delete(void*) — operator delete(void*, const std::nothrow_t&) — operator delete[](void*) — operator delete[](void*, const std::nothrow_t&) 3
The program’s definitions are used instead of the default versions supplied by the implementation (18.6). Such replacement occurs prior to program startup (3.2, 3.6). The program’s definitions shall not be specified as inline. No diagnostic is required. 17.6.4.7
1
Handler functions
[handler.functions]
The C++ standard library provides default versions of the following handler functions (Clause 18): — unexpected_handler — terminate_handler
2
A C++ program may install different handler functions during execution, by supplying a pointer to a function defined in the program or the library as an argument to (respectively): — set_new_handler — set_unexpected — set_terminate See also: subclauses 18.6.2, Storage allocation errors, and 18.8, Exception handling.
3
A C++ program can get a pointer to the current handler function by calling the following functions: — get_new_handler — get_unexpected — get_terminate
4
Calling the set_* and get_* functions shall not incur a data race. A call to any of the set_* functions shall synchronize with subsequent calls to the same set_* function and to the corresponding get_* function. § 17.6.4.7
420
c ISO/IEC
17.6.4.8 1
2
N3376
Other functions
[res.on.functions]
In certain cases (replacement functions, handler functions, operations on types used to instantiate standard library template components), the C++ standard library depends on components supplied by a C++ program. If these components do not meet their requirements, the Standard places no requirements on the implementation. In particular, the effects are undefined in the following cases: — for replacement functions (18.6.1), if the installed replacement function does not implement the semantics of the applicable Required behavior: paragraph. — for handler functions (18.6.2.3, 18.8.3.1, D.11.1), if the installed handler function does not implement the semantics of the applicable Required behavior: paragraph — for types used as template arguments when instantiating a template component, if the operations on the type do not implement the semantics of the applicable Requirements subclause (17.6.3.5, 23.2, 24.2, 26.2). Operations on such types can report a failure by throwing an exception unless otherwise specified. — if any replacement function or handler function or destructor operation exits via an exception, unless specifically allowed in the applicable Required behavior: paragraph. — if an incomplete type (3.9) is used as a template argument when instantiating a template component, unless specifically allowed for that component. 17.6.4.9
1
Function arguments
[res.on.arguments]
Each of the following applies to all arguments to functions defined in the C++ standard library, unless explicitly stated otherwise. — If an argument to a function has an invalid value (such as a value outside the domain of the function or a pointer invalid for its intended use), the behavior is undefined. — If a function argument is described as being an array, the pointer actually passed to the function shall have a value such that all address computations and accesses to objects (that would be valid if the pointer did point to the first element of such an array) are in fact valid. — If a function argument binds to an rvalue reference parameter, the implementation may assume that this parameter is a unique reference to this argument. [ Note: If the parameter is a generic parameter of the form T&& and an lvalue of type A is bound, the argument binds to an lvalue reference (14.8.2.1) and thus is not covered by the previous sentence. — end note ] [ Note: If a program casts an lvalue to an xvalue while passing that lvalue to a library function (e.g. by calling the function with the argument move(x)), the program is effectively asking that function to treat that lvalue as a temporary. The implementation is free to optimize away aliasing checks which might be needed if the argument was an lvalue. — end note ] 17.6.4.10
1
2
Shared objects and the library
[res.on.objects]
The behavior of a program is undefined if calls to standard library functions from different threads may introduce a data race. The conditions under which this may occur are specified in 17.6.5.9. [ Note: Modifying an object of a standard library type that is shared between threads risks undefined behavior unless objects of that type are explicitly specified as being sharable without data races or the user supplies a locking mechanism. — end note ] [ Note: In particular, the program is required to ensure that completion of the constructor of any object of a class type defined in the standard library happens before any other member function invocation on that object and, unless otherwise specified, to ensure that completion of any member function invocation other
§ 17.6.4.10
421
c ISO/IEC
N3376
than destruction on such an object happens before destruction of that object. This applies even to objects such as mutexes intended for thread synchronization. — end note ] 17.6.4.11 Requires paragraph [res.on.required] 1
Violation of the preconditions specified in a function’s Requires: paragraph results in undefined behavior unless the function’s Throws: paragraph specifies throwing an exception when the precondition is violated.
17.6.5 17.6.5.1 1 2
1
2
3
1 2
1
2
3
4
Conforming implementations Overview
[conforming] [conforming.overview]
This section describes the constraints upon, and latitude of, implementations of the C++ standard library. An implementation’s use of headers is discussed in 17.6.5.2, its use of macros in 17.6.5.3, global functions in 17.6.5.4, member functions in 17.6.5.5, data race avoidance in 17.6.5.9, access specifiers in 17.6.5.10, class derivation in 17.6.5.11, and exceptions in 17.6.5.12. 17.6.5.2 Headers [res.on.headers] A C++ header may include other C++ headers. A C++ header shall provide the declarations and definitions that appear in its synopsis. A C++ header shown in its synopsis as including other C++ headers shall provide the declarations and definitions that appear in the synopses of those other headers. Certain types and macros are defined in more than one header. Every such entity shall be defined such that any header that defines it may be included after any other header that also defines it (3.2). The C standard headers (D.5) shall include only their corresponding C++ standard header, as described in 17.6.1.2. 17.6.5.3 Restrictions on macro definitions [res.on.macro.definitions] The names and global function signatures described in 17.6.1.1 are reserved to the implementation. All object-like macros defined by the C standard library and described in this Clause as expanding to integral constant expressions are also suitable for use in #if preprocessing directives, unless explicitly stated otherwise. 17.6.5.4 Global and non-member functions [global.functions] It is unspecified whether any global or non-member functions in the C++ standard library are defined as inline (7.1.2). A call to a global or non-member function signature described in Clauses 18 through 30 and Annex D shall behave as if the implementation declared no additional global or non-member function signatures.185 An implementation shall not declare a global or non-member function signature with additional default arguments. Unless otherwise specified, global and non-member functions in the standard library shall not use functions from another namespace which are found through argument-dependent name lookup (3.4.2). [ Note: The phrase “unless otherwise specified” is intended to allow argument-dependent lookup in cases like that of ostream_iterators: Effects: *out_stream , with the following changes: The macro NULL is an implementation-defined C++ null pointer constant in this International Standard (4.10).193 The macro offsetof(type, member-designator) accepts a restricted set of type arguments in this International Standard. If type is not a standard-layout class (Clause 9), the results are undefined.194 The expression offsetof(type, member-designator) is never type-dependent (14.6.2.2) and it is value-dependent (14.6.2.3) if and only if type is dependent. The result of applying the offsetof macro to a field that is a static data member or a function member is undefined. No operation invoked by the offsetof macro shall throw an exception and noexcept(offsetof(type, member-designator)) shall be true. The type ptrdiff_t is an implementation-defined signed integer type that can hold the difference of two subscripts in an array object, as described in 5.7. The type size_t is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object. [ Note: It is recommended that implementations choose types for ptrdiff_t and size_t whose integer conversion ranks (4.13) are no greater than that of signed long int unless a larger size is necessary to contain all the possible values. — end note ] The type max_align_t is a POD type whose alignment requirement is at least as great as that of every scalar type, and whose alignment requirement is supported in every context. nullptr_t is defined as follows: namespace std { typedef decltype(nullptr) nullptr_t; }
The type for which nullptr_t is a synonym has the characteristics described in 3.9.1 and 4.10. [ Note: Although nullptr’s address cannot be taken, the address of another nullptr_t object that is an lvalue can be taken. — end note ] See also: Alignment (3.11), Sizeof (5.3.3), Additive operators (5.7), Free store (12.5), and ISO C 7.1.6.
18.3
Implementation properties
18.3.1 1
18.3.2.1
2
3
4
In general
[support.limits.general]
The headers (18.3.2), , and (18.3.3) supply characteristics of implementationdependent arithmetic types (3.9.1).
18.3.2 1
[support.limits]
Numeric limits
[limits]
Class template numeric_limits
[limits.numeric] C++
The numeric_limits class template provides a program with information about various properties of the implementation’s representation of the arithmetic types. Specializations shall be provided for each arithmetic type, both floating point and integer, including bool. The member is_specialized shall be true for all such specializations of numeric_limits. For all members declared static constexpr in the numeric_limits template, specializations shall define these values in such a way that they are usable as constant expressions. Non-arithmetic standard types, such as complex (26.4.2), shall not have specializations. 18.3.2.2 Header synopsis [limits.syn] namespace std { template class numeric_limits; enum float_round_style; enum float_denorm_style; 193) Possible definitions include 0 and 0L, but not (void*)0. 194) Note that offsetof is required to work as specified even if unary operator& is overloaded for any of the types involved.
§ 18.3.2.2
427
c ISO/IEC
N3376
template class numeric_limits; template template template template template template
class class class class class class
numeric_limits; numeric_limits<signed char>; numeric_limits; numeric_limits; numeric_limits; numeric_limits<wchar_t>;
template template template template template template template template
class class class class class class class class
numeric_limits<short>; numeric_limits; numeric_limits; numeric_limits; numeric_limits; numeric_limits; numeric_limits; numeric_limits;
template class numeric_limits; template class numeric_limits<double>; template class numeric_limits; }
18.3.2.3
Class template numeric_limits
[numeric.limits]
namespace std { template class numeric_limits { public: static constexpr bool is_specialized = false; static constexpr T min() noexcept { return T(); } static constexpr T max() noexcept { return T(); } static constexpr T lowest() noexcept { return T(); } static static static static static static static static static
constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr
int digits = 0; int digits10 = 0; int max_digits10 = 0; bool is_signed = false; bool is_integer = false; bool is_exact = false; int radix = 0; T epsilon() noexcept { return T(); } T round_error() noexcept { return T(); }
static static static static
constexpr constexpr constexpr constexpr
int int int int
static static static static static static static static
constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr
bool has_infinity = false; bool has_quiet_NaN = false; bool has_signaling_NaN = false; float_denorm_style has_denorm = denorm_absent; bool has_denorm_loss = false; T infinity() noexcept { return T(); } T quiet_NaN() noexcept { return T(); } T signaling_NaN() noexcept { return T(); }
§ 18.3.2.3
min_exponent = min_exponent10 max_exponent = max_exponent10
0; = 0; 0; = 0;
428
c ISO/IEC
N3376
static constexpr T denorm_min() noexcept { return T(); } static constexpr bool is_iec559 = false; static constexpr bool is_bounded = false; static constexpr bool is_modulo = false; static constexpr bool traps = false; static constexpr bool tinyness_before = false; static constexpr float_round_style round_style = round_toward_zero; }; template class numeric_limits; template class numeric_limits; template class numeric_limits; } 1 2
The default numeric_limits template shall have all members, but with 0 or false values. The value of each member of a specialization of numeric_limits on a cv-qualified type cv T shall be equal to the value of the corresponding member of the specialization on the unqualified type T. 18.3.2.4 numeric_limits members [numeric.limits.members] static constexpr T min() noexcept;
1
Minimum finite value.195
2
For floating types with denormalization, returns the minimum positive normalized value.
3
Meaningful for all specializations in which is_bounded != false, or is_bounded == false && is_signed == false. static constexpr T max() noexcept;
4
Maximum finite value.196
5
Meaningful for all specializations in which is_bounded != false. static constexpr T lowest() noexcept;
6
A finite value x such that there is no other finite value y where y < x.197
7
Meaningful for all specializations in which is_bounded != false. static constexpr int digits;
8
Number of radix digits that can be represented without change.
9
For integer types, the number of non-sign bits in the representation.
10
For floating point types, the number of radix digits in the mantissa.198 static constexpr int digits10; 195) Equivalent to CHAR_MIN, SHRT_MIN, FLT_MIN, DBL_MIN, etc. 196) Equivalent to CHAR_MAX, SHRT_MAX, FLT_MAX, DBL_MAX, etc. 197) lowest() is necessary because not all floating-point representations have a smallest (most negative) value that is the
negative of the largest (most positive) finite value. 198) Equivalent to FLT_MANT_DIG, DBL_MANT_DIG, LDBL_MANT_DIG.
§ 18.3.2.4
429
c ISO/IEC
N3376
11
Number of base 10 digits that can be represented without change.199
12
Meaningful for all specializations in which is_bounded != false. static constexpr int max_digits10;
13
Number of base 10 digits required to ensure that values which differ are always differentiated.
14
Meaningful for all floating point types. static constexpr bool is_signed;
15
True if the type is signed.
16
Meaningful for all specializations. static constexpr bool is_integer;
17
True if the type is integer.
18
Meaningful for all specializations. static constexpr bool is_exact;
19
True if the type uses an exact representation. All integer types are exact, but not all exact types are integer. For example, rational and fixed-exponent representations are exact but not integer.
20
Meaningful for all specializations. static constexpr int radix;
21
For floating types, specifies the base or radix of the exponent representation (often 2).200
22
For integer types, specifies the base of the representation.201
23
Meaningful for all specializations. static constexpr T epsilon() noexcept;
24
Machine epsilon: the difference between 1 and the least value greater than 1 that is representable.202
25
Meaningful for all floating point types. static constexpr T round_error() noexcept;
Measure of the maximum rounding error.203
26
static constexpr int
min_exponent;
Equivalent to FLT_DIG, DBL_DIG, LDBL_DIG. Equivalent to FLT_RADIX. Distinguishes types with bases other than 2 (e.g. BCD). Equivalent to FLT_EPSILON, DBL_EPSILON, LDBL_EPSILON. Rounding error is described in ISO/IEC 10967-1 Language independent arithmetic - Part 1 Section 5.2.8 and Annex A Rationale Section A.5.2.8 - Rounding constants. 199) 200) 201) 202) 203)
§ 18.3.2.4
430
c ISO/IEC
N3376
27
Minimum negative integer such that radix raised to the power of one less than that integer is a normalized floating point number.204
28
Meaningful for all floating point types. static constexpr int
min_exponent10;
29
Minimum negative integer such that 10 raised to that power is in the range of normalized floating point numbers.205
30
Meaningful for all floating point types. static constexpr int
max_exponent;
31
Maximum positive integer such that radix raised to the power one less than that integer is a representable finite floating point number.206
32
Meaningful for all floating point types. static constexpr int
max_exponent10;
33
Maximum positive integer such that 10 raised to that power is in the range of representable finite floating point numbers.207
34
Meaningful for all floating point types. static constexpr bool has_infinity;
35
True if the type has a representation for positive infinity.
36
Meaningful for all floating point types.
37
Shall be true for all specializations in which is_iec559 != false. static constexpr bool has_quiet_NaN;
38
True if the type has a representation for a quiet (non-signaling) “Not a Number.”208
39
Meaningful for all floating point types.
40
Shall be true for all specializations in which is_iec559 != false. static constexpr bool has_signaling_NaN;
41
True if the type has a representation for a signaling “Not a Number.”209
42
Meaningful for all floating point types.
43
Shall be true for all specializations in which is_iec559 != false. 204) 205) 206) 207) 208) 209)
Equivalent to FLT_MIN_EXP, DBL_MIN_EXP, LDBL_MIN_EXP. Equivalent to FLT_MIN_10_EXP, DBL_MIN_10_EXP, LDBL_MIN_10_EXP. Equivalent to FLT_MAX_EXP, DBL_MAX_EXP, LDBL_MAX_EXP. Equivalent to FLT_MAX_10_EXP, DBL_MAX_10_EXP, LDBL_MAX_10_EXP. Required by LIA-1. Required by LIA-1.
§ 18.3.2.4
431
c ISO/IEC
N3376
static constexpr float_denorm_style has_denorm; 44
denorm_present if the type allows denormalized values (variable number of exponent bits)210 , denorm_absent if the type does not allow denormalized values, and denorm_indeterminate if it is indeterminate at compile time whether the type allows denormalized values.
45
Meaningful for all floating point types. static constexpr bool has_denorm_loss;
True if loss of accuracy is detected as a denormalization loss, rather than as an inexact result.211
46
static constexpr T infinity() noexcept; 47
Representation of positive infinity, if available.212
48
Meaningful for all specializations for which has_infinity != false. Required in specializations for which is_iec559 != false. static constexpr T quiet_NaN() noexcept;
49
Representation of a quiet “Not a Number,” if available.213
50
Meaningful for all specializations for which has_quiet_NaN != false. Required in specializations for which is_iec559 != false. static constexpr T signaling_NaN() noexcept;
51
Representation of a signaling “Not a Number,” if available.214
52
Meaningful for all specializations for which has_signaling_NaN != false. Required in specializations for which is_iec559 != false. static constexpr T denorm_min() noexcept;
53
Minimum positive denormalized value.215
54
Meaningful for all floating point types.
55
In specializations for which has_denorm == false, returns the minimum positive normalized value. static constexpr bool is_iec559;
56
True if and only if the type adheres to IEC 559 standard.216
57
Meaningful for all floating point types. 210) 211) 212) 213) 214) 215) 216)
Required by LIA-1. See IEC 559. Required by LIA-1. Required by LIA-1. Required by LIA-1. Required by LIA-1. International Electrotechnical Commission standard 559 is the same as IEEE 754.
§ 18.3.2.4
432
c ISO/IEC
N3376
static constexpr bool is_bounded; 58
True if the set of values representable by the type is finite.217 [ Note: All fundamental types (3.9.1) are bounded. This member would be false for arbitrary precision types. — end note ]
59
Meaningful for all specializations. static constexpr bool is_modulo;
60
True if the type is modulo.218 A type is modulo if, for any operation involving +, -, or * on values of that type whose result would fall outside the range [min(),max()], the value returned differs from the true value by an integer multiple of max() - min() + 1.
61
On most machines, this is false for floating types, true for unsigned integers, and true for signed integers.
62
Meaningful for all specializations. static constexpr bool traps;
63
true if, at program startup, there exists a value of the type that would cause an arithmetic operation using that value to trap.219
64
Meaningful for all specializations. static constexpr bool tinyness_before;
65
true if tinyness is detected before rounding.220
66
Meaningful for all floating point types. static constexpr float_round_style round_style;
67
The rounding style for the type.221
68
Meaningful for all floating point types. Specializations for integer types shall return round_toward_zero. 18.3.2.5
Type float_round_style
namespace std { enum float_round_style { round_indeterminate round_toward_zero round_to_nearest round_toward_infinity round_toward_neg_infinity }; } 217) 218) 219) 220) 221)
[round.style]
= -1, = 0, = 1, = 2, = 3
Required by LIA-1. Required by LIA-1. Required by LIA-1. Refer to IEC 559. Required by LIA-1. Equivalent to FLT_ROUNDS. Required by LIA-1.
§ 18.3.2.5
433
c ISO/IEC
1
N3376
The rounding mode for floating point arithmetic is characterized by the values: — round_indeterminate if the rounding style is indeterminable — round_toward_zero if the rounding style is toward zero — round_to_nearest if the rounding style is to the nearest representable value — round_toward_infinity if the rounding style is toward infinity — round_toward_neg_infinity if the rounding style is toward negative infinity 18.3.2.6
Type float_denorm_style
[denorm.style]
namespace std { enum float_denorm_style { denorm_indeterminate = -1, denorm_absent = 0, denorm_present = 1 }; } 1
The presence or absence of denormalization (variable number of exponent bits) is characterized by the values: — denorm_indeterminate if it cannot be determined whether or not the type allows denormalized values — denorm_absent if the type does not allow denormalized values — denorm_present if the type does allow denormalized values 18.3.2.7
1
2
numeric_limits specializations
[numeric.special]
All members shall be provided for all specializations. However, many values are only required to be meaningful under certain conditions (for example, epsilon() is only meaningful if is_integer is false). Any value that is not “meaningful” shall be set to 0 or false. [ Example: namespace std { template class numeric_limits { public: static constexpr bool is_specialized = true; inline static constexpr float min() noexcept { return 1.17549435E-38F; } inline static constexpr float max() noexcept { return 3.40282347E+38F; } inline static constexpr float lowest() noexcept { return -3.40282347E+38F; } static constexpr int digits = 24; static constexpr int digits10 = 6; static constexpr int max_digits10 =
9;
static constexpr bool is_signed = true; static constexpr bool is_integer = false; static constexpr bool is_exact = false; static constexpr int radix = 2; inline static constexpr float epsilon() noexcept { return 1.19209290E-07F; } inline static constexpr float round_error() noexcept { return 0.5F; } static constexpr int min_exponent = -125; static constexpr int min_exponent10 = - 37;
§ 18.3.2.7
434
c ISO/IEC
N3376
static constexpr int max_exponent = +128; static constexpr int max_exponent10 = + 38; static static static static static
constexpr constexpr constexpr constexpr constexpr
inline inline inline inline
static static static static
static static static static static
constexpr constexpr constexpr constexpr constexpr
bool has_infinity bool has_quiet_NaN bool has_signaling_NaN float_denorm_style has_denorm bool has_denorm_loss
constexpr constexpr constexpr constexpr bool bool bool bool bool
float float float float
infinity() quiet_NaN() signaling_NaN() denorm_min()
= = = = =
true; true; true; denorm_absent; false;
noexcept noexcept noexcept noexcept
{ { { {
return return return return
value ; value ; value ; min();
} } } }
is_iec559 = true; is_bounded = true; is_modulo = false; traps = true; tinyness_before = true;
static constexpr float_round_style round_style = round_to_nearest; }; } 3
— end example ] The specialization for bool shall be provided as follows: namespace std { template class numeric_limits { public: static constexpr bool is_specialized = true; static constexpr bool min() noexcept { return false; } static constexpr bool max() noexcept { return true; } static constexpr bool lowest() noexcept { return false; } static constexpr int static constexpr int static constexpr int
digits = 1; digits10 = 0; max_digits10 = 0;
static static static static static static
constexpr constexpr constexpr constexpr constexpr constexpr
bool bool bool int bool bool
is_signed = false; is_integer = true; is_exact = true; radix = 2; epsilon() noexcept { return 0; } round_error() noexcept { return 0; }
static static static static
constexpr constexpr constexpr constexpr
int int int int
min_exponent = min_exponent10 max_exponent = max_exponent10
static static static static static
constexpr constexpr constexpr constexpr constexpr
bool has_infinity = false; bool has_quiet_NaN = false; bool has_signaling_NaN = false; float_denorm_style has_denorm = denorm_absent; bool has_denorm_loss = false;
§ 18.3.2.7
0; = 0; 0; = 0;
435
c ISO/IEC
N3376
static static static static
constexpr constexpr constexpr constexpr
bool bool bool bool
infinity() noexcept { return 0; } quiet_NaN() noexcept { return 0; } signaling_NaN() noexcept { return 0; } denorm_min() noexcept { return 0; }
static constexpr bool is_iec559 = false; static constexpr bool is_bounded = true; static constexpr bool is_modulo = false; static constexpr bool traps = false; static constexpr bool tinyness_before = false; static constexpr float_round_style round_style = round_toward_zero; }; }
18.3.3 1
C library
[c.limits]
Table 31 describes the header . Table 31 — Header synopsis Type Values: CHAR_BIT CHAR_MAX CHAR_MIN INT_MIN
2
3
Name(s) INT_MAX LLONG_MAX LLONG_MIN
LONG_MAX LONG_MIN MB_LEN_MAX
SCHAR_MIN SCHAR_MAX SHRT_MAX
SHRT_MIN UCHAR_MAX UINT_MAX
ULLONG_MAX ULONG_MAX USHRT_MAX
The contents are the same as the Standard C library header . [ Note: The types of the constants defined by macros in are not required to match the types to which the macros refer. — end note ] Table 32 describes the header . Table 32 — Header synopsis Type Values: DBL_DIG DBL_EPSILON DBL_MANT_DIG DBL_MAX DBL_MAX_10_EXP DBL_MAX_EXP DBL_MIN DBL_MIN_10_EXP
4
Name(s) DBL_MIN_EXP DECIMAL_DIG FLT_DIG FLT_EPSILON FLT_EVAL_METHOD FLT_MANT_DIG FLT_MAX FLT_MAX_10_EXP
FLT_MAX_EXP FLT_MIN FLT_MIN_10_EXP FLT_MIN_EXP FLT_RADIX FLT_ROUNDS LDBL_DIG LDBL_EPSILON
LDBL_MANT_DIG LDBL_MAX_10_EXP LDBL_MAX_EXP LDBL_MAX LDBL_MIN LDBL_MIN_10_EXP LDBL_MIN_EXP
The contents are the same as the Standard C library header . See also: ISO C 7.1.5, 5.2.4.2.2, 5.2.4.2.1.
18.4 18.4.1 § 18.4.1
Integer types Header synopsis
[cstdint] [cstdint.syn] 436
c ISO/IEC
N3376
namespace typedef typedef typedef typedef
std { signed signed signed signed
integer integer integer integer
type type type type
int8_t; int16_t; int32_t; int64_t;
typedef typedef typedef typedef
signed signed signed signed
integer integer integer integer
type type type type
int_fast8_t; int_fast16_t; int_fast32_t; int_fast64_t;
typedef typedef typedef typedef
signed signed signed signed
integer integer integer integer
type type type type
int_least8_t; int_least16_t; int_least32_t; int_least64_t;
// // // //
optional optional optional optional
typedef signed integer type intmax_t; typedef signed integer type intptr_t;
// optional
typedef typedef typedef typedef
unsigned unsigned unsigned unsigned
integer integer integer integer
type type type type
uint8_t; uint16_t; uint32_t; uint64_t;
// // // //
typedef typedef typedef typedef
unsigned unsigned unsigned unsigned
integer integer integer integer
type type type type
uint_fast8_t; uint_fast16_t; uint_fast32_t; uint_fast64_t;
typedef typedef typedef typedef
unsigned unsigned unsigned unsigned
integer integer integer integer
type type type type
uint_least8_t; uint_least16_t; uint_least32_t; uint_least64_t;
typedef unsigned integer type uintmax_t; typedef unsigned integer type uintptr_t; } // namespace std 1
optional optional optional optional
// optional
The header also defines numerous macros of the form: INT_[FAST LEAST]{8 16 32 64}_MIN [U]INT_[FAST LEAST]{8 16 32 64}_MAX INT{MAX PTR}_MIN [U]INT{MAX PTR}_MAX {PTRDIFF SIG_ATOMIC WCHAR WINT}{_MAX _MIN} SIZE_MAX
plus function macros of the form: [U]INT{8 16 32 64 MAX}_C 2
The header defines all functions, types, and macros the same as 7.18 in the C standard. [ Note: The macros defined by are provided unconditionally. In particular, the symbols __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS (mentioned in footnotes 219, 220, and 222 in the C standard) play no role in
§ 18.5
437
c ISO/IEC
N3376
Table 33 — Header synopsis Type Macros: Functions:
EXIT_FAILURE _Exit at_quick_exit
Name(s) EXIT_SUCCESS abort exit
atexit quick_exit
C++. — end note ]
18.5 1 2
Start and termination
[support.start.term]
Table 33 describes some of the contents of the header . The contents are the same as the Standard C library header <stdlib.h>, with the following changes: [[noreturn]] void _Exit(int status) noexcept;
3
The function _Exit(int status) has additional behavior in this International Standard: — The program is terminated without executing destructors for objects of automatic, thread, or static storage duration and without calling functions passed to atexit() (3.6.3). [[noreturn]] void abort(void) noexcept;
4
The function abort() has additional behavior in this International Standard: — The program is terminated without executing destructors for objects of automatic, thread, or static storage duration and without calling functions passed to atexit() (3.6.3). extern "C" int atexit(void (*f)(void)) noexcept; extern "C++" int atexit(void (*f)(void)) noexcept;
5
Effects: The atexit() functions register the function pointed to by f to be called without arguments at normal program termination. It is unspecified whether a call to atexit() that does not happen before (1.10) a call to exit() will succeed. [ Note: The atexit() functions do not introduce a data race (17.6.5.9). — end note ]
6
Implementation limits: The implementation shall support the registration of at least 32 functions.
7
Returns: The atexit() function returns zero if the registration succeeds, non-zero if it fails. [[noreturn]] void exit(int status)
8
The function exit() has additional behavior in this International Standard: — First, objects with thread storage duration and associated with the current thread are destroyed. Next, objects with static storage duration are destroyed and functions registered by calling atexit are called.222 See 3.6.3 for the order of destructions and calls. (Automatic objects are not destroyed as a result of calling exit().)223 If control leaves a registered function called by exit because the function does not provide a handler for a thrown exception, std::terminate() shall be called (15.5.1). 222) A function is called for every time it is registered. 223) Objects with automatic storage duration are all destroyed in a program whose function main() contains no automatic
objects and executes the call to exit(). Control can be transferred directly to such a main() by throwing an exception that is caught in main().
§ 18.5
438
c ISO/IEC
N3376
— Next, all open C streams (as mediated by the function signatures declared in ) with unwritten buffered data are flushed, all open C streams are closed, and all files created by calling tmpfile() are removed. — Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.224 extern "C" int at_quick_exit(void (*f)(void)) noexcept; extern "C++" int at_quick_exit(void (*f)(void)) noexcept; 9
Effects: The at_quick_exit() functions register the function pointed to by f to be called without arguments when quick_exit is called. It is unspecified whether a call to at_quick_exit() that does not happen before (1.10) all calls to quick_exit will succeed. [ Note: The at_quick_exit() functions do not introduce a data race (17.6.5.9). — end note ] [ Note: The order of registration may be indeterminate if at_quick_exit was called from more than one thread. — end note ] [ Note: The at_quick_exit registrations are distinct from the atexit registrations, and applications may need to call both registration functions with the same argument. — end note ]
10
Implementation limits: The implementation shall support the registration of at least 32 functions.
11
Returns: Zero if the registration succeeds, non-zero if it fails. [[noreturn]] void quick_exit(int status) noexcept;
12
Effects: Functions registered by calls to at_quick_exit are called in the reverse order of their registration, except that a function shall be called after any previously registered functions that had already been called at the time it was registered. Objects shall not be destroyed as a result of calling quick_exit. If control leaves a registered function called by quick_exit because the function does not provide a handler for a thrown exception, std::terminate() shall be called. [ Note: at_quick_exit may call a registered function from a different thread than the one that registered it, so registered functions should not rely on the identity of objects with thread storage duration. — end note ] After calling registered functions, quick_exit shall call _Exit(status). [ Note: The standard file buffers are not flushed. See: ISO C 7.20.4.4. — end note ] See also: 3.6, 3.6.3, ISO C 7.10.4.
18.6 1
Dynamic memory management
[support.dynamic]
The header defines several functions that manage the allocation of dynamic storage in a program. It also defines components for reporting storage management errors. Header synopsis namespace std { class bad_alloc; class bad_array_new_length; struct nothrow_t {}; extern const nothrow_t nothrow; typedef void (*new_handler)(); new_handler get_new_handler() noexcept; new_handler set_new_handler(new_handler new_p) noexcept; } 224) The macros EXIT_FAILURE and EXIT_SUCCESS are defined in .
§ 18.6
439
c ISO/IEC
N3376
void* void* void void void* void* void void
operator operator operator operator operator operator operator operator
new(std::size_t size); new(std::size_t size, const std::nothrow_t&) noexcept; delete(void* ptr) noexcept; delete(void* ptr, const std::nothrow_t&) noexcept; new[](std::size_t size); new[](std::size_t size, const std::nothrow_t&) noexcept; delete[](void* ptr) noexcept; delete[](void* ptr, const std::nothrow_t&) noexcept;
void* void* void void
operator operator operator operator
new (std::size_t size, void* ptr) noexcept; new[](std::size_t size, void* ptr) noexcept; delete (void* ptr, void*) noexcept; delete[](void* ptr, void*) noexcept;
See also: 1.7, 3.7.4, 5.3.4, 5.3.5, 12.5, 20.6.
18.6.1 1
Storage allocation and deallocation
[new.delete]
Except where otherwise specified, the provisions of (3.7.4) apply to the library versions of operator new and operator delete. 18.6.1.1 Single-object forms [new.delete.single] void* operator new(std::size_t size);
1
Effects: The allocation function (3.7.4.1) called by a new-expression (5.3.4) to allocate size bytes of storage suitably aligned to represent any object of that size.
2
Replaceable: a C++ program may define a function with this function signature that displaces the default version defined by the C++ standard library.
3
Required behavior: Return a non-null pointer to suitably aligned storage (3.7.4), or else throw a bad_alloc exception. This requirement is binding on a replacement version of this function.
4
Default behavior: — Executes a loop: Within the loop, the function first attempts to allocate the requested storage. Whether the attempt involves a call to the Standard C library function malloc is unspecified. — Returns a pointer to the allocated storage if the attempt is successful. Otherwise, if the current new_handler (18.6.2.5) is a null pointer value, throws bad_alloc. — Otherwise, the function calls the current new_handler function (18.6.2.3). If the called function returns, the loop repeats. — The loop terminates when an attempt to allocate the requested storage is successful or when a called new_handler function does not return. void* operator new(std::size_t size, const std::nothrow_t&) noexcept;
5
Effects: Same as above, except that it is called by a placement version of a new-expression when a C++ program prefers a null pointer result as an error indication, instead of a bad_alloc exception.
6
Replaceable: a C++ program may define a function with this function signature that displaces the default version defined by the C++ standard library.
7
Required behavior: Return a non-null pointer to suitably aligned storage (3.7.4), or else return a null pointer. This nothrow version of operator new returns a pointer obtained as if acquired from the (possibly replaced) ordinary version. This requirement is binding on a replacement version of this function. § 18.6.1.1
440
c ISO/IEC
N3376
8
Default behavior: Calls operator new(size). If the call returns normally, returns the result of that call. Otherwise, returns a null pointer.
9
[ Example: T* p1 = new T; T* p2 = new(nothrow) T;
// throws bad_alloc if it fails // returns 0 if it fails
— end example ] void operator delete(void* ptr) noexcept; 10
Effects: The deallocation function (3.7.4.2) called by a delete-expression to render the value of ptr invalid.
11
Replaceable: a C++ program may define a function with this function signature that displaces the default version defined by the C++ standard library.
12
Requires: ptr shall be a null pointer or its value shall be a value returned by an earlier call to the (possibly replaced) operator new(std::size_t) or operator new(std::size_t,const std::nothrow_t&) which has not been invalidated by an intervening call to operator delete(void*).
13
Requires: If an implementation has strict pointer safety (3.7.4.3) then ptr shall be a safely-derived pointer.
14
Default behavior: If ptr is null, does nothing. Otherwise, reclaims the storage allocated by the earlier call to operator new.
15
Remarks: It is unspecified under what conditions part or all of such reclaimed storage will be allocated by subsequent calls to operator new or any of calloc, malloc, or realloc, declared in . void operator delete(void* ptr, const std::nothrow_t&) noexcept;
16
Effects: The deallocation function (3.7.4.2) called by the implementation to render the value of ptr invalid when the constructor invoked from a nothrow placement version of the new-expression throws an exception.
17
Replaceable: a C++ program may define a function with this function signature that displaces the default version defined by the C++ standard library.
18
Requires: If an implementation has strict pointer safety (3.7.4.3) then ptr shall be a safely-derived pointer.
19
Default behavior: calls operator delete(ptr). 18.6.1.2
Array forms
[new.delete.array]
void* operator new[](std::size_t size); 1
Effects: The allocation function (3.7.4.1) called by the array form of a new-expression (5.3.4) to allocate size bytes of storage suitably aligned to represent any array object of that size or smaller.225
2
Replaceable: a C++ program can define a function with this function signature that displaces the default version defined by the C++ standard library. 225) It is not the direct responsibility of operator new[](std::size_t) or operator delete[](void*) to note the repetition count or element size of the array. Those operations are performed elsewhere in the array new and delete expressions. The array new expression, may, however, increase the size argument to operator new[](std::size_t) to obtain space to store supplemental information.
§ 18.6.1.2
441
c ISO/IEC
N3376
3
Required behavior: Same as for operator new(std::size_t). This requirement is binding on a replacement version of this function.
4
Default behavior: Returns operator new(size). void* operator new[](std::size_t size, const std::nothrow_t&) noexcept;
5
Effects: Same as above, except that it is called by a placement version of a new-expression when a C++ program prefers a null pointer result as an error indication, instead of a bad_alloc exception.
6
Replaceable: a C++ program can define a function with this function signature that displaces the default version defined by the C++ standard library.
7
Required behavior: Return a non-null pointer to suitably aligned storage (3.7.4), or return a null pointer. This requirement is binding on a replacement version of this function.
8
Default behavior: Calls operator new[](size). If the call returns normally, returns the result of that call. Otherwise, returns a null pointer. void operator delete[](void* ptr) noexcept;
9
Effects: The deallocation function (3.7.4.2) called by the array form of a delete-expression to render the value of ptr invalid.
10
Replaceable: a C++ program can define a function with this function signature that displaces the default version defined by the C++ standard library.
11
Requires: ptr shall be a null pointer or its value shall be the value returned by an earlier call to operator new[](std::size_t) or operator new[](std::size_t,const std::nothrow_t&) which has not been invalidated by an intervening call to operator delete[](void*).
12
Requires: If an implementation has strict pointer safety (3.7.4.3) then ptr shall be a safely-derived pointer.
13
Default behavior: Calls operator delete(ptr). void operator delete[](void* ptr, const std::nothrow_t&) noexcept;
14
Effects: The deallocation function (3.7.4.2) called by the implementation to render the value of ptr invalid when the constructor invoked from a nothrow placement version of the array new-expression throws an exception.
15
Replaceable: a C++ program may define a function with this function signature that displaces the default version defined by the C++ standard library.
16
Requires: If an implementation has strict pointer safety (3.7.4.3) then ptr shall be a safely-derived pointer.
17
Default behavior: calls operator delete[](ptr). 18.6.1.3
1
Placement forms
[new.delete.placement]
These functions are reserved, a C++ program may not define functions that displace the versions in the Standard C++ library (17.6.4). The provisions of (3.7.4) do not apply to these reserved placement forms of operator new and operator delete. void* operator new(std::size_t size, void* ptr) noexcept;
§ 18.6.1.3
442
c ISO/IEC
N3376
2
Returns: ptr.
3
Remarks: Intentionally performs no other action.
4
[ Example: This can be useful for constructing an object at a known address: void* place = operator new(sizeof(Something)); Something* p = new (place) Something();
— end example ] void* operator new[](std::size_t size, void* ptr) noexcept; 5
Returns: ptr.
6
Remarks: Intentionally performs no other action. void operator delete(void* ptr, void*) noexcept;
7
Effects: Intentionally performs no action.
8
Requires: If an implementation has strict pointer safety (3.7.4.3) then ptr shall be a safely-derived pointer.
9
Remarks: Default function called when any part of the initialization in a placement new expression that invokes the library’s non-array placement operator new terminates by throwing an exception (5.3.4). void operator delete[](void* ptr, void*) noexcept;
10
Effects: Intentionally performs no action.
11
Requires: If an implementation has strict pointer safety (3.7.4.3) then ptr shall be a safely-derived pointer.
12
Remarks: Default function called when any part of the initialization in a placement new expression that invokes the library’s array placement operator new terminates by throwing an exception (5.3.4). 18.6.1.4
1
Data races
[new.delete.dataraces]
For purposes of determining the existence of data races, the library versions of operator new, user replacement versions of global operator new, and the C standard library functions calloc and malloc shall behave as though they accessed and modified only the storage referenced by the return value. The library versions of operator delete, user replacement versions of operator delete, and the C standard library function free shall behave as though they accessed and modified only the storage referenced by their first argument. The C standard library function realloc shall behave as though it accessed and modified only the storage referenced by its first argument and by its return value. Calls to these functions that allocate or deallocate a particular unit of storage shall occur in a single total order, and each such deallocation call shall happen before the next allocation (if any) in this order.
18.6.2 18.6.2.1
Storage allocation errors Class bad_alloc
[alloc.errors] [bad.alloc]
namespace std { class bad_alloc : public exception { public: bad_alloc() noexcept; bad_alloc(const bad_alloc&) noexcept; bad_alloc& operator=(const bad_alloc&) noexcept;
§ 18.6.2.1
443
c ISO/IEC
N3376
virtual const char* what() const noexcept; }; } 1
The class bad_alloc defines the type of objects thrown as exceptions by the implementation to report a failure to allocate storage. bad_alloc() noexcept;
2
Effects: Constructs an object of class bad_alloc.
3
Remarks: The result of calling what() on the newly constructed object is implementation-defined. bad_alloc(const bad_alloc&) noexcept; bad_alloc& operator=(const bad_alloc&) noexcept;
4
Effects: Copies an object of class bad_alloc. virtual const char* what() const noexcept;
5
Returns: An implementation-defined ntbs. 18.6.2.2
Class bad_array_new_length
[new.badlength]
namespace std { class bad_array_new_length : public bad_alloc { public: bad_array_new_length() noexcept; }; } 1
The class bad_array_new_length defines the type of objects thrown as exceptions by the implementation to report an attempt to allocate an array of size less than zero or greater than an implementation-defined limit (5.3.4). bad_array_new_length() noexcept;
2
Effects: constructs an object of class bad_array_new_length.
3
Remarks: the result of calling what() on the newly constructed object is implementation-defined. 18.6.2.3
Type new_handler
[new.handler]
typedef void (*new_handler)(); 1
The type of a handler function to be called by operator new() or operator new[]() (18.6.1) when they cannot satisfy a request for additional storage.
2
Required behavior: A new_handler shall perform one of the following: — make more storage available for allocation and then return; — throw an exception of type bad_alloc or a class derived from bad_alloc; — terminate execution of the program without returning to the caller;
§ 18.6.2.3
444
c ISO/IEC
18.6.2.4
set_new_handler
N3376
[set.new.handler]
new_handler set_new_handler(new_handler new_p) noexcept; 1
Effects: Establishes the function designated by new_p as the current new_handler.
2
Returns: The previous new_handler.
3
Remarks: The initial new_handler is a null pointer. 18.6.2.5
get_new_handler
[get.new.handler]
new_handler get_new_handler() noexcept; 1
Returns: The current new_handler. [ Note: This may be a null pointer value. — end note ]
18.7 1
Type identification
[support.rtti]
The header defines a type associated with type information generated by the implementation. It also defines two types for reporting dynamic type identification errors. Header synopsis namespace std { class type_info; class bad_cast; class bad_typeid; }
See also: 5.2.7, 5.2.8.
18.7.1
Class type_info
[type.info]
namespace std { class type_info { public: virtual ~type_info(); bool operator==(const type_info& rhs) const noexcept; bool operator!=(const type_info& rhs) const noexcept; bool before(const type_info& rhs) const noexcept; size_t hash_code() const noexcept; const char* name() const noexcept; type_info(const type_info& rhs) = delete; // cannot be copied type_info& operator=(const type_info& rhs) = delete; // cannot be copied }; } 1
The class type_info describes type information generated by the implementation. Objects of this class effectively store a pointer to a name for the type, and an encoded value suitable for comparing two types for equality or collating order. The names, encoding rule, and collating sequence for types are all unspecified and may differ between programs. bool operator==(const type_info& rhs) const noexcept;
2
Effects: Compares the current object with rhs.
3
Returns: true if the two values describe the same type. bool operator!=(const type_info& rhs) const noexcept;
4
Returns: !(*this == rhs). § 18.7.1
445
c ISO/IEC
N3376
bool before(const type_info& rhs) const noexcept; 5
Effects: Compares the current object with rhs.
6
Returns: true if *this precedes rhs in the implementation’s collation order. size_t hash_code() const noexcept;
7
Returns: An unspecified value, except that within a single execution of the program, it shall return the same value for any two type_info objects which compare equal.
8
Remark: an implementation should return different values for two type_info objects which do not compare equal. const char* name() const noexcept;
9 10
Returns: An implementation-defined ntbs. Remarks: The message may be a null-terminated multibyte string (17.5.2.1.4.2), suitable for conversion and display as a wstring (21.3, 22.4.1.4)
18.7.2
Class bad_cast
[bad.cast]
namespace std { class bad_cast : public exception { public: bad_cast() noexcept; bad_cast(const bad_cast&) noexcept; bad_cast& operator=(const bad_cast&) noexcept; virtual const char* what() const noexcept; }; } 1
The class bad_cast defines the type of objects thrown as exceptions by the implementation to report the execution of an invalid dynamic-cast expression (5.2.7). bad_cast() noexcept;
2
Effects: Constructs an object of class bad_cast.
3
Remarks: The result of calling what() on the newly constructed object is implementation-defined. bad_cast(const bad_cast&) noexcept; bad_cast& operator=(const bad_cast&) noexcept;
4
Effects: Copies an object of class bad_cast. virtual const char* what() const noexcept;
5
Returns: An implementation-defined ntbs.
6
Remarks: The message may be a null-terminated multibyte string (17.5.2.1.4.2), suitable for conversion and display as a wstring (21.3, 22.4.1.4)
§ 18.7.2
446
c ISO/IEC
18.7.3
N3376
Class bad_typeid
[bad.typeid]
namespace std { class bad_typeid : public exception { public: bad_typeid() noexcept; bad_typeid(const bad_typeid&) noexcept; bad_typeid& operator=(const bad_typeid&) noexcept; virtual const char* what() const noexcept; }; } 1
The class bad_typeid defines the type of objects thrown as exceptions by the implementation to report a null pointer in a typeid expression (5.2.8). bad_typeid() noexcept;
2
Effects: Constructs an object of class bad_typeid.
3
Remarks: The result of calling what() on the newly constructed object is implementation-defined. bad_typeid(const bad_typeid&) noexcept; bad_typeid& operator=(const bad_typeid&) noexcept;
4
Effects: Copies an object of class bad_typeid. virtual const char* what() const noexcept;
5
Returns: An implementation-defined ntbs.
6
Remarks: The message may be a null-terminated multibyte string (17.5.2.1.4.2), suitable for conversion and display as a wstring (21.3, 22.4.1.4)
18.8 1
Exception handling
[support.exception]
The header <exception> defines several types and functions related to the handling of exceptions in a C++ program. Header <exception> synopsis namespace std { class exception; class bad_exception; class nested_exception; typedef void (*unexpected_handler)(); unexpected_handler get_unexpected() noexcept; unexpected_handler set_unexpected(unexpected_handler f) noexcept; [[noreturn]] void unexpected(); typedef void (*terminate_handler)(); terminate_handler get_terminate() noexcept; terminate_handler set_terminate(terminate_handler f) noexcept; [[noreturn]] void terminate() noexcept; bool uncaught_exception() noexcept; typedef unspecified
§ 18.8
exception_ptr;
447
c ISO/IEC
N3376
exception_ptr current_exception() noexcept; [[noreturn]] void rethrow_exception(exception_ptr p); template exception_ptr make_exception_ptr(E e) noexcept; [[noreturn]] template void throw_with_nested(T&& t); template void rethrow_if_nested(const E& e); }
See also: 15.5.
18.8.1
Class exception
[exception]
namespace std { class exception { public: exception() noexcept; exception(const exception&) noexcept; exception& operator=(const exception&) noexcept; virtual ~exception(); virtual const char* what() const noexcept; }; } 1
2
The class exception defines the base class for the types of objects thrown as exceptions by C++ standard library components, and certain expressions, to report errors detected during program execution. Each standard library class T that derives from class exception shall have a publicly accessible copy constructor and a publicly accessible copy assignment operator that do not exit with an exception. These member functions shall meet the following postcondition: If two objects lhs and rhs both have dynamic type T and lhs is a copy of rhs, then strcmp(lhs.what(), rhs.what()) shall equal 0. exception() noexcept;
3
Effects: Constructs an object of class exception.
4
Remarks: Does not throw any exceptions. exception(const exception& rhs) noexcept; exception& operator=(const exception& rhs) noexcept;
5
Effects: Copies an exception object.
6
Postcondition: If *this and rhs both have dynamic type exception then strcmp(what(), rhs.what()) shall equal 0. virtual ~exception();
7
Effects: Destroys an object of class exception.
8
Remarks: Does not throw any exceptions. virtual const char* what() const noexcept;
9 10
Returns: An implementation-defined ntbs. Remarks: The message may be a null-terminated multibyte string (17.5.2.1.4.2), suitable for conversion and display as a wstring (21.3, 22.4.1.4). The return value remains valid until the exception object from which it is obtained is destroyed or a non-const member function of the exception object is called. § 18.8.1
448
c ISO/IEC
18.8.2
N3376
Class bad_exception
[bad.exception]
namespace std { class bad_exception : public exception { public: bad_exception() noexcept; bad_exception(const bad_exception&) noexcept; bad_exception& operator=(const bad_exception&) noexcept; virtual const char* what() const noexcept; }; } 1
The class bad_exception defines the type of objects thrown as described in (15.5.2). bad_exception() noexcept;
2
Effects: Constructs an object of class bad_exception.
3
Remarks: The result of calling what() on the newly constructed object is implementation-defined. bad_exception(const bad_exception&) noexcept; bad_exception& operator=(const bad_exception&) noexcept;
4
Effects: Copies an object of class bad_exception. virtual const char* what() const noexcept;
5
Returns: An implementation-defined ntbs.
6
Remarks: The message may be a null-terminated multibyte string (17.5.2.1.4.2), suitable for conversion and display as a wstring (21.3, 22.4.1.4).
18.8.3 18.8.3.1
Abnormal termination
[exception.terminate]
Type terminate_handler
[terminate.handler]
typedef void (*terminate_handler)(); 1
The type of a handler function to be called by std::terminate() when terminating exception processing.
2
Required behavior: A terminate_handler shall terminate execution of the program without returning to the caller.
3
Default behavior: The implementation’s default terminate_handler calls abort(). 18.8.3.2
set_terminate
[set.terminate]
terminate_handler set_terminate(terminate_handler f) noexcept; 1
Effects: Establishes the function designated by f as the current handler function for terminating exception processing.
2
Remarks: It is unspecified whether a null pointer value designates the default terminate_handler.
3
Returns: The previous terminate_handler. 18.8.3.3
get_terminate
[get.terminate]
terminate_handler get_terminate() noexcept; 1
Returns: The current terminate_handler. [ Note: This may be a null pointer value. — end note ] § 18.8.3.3
449
c ISO/IEC
18.8.3.4
N3376
[terminate]
terminate
[[noreturn]] void terminate() noexcept; 1
Remarks: Called by the implementation when exception handling must be abandoned for any of several reasons (15.5.1), in effect immediately after evaluating the throw-expression (18.8.3.1). May also be called directly by the program.
2
Effects: Calls the current terminate_handler function. [ Note: A default terminate_handler is always considered a callable handler in this context. — end note ]
18.8.4
uncaught_exception
[uncaught]
bool uncaught_exception() noexcept; 1
Returns: true after the current thread has initialized an exception object (15.1) until a handler for the exception (including std::unexpected() or std::terminate()) is activated (15.3). [ Note: This includes stack unwinding (15.2). — end note ]
2
Remarks: When uncaught_exception() returns true, throwing an exception can result in a call of std::terminate() (15.5.1).
18.8.5
Exception propagation
typedef unspecified
[propagation]
exception_ptr;
1
The type exception_ptr can be used to refer to an exception object.
2
exception_ptr shall satisfy the requirements of NullablePointer (17.6.3.3).
3
Two non-null values of type exception_ptr are equivalent and compare equal if and only if they refer to the same exception.
4
The default constructor of exception_ptr produces the null value of the type.
5
exception_ptr shall not be implicitly convertible to any arithmetic, enumeration, or pointer type.
6
[ Note: An implementation might use a reference-counted smart pointer as exception_ptr. — end note ]
7
For purposes of determining the presence of a data race, operations on exception_ptr objects shall access and modify only the exception_ptr objects themselves and not the exceptions they refer to. Use of rethrow_exception on exception_ptr objects that refer to the same exception object shall not introduce a data race. [ Note: if rethrow_exception rethrows the same exception object (rather than a copy), concurrent access to that rethrown exception object may introduce a data race. Changes in the number of exception_ptr objects that refer to a particular exception do not introduce a data race. — end note ] exception_ptr current_exception() noexcept;
8
Returns: An exception_ptr object that refers to the currently handled exception (15.3) or a copy of the currently handled exception, or a null exception_ptr object if no exception is being handled. The referenced object shall remain valid at least as long as there is an exception_ptr object that refers to it. If the function needs to allocate memory and the attempt fails, it returns an exception_ptr object that refers to an instance of bad_alloc. It is unspecified whether the return values of two successive calls to current_exception refer to the same exception object. [ Note: That is, it is unspecified whether current_exception creates a new copy each time it is called. — end note ] If the attempt to copy the current exception object throws an exception, the function returns an exception_ptr object that refers to the thrown exception or, if this is not possible, to an instance of bad_exception. § 18.8.5
450
c ISO/IEC
N3376
[ Note: The copy constructor of the thrown exception may also fail, so the implementation is allowed to substitute a bad_exception object to avoid infinite recursion. — end note ] [[noreturn]] void rethrow_exception(exception_ptr p); 9
Requires: p shall not be a null pointer.
10
Throws: the exception object to which p refers. template exception_ptr make_exception_ptr(E e) noexcept;
11
Effects: Creates an exception_ptr object that refers to a copy of e, as if try { throw e; } catch(...) { return current_exception(); }
12
[ Note: This function is provided for convenience and efficiency reasons. — end note ]
18.8.6
nested_exception
[except.nested]
namespace std { class nested_exception { public: nested_exception() noexcept; nested_exception(const nested_exception&) noexcept = default; nested_exception& operator=(const nested_exception&) noexcept = default; virtual ~nested_exception() = default; // access functions [[noreturn]] void rethrow_nested() const; exception_ptr nested_ptr() const noexcept; }; [[noreturn]] template void throw_with_nested(T&& t); template void rethrow_if_nested(const E& e); } 1
2
The class nested_exception is designed for use as a mixin through multiple inheritance. It captures the currently handled exception and stores it for later use. [ Note: nested_exception has a virtual destructor to make it a polymorphic class. Its presence can be tested for with dynamic_cast. — end note ] nested_exception() noexcept;
3
Effects: The constructor calls current_exception() and stores the returned value. [[noreturn]] void rethrow_nested() const;
4
Effects: If nested_ptr() returns a null pointer, the function calls std::terminate(). Otherwise, it throws the stored exception captured by *this. exception_ptr nested_ptr() const noexcept;
§ 18.8.6
451
c ISO/IEC
5
N3376
Returns: The stored exception captured by this nested_exception object. [[noreturn]] template void throw_with_nested(T&& t);
Let U be remove_reference::type. 6
Requires: U shall be CopyConstructible.
7
Throws: if U is a non-union class type not derived from nested_exception, an exception of unspecified type that is publicly derived from both U and nested_exception and constructed from std::forward(t), otherwise std::forward(t). template void rethrow_if_nested(const E& e);
8
Effects: If the dynamic type of e is publicly and unambiguously derived from nested_exception, calls dynamic_cast(e).rethrow_nested().
18.9 1
Initializer lists
[support.initlist]
The header defines one type. Header synopsis namespace std { template class initializer_list { public: typedef E value_type; typedef const E& reference; typedef const E& const_reference; typedef size_t size_type; typedef const E* iterator; typedef const E* const_iterator; initializer_list() noexcept; size_t size() const noexcept; const E* begin() const noexcept; const E* end() const noexcept;
// number of elements // first element // one past the last element
}; // 18.9.3 initializer list range access template const E* begin(initializer_list<E> il) noexcept; template const E* end(initializer_list<E> il) noexcept; } 2
An object of type initializer_list<E> provides access to an array of objects of type const E. [ Note: A pair of pointers or a pointer plus a length would be obvious representations for initializer_list. initializer_list is used to implement initializer lists as specified in 8.5.4. Copying an initializer list does not copy the underlying elements. — end note ]
18.9.1
Initializer list constructors
[support.initlist.cons]
initializer_list() noexcept; 1
Effects: constructs an empty initializer_list object.
2
Postcondition: size() == 0 § 18.9.1
452
c ISO/IEC
18.9.2
Initializer list access
N3376
[support.initlist.access]
const E* begin() const noexcept; 1
Returns: A pointer to the beginning of the array. If size() == 0 the values of begin() and end() are unspecified but they shall be identical. const E* end() const noexcept;
2
Returns: begin() + size() size_t size() const noexcept;
3
Returns: The number of elements in the array.
4
Complexity: constant time.
18.9.3
Initializer list range access
[support.initlist.range]
template const E* begin(initializer_list<E> il) noexcept; 1
Returns: il.begin(). template const E* end(initializer_list<E> il) noexcept;
2
Returns: il.end().
18.10 1
2
3
4
5
6
Other runtime support
[support.runtime]
Headers (nonlocal jumps), (signal handling), (alignment), (variable arguments), (_ _ bool_true_false_are_defined). (runtime environment getenv(), system()), and (system clock clock(), time()) provide further compatibility with C code. The contents of these headers are the same as the Standard C library headers <setjmp.h>, <signal.h>, <stdalign.h>, <stdarg.h>, <stdbool.h>, <stdlib.h>, and , respectively, with the following changes: The restrictions that ISO C places on the second parameter to the va_start() macro in header <stdarg.h> are different in this International Standard. The parameter parmN is the identifier of the rightmost parameter in the variable parameter list of the function definition (the one just before the ...).226 If the parameter parmN is declared with a function, array, or reference type, or with a type that is not compatible with the type that results when passing an argument for which there is no parameter, the behavior is undefined. See also: ISO C 4.8.1.1. The function signature longjmp(jmp_buf jbuf, int val) has more restricted behavior in this International Standard. A setjmp/longjmp call pair has undefined behavior if replacing the setjmp and longjmp by catch and throw would invoke any non-trivial destructors for any automatic objects. See also: ISO C 7.10.4, 7.8, 7.6, 7.12. Calls to the function getenv shall not introduce a data race (17.6.5.9) provided that nothing modifies the environment. [ Note: Calls to the POSIX functions setenv and putenv modify the environment. — end note ] A call to the setlocale function may introduce a data race with other calls to the setlocale function or with calls to functions that are affected by the current C locale. The implementation shall behave as if no library function other than locale::global() calls the setlocale function. 226) Note that va_start is required to work as specified even if unary operator& is overloaded for the type of parmN.
§ 18.10
453
c ISO/IEC
7 8 9
N3376
The header and the header <stdalign.h> shall not define a macro named alignas. The header and the header <stdbool.h> shall not define macros named bool, true, or false. The common subset of the C and C++ languages consists of all declarations, definitions, and expressions that may appear in a well formed C++ program and also in a conforming C program. A POF (“plain old function”) is a function that uses only features from this common subset, and that does not directly or indirectly use any function that is not a POF, except that it may use functions defined in Clause 29 that are not member functions. All signal handlers shall have C linkage. A POF that could be used as a signal handler in a conforming C program does not produce undefined behavior when used as a signal handler in a C++ program. The behavior of any other function used as a signal handler in a C++ program is implementation-defined.227 Table 34 — Header synopsis Type Macro: Type: Function:
Name(s) setjmp jmp_buf longjmp
Table 35 — Header synopsis Type Macros: SIG_IGN Type: Functions:
SIGABRT SIGFPE sig_atomic_t raise
SIGILL SIGINT
Name(s) SIGSEGV SIGTERM
SIG_DFL SIG_ERR
signal
Table 36 — Header synopsis Type Macro:
Name(s) __alignas_is_defined
Table 37 — Header synopsis Type Macros: va_copy Type:
va_arg
va_end
Name(s) va_start
va_list
227) In particular, a signal handler using exception handling is very likely to have problems. Also, invoking std::exit may cause destruction of objects, including those of the standard library implementation, which, in general, yields undefined behavior in a signal handler (see 1.9).
§ 18.10
454
c ISO/IEC
N3376
Table 38 — Header synopsis Type Macro:
Name(s) __bool_true_false_are_defined
Table 39 — Header synopsis Type Functions:
Name(s) getenv
system
Table 40 — Header synopsis Type Macro: Type: Function:
§ 18.10
Name(s) CLOCKS_PER_SEC clock_t clock
455
c ISO/IEC
19 19.1 1 2
N3376
Diagnostics library
[diagnostics]
General
[diagnostics.general]
This Clause describes components that C++ programs may use to detect and report error conditions. The following subclauses describe components for reporting several kinds of exceptional conditions, documenting program assertions, and a global variable for error number codes, as summarized in Table 41. Table 41 — Diagnostics library summary
19.2 19.3 19.4 19.5
19.2 1
2
3
Subclause Exception classes Assertions Error numbers System error support
Exception classes
Header(s) <stdexcept> <system_error>
[std.exceptions]
The Standard C++ library provides classes to be used to report certain errors (17.6.5.12) in C++ programs. In the error model reflected in these classes, errors are divided into two broad categories: logic errors and runtime errors. The distinguishing characteristic of logic errors is that they are due to errors in the internal logic of the program. In theory, they are preventable. By contrast, runtime errors are due to events beyond the scope of the program. They cannot be easily predicted in advance. The header <stdexcept> defines several types of predefined exceptions for reporting errors in a C++ program. These exceptions are related by inheritance. Header <stdexcept> synopsis namespace std { class logic_error; class domain_error; class invalid_argument; class length_error; class out_of_range; class runtime_error; class range_error; class overflow_error; class underflow_error; }
19.2.1
Class logic_error
[logic.error]
namespace std { class logic_error : public exception { public: explicit logic_error(const string& what_arg); explicit logic_error(const char* what_arg); }; }
§ 19.2.1
456
c ISO/IEC
1
N3376
The class logic_error defines the type of objects thrown as exceptions to report errors presumably detectable before the program executes, such as violations of logical preconditions or class invariants. logic_error(const string& what_arg);
2
Effects: Constructs an object of class logic_error.
3
Postcondition: strcmp(what(), what_arg.c_str()) == 0. logic_error(const char* what_arg);
4
Effects: Constructs an object of class logic_error.
5
Postcondition: strcmp(what(), what_arg) == 0.
19.2.2
Class domain_error
[domain.error]
namespace std { class domain_error : public logic_error { public: explicit domain_error(const string& what_arg); explicit domain_error(const char* what_arg); }; } 1
The class domain_error defines the type of objects thrown as exceptions by the implementation to report domain errors. domain_error(const string& what_arg);
2
Effects: Constructs an object of class domain_error.
3
Postcondition: strcmp(what(), what_arg.c_str()) == 0. domain_error(const char* what_arg);
4
Effects: Constructs an object of class domain_error.
5
Postcondition: strcmp(what(), what_arg) == 0.
19.2.3
Class invalid_argument
[invalid.argument]
namespace std { class invalid_argument : public logic_error { public: explicit invalid_argument(const string& what_arg); explicit invalid_argument(const char* what_arg); }; } 1
The class invalid_argument defines the type of objects thrown as exceptions to report an invalid argument. invalid_argument(const string& what_arg);
2
Effects: Constructs an object of class invalid_argument.
3
Postcondition: strcmp(what(), what_arg.c_str()) == 0. invalid_argument(const char* what_arg);
4
Effects: Constructs an object of class invalid_argument.
5
Postcondition: strcmp(what(), what_arg) == 0. § 19.2.3
457
c ISO/IEC
19.2.4
Class length_error
N3376
[length.error]
namespace std { class length_error : public logic_error { public: explicit length_error(const string& what_arg); explicit length_error(const char* what_arg); }; } 1
The class length_error defines the type of objects thrown as exceptions to report an attempt to produce an object whose length exceeds its maximum allowable size. length_error(const string& what_arg);
2
Effects: Constructs an object of class length_error.
3
Postcondition: strcmp(what(), what_arg.c_str()) == 0. length_error(const char* what_arg);
4
Effects: Constructs an object of class length_error.
5
Postcondition: strcmp(what(), what_arg) == 0.
19.2.5
Class out_of_range
[out.of.range]
namespace std { class out_of_range : public logic_error { public: explicit out_of_range(const string& what_arg); explicit out_of_range(const char* what_arg); }; } 1
The class out_of_range defines the type of objects thrown as exceptions to report an argument value not in its expected range. out_of_range(const string& what_arg);
2
Effects: Constructs an object of class out_of_range.
3
Postcondition: strcmp(what(), what_arg.c_str()) == 0. out_of_range(const char* what_arg);
4
Effects: Constructs an object of class out_of_range.
5
Postcondition: strcmp(what(), what_arg) == 0.
19.2.6
Class runtime_error
[runtime.error]
namespace std { class runtime_error : public exception { public: explicit runtime_error(const string& what_arg); explicit runtime_error(const char* what_arg); }; }
§ 19.2.6
458
c ISO/IEC
1
N3376
The class runtime_error defines the type of objects thrown as exceptions to report errors presumably detectable only when the program executes. runtime_error(const string& what_arg);
2
Effects: Constructs an object of class runtime_error.
3
Postcondition: strcmp(what(), what_arg.c_str()) == 0. runtime_error(const char* what_arg);
4
Effects: Constructs an object of class runtime_error.
5
Postcondition: strcmp(what(), what_arg) == 0.
19.2.7
Class range_error
[range.error]
namespace std { class range_error : public runtime_error { public: explicit range_error(const string& what_arg); explicit range_error(const char* what_arg); }; } 1
The class range_error defines the type of objects thrown as exceptions to report range errors in internal computations. range_error(const string& what_arg);
2
Effects: Constructs an object of class range_error.
3
Postcondition: strcmp(what(), what_arg.c_str()) == 0. range_error(const char* what_arg);
4
Effects: Constructs an object of class range_error.
5
Postcondition: strcmp(what(), what_arg) == 0.
19.2.8
Class overflow_error
[overflow.error]
namespace std { class overflow_error : public runtime_error { public: explicit overflow_error(const string& what_arg); explicit overflow_error(const char* what_arg); }; } 1
The class overflow_error defines the type of objects thrown as exceptions to report an arithmetic overflow error. overflow_error(const string& what_arg);
2
Effects: Constructs an object of class overflow_error.
3
Postcondition: strcmp(what(), what_arg.c_str()) == 0. overflow_error(const char* what_arg);
4
Effects: Constructs an object of class overflow_error.
5
Postcondition: strcmp(what(), what_arg) == 0. § 19.2.8
459
c ISO/IEC
19.2.9
N3376
Class underflow_error
[underflow.error]
namespace std { class underflow_error : public runtime_error { public: explicit underflow_error(const string& what_arg); explicit underflow_error(const char* what_arg); }; } 1
The class underflow_error defines the type of objects thrown as exceptions to report an arithmetic underflow error. underflow_error(const string& what_arg);
2
Effects: Constructs an object of class underflow_error.
3
Postcondition: strcmp(what(), what_arg.c_str()) == 0. underflow_error(const char* what_arg);
4
Effects: Constructs an object of class underflow_error.
5
Postcondition: strcmp(what(), what_arg) == 0.
19.3 1
Assertions
[assertions]
The header , described in (Table 42), provides a macro for documenting C++ program assertions and a mechanism for disabling the assertion checks. Table 42 — Header synopsis Type Macro:
2
The contents are the same as the Standard C library header . See also: ISO C 7.2.
19.4 1
2
Error numbers
[errno]
The header is described in Table 43. Its contents are the same as the POSIX header <errno.h>, except that errno shall be defined as a macro. [ Note: The intent is to remain in close alignment with the POSIX standard. — end note ] A separate errno value shall be provided for each thread.
19.5 1
Name(s) assert
System error support
[syserr] C++
This subclause describes components that the standard library and programs may use to report error conditions originating from the operating system or other low-level application program interfaces. Components described in this subclause shall not change the value of errno (19.4). Implementations should leave the error states provided by other libraries unchanged. Header <system_error> synopsis namespace std { class error_category; const error_category& generic_category() noexcept; const error_category& system_category() noexcept; class error_code;
§ 19.5
460
c ISO/IEC
N3376
Table 43 — Header synopsis Type Macros: E2BIG EACCES EADDRINUSE EADDRNOTAVAIL EAFNOSUPPORT EAGAIN EALREADY EBADF EBADMSG EBUSY ECANCELED ECHILD ECONNABORTED
ECONNREFUSED ECONNRESET EDEADLK EDESTADDRREQ EDOM EEXIST EFAULT EFBIG EHOSTUNREACH EIDRM EILSEQ EINPROGRESS EINTR EINVAL
EIO EISCONN EISDIR ELOOP EMFILE EMLINK EMSGSIZE ENAMETOOLONG ENETDOWN ENETRESET ENETUNREACH ENFILE ENOBUFS ENODATA
Name(s) ENODEV ENOENT ENOEXEC ENOLCK ENOLINK ENOMEM ENOMSG ENOPROTOOPT ENOSPC ENOSR ENOSTR ENOSYS ENOTCONN ENOTDIR
ENOTEMPTY ENOTRECOVERABLE ENOTSOCK ENOTSUP ENOTTY ENXIO EOPNOTSUPP EOVERFLOW EOWNERDEAD EPERM EPIPE EPROTO EPROTONOSUPPORT EPROTOTYPE
ERANGE EROFS ESPIPE ESRCH ETIME ETIMEDOUT ETXTBSY EWOULDBLOCK EXDEV errno
class error_condition; class system_error; template struct is_error_code_enum : public false_type {}; template struct is_error_condition_enum : public false_type {}; enum class errc { address_family_not_supported, address_in_use, address_not_available, already_connected, argument_list_too_long, argument_out_of_domain, bad_address, bad_file_descriptor, bad_message, broken_pipe, connection_aborted, connection_already_in_progress, connection_refused, connection_reset, cross_device_link, destination_address_required, device_or_resource_busy, directory_not_empty, executable_format_error, file_exists, file_too_large, filename_too_long, function_not_supported,
§ 19.5
// // // // // // // // // // // // // // // // // // // // // // //
EAFNOSUPPORT EADDRINUSE EADDRNOTAVAIL EISCONN E2BIG EDOM EFAULT EBADF EBADMSG EPIPE ECONNABORTED EALREADY ECONNREFUSED ECONNRESET EXDEV EDESTADDRREQ EBUSY ENOTEMPTY ENOEXEC EEXIST EFBIG ENAMETOOLONG ENOSYS
461
c ISO/IEC
host_unreachable, identifier_removed, illegal_byte_sequence, inappropriate_io_control_operation, interrupted, invalid_argument, invalid_seek, io_error, is_a_directory, message_size, network_down, network_reset, network_unreachable, no_buffer_space, no_child_process, no_link, no_lock_available, no_message_available, no_message, no_protocol_option, no_space_on_device, no_stream_resources, no_such_device_or_address, no_such_device, no_such_file_or_directory, no_such_process, not_a_directory, not_a_socket, not_a_stream, not_connected, not_enough_memory, not_supported, operation_canceled, operation_in_progress, operation_not_permitted, operation_not_supported, operation_would_block, owner_dead, permission_denied, protocol_error, protocol_not_supported, read_only_file_system, resource_deadlock_would_occur, resource_unavailable_try_again, result_out_of_range, state_not_recoverable, stream_timeout, text_file_busy, timed_out, too_many_files_open_in_system, too_many_files_open, too_many_links, too_many_symbolic_link_levels, value_too_large, wrong_protocol_type,
§ 19.5
N3376
// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //
EHOSTUNREACH EIDRM EILSEQ ENOTTY EINTR EINVAL ESPIPE EIO EISDIR EMSGSIZE ENETDOWN ENETRESET ENETUNREACH ENOBUFS ECHILD ENOLINK ENOLCK ENODATA ENOMSG ENOPROTOOPT ENOSPC ENOSR ENXIO ENODEV ENOENT ESRCH ENOTDIR ENOTSOCK ENOSTR ENOTCONN ENOMEM ENOTSUP ECANCELED EINPROGRESS EPERM EOPNOTSUPP EWOULDBLOCK EOWNERDEAD EACCES EPROTO EPROTONOSUPPORT EROFS EDEADLK EAGAIN ERANGE ENOTRECOVERABLE ETIME ETXTBSY ETIMEDOUT ENFILE EMFILE EMLINK ELOOP EOVERFLOW EPROTOTYPE
462
c ISO/IEC
N3376
}; template struct is_error_condition_enum<errc> : true_type { } error_code make_error_code(errc e) noexcept; error_condition make_error_condition(errc e) noexcept; // 19.5.4 Comparison operators: bool operator==(const error_code& lhs, bool operator==(const error_code& lhs, bool operator==(const error_condition& bool operator==(const error_condition& bool operator!=(const error_code& lhs, bool operator!=(const error_code& lhs, bool operator!=(const error_condition& bool operator!=(const error_condition&
const error_code& rhs) noexcept; const error_condition& rhs) noexcept; lhs, const error_code& rhs) noexcept; lhs, const error_condition& rhs) noexcept; const error_code& rhs) noexcept; const error_condition& rhs) noexcept; lhs, const error_code& rhs) noexcept; lhs, const error_condition& rhs) noexcept;
// 19.5.5 Hash support template struct hash; template struct hash<error_code>; } // namespace std 3
4
The value of each enum errc constant shall be the same as the value of the macro shown in the above synopsis. Whether or not the <system_error> implementation exposes the macros is unspecified. The is_error_code_enum and is_error_condition_enum may be specialized for user-defined types to indicate that such types are eligible for class error_code and class error_condition automatic conversions, respectively.
19.5.1 19.5.1.1 1
Class error_category Class error_category overview
[syserr.errcat] [syserr.errcat.overview]
The class error_category serves as a base class for types used to identify the source and encoding of a particular category of error code. Classes may be derived from error_category to support categories of errors in addition to those defined in this International Standard. Such classes shall behave as specified in this subclause. [ Note: error_category objects are passed by reference, and two such objects are equal if they have the same address. This means that applications using custom error_category types should create a single object of each such type. — end note ] namespace std { class error_category { public: virtual ~error_category() noexcept; error_category(const error_category&) = delete; error_category& operator=(const error_category&) = delete; virtual const char* name() const noexcept = 0; virtual error_condition default_error_condition(int ev) const noexcept; virtual bool equivalent(int code, const error_condition& condition) const noexcept; virtual bool equivalent(const error_code& code, int condition) const noexcept; virtual string message(int ev) const = 0; bool operator==(const error_category& rhs) const noexcept; bool operator!=(const error_category& rhs) const noexcept; bool operator (const pair&, const template bool operator>=(const pair&, const template bool operator class tuple_element; template struct tuple_size<std::pair >; template struct tuple_element; template struct tuple_element; template<size_t I, class T1, class T2> typename tuple_element::type& get(std::pair&) noexcept; template<size_t I, class T1, class T2> typename tuple_element::type&& get(std::pair&&) noexcept; template<size_t I, class T1, class T2> const typename tuple_element::type& get(const std::pair&) noexcept; // 20.3.5, pair piecewise construction struct piecewise_construct_t { }; constexpr piecewise_construct_t piecewise_construct = piecewise_construct_t(); template class tuple; // defined in }
§ 20.2
473
c ISO/IEC
20.2.1 1
Operators
N3376
[operators]
To avoid redundant definitions of operator!= out of operator== and operators >, = out of operator(const T& x, const T& y);
4
Requires: Type T is LessThanComparable (Table 18).
5
Returns: y < x. template bool operator=(const T& x, const T& y);
8
Requires: Type T is LessThanComparable (Table 18).
9
Returns: !(x < y).
10
In this library, whenever a declaration is provided for an operator!=, operator>, operator>=, or operator::type move_if_noexcept(T& x) noexcept; 8
Returns: std::move(x)
20.2.4 1
Function template declval
[declval]
The library provides the function template declval to simplify the definition of expressions which occur as unevaluated operands (Clause 5). template typename add_rvalue_reference::type declval() noexcept;
// as unevaluated operand
2
Remarks: If this function is odr-used (3.2), the program is ill-formed.
3
Remarks: The template parameter T of declval may be an incomplete type. [ Example: template decltype(static_cast(declval())) convert(From&&);
declares a function template convert which only participates in overloading if the type From can be explicitly converted to type To. For another example see class template common_type (20.9.7.6). — end example ]
20.3
Pairs
20.3.1 1
In general
[pairs] [pairs.general]
The library provides a template for heterogeneous pairs of values. The library also provides a matching function template to simplify their construction and several templates that provide access to pair objects as if they were tuple objects (see 20.4.2.5 and 20.4.2.6).
20.3.2
Class template pair
[pairs.pair]
// defined in header namespace std { template struct pair { typedef T1 first_type; typedef T2 second_type; T1 first; T2 second; pair(const pair&) = default; pair(pair&&) = default; constexpr pair(); pair(const T1& x, const T2& y); template pair(U&& x, V&& y); template pair(const pair& p); template pair(pair&& p); template
§ 20.3.2
476
c ISO/IEC
N3376
pair(piecewise_construct_t, tuple first_args, tuple second_args); pair& operator=(const pair& p); template pair& operator=(const pair& p); pair& operator=(pair&& p) noexcept(see below ); template pair& operator=(pair&& p); void swap(pair& p) noexcept(see below ); }; } 1
Constructors and member function of pair shall not throw exceptions unless one of the element-wise operations specified to be called for that operation throws an exception. constexpr pair();
2
Requires: is_default_constructible::value is true and is_default_constructible<second_type>::value is true.
3
Effects: Value-initializes first and second. pair(const T1& x, const T2& y);
4
Requires: is_copy_constructible::value is true and is_copy_constructible<second_type>::value is true.
5
Effects: The constructor initializes first with x and second with y. template pair(U&& x, V&& y);
6
Requires: is_constructible::value is true and is_constructible<second_type, V&&>::value is true.
7
Effects: The constructor initializes first with std::forward(x) and second with std::forward< V>(y).
8
Remarks: If U is not implicitly convertible to first_type or V is not implicitly convertible to second_type this constructor shall not participate in overload resolution. template pair(const pair& p);
9
Requires: is_constructible::value is true and is_constructible<second_type, const V&>::value is true.
10
Effects: Initializes members from the corresponding members of the argument.
11
Remark: This constructor shall not participate in overload resolution unless const U& is implicitly convertible to first_type and const V& is implicitly convertible to second_type. template pair(pair&& p);
12
Requires: is_constructible::value is true and is_constructible<second_type, V&&>::value is true.
13
Effects: The constructor initializes first with std::forward(p.first) and second with std:: forward(p.second).
14
Remark: This constructor shall not participate in overload resolution unless U is implicitly convertible to first_type and V is implicitly convertible to second_type. § 20.3.2
477
c ISO/IEC
N3376
template pair(piecewise_construct_t, tuple first_args, tuple second_args); 15
Requires: Requires: is_constructible::value is true and is_constructible<second_type, Args2&&...>::value is true.
16
Effects: The constructor initializes first with arguments of types Args1... obtained by forwarding the elements of first_args and initializes second with arguments of types Args2... obtained by forwarding the elements of second_args. (Here, forwarding an element x of type U within a tuple object means calling std::forward(x).) This form of construction, whereby constructor arguments for first and second are each provided in a separate tuple object, is called piecewise construction. pair& operator=(const pair& p);
17
Requires: is_copy_assignable::value is true and is_copy_assignable<second_type>::value is true.
18
Effects: Assigns p.first to first and p.second to second.
19
Returns: *this. template pair& operator=(const pair& p);
20
Requires: is_assignable::value is true and is_assignable<second_type&, const V&>::value is true.
21
Effects: Assigns p.first to first and p.second to second.
22
Returns: *this. pair& operator=(pair&& p) noexcept(see below );
23
Remarks: The expression inside noexcept is equivalent to: is_nothrow_move_assignable::value && is_nothrow_move_assignable::value
24
Requires: is_move_assignable::value is true and is_move_assignable<second_type>::value is true.
25
Effects: Assigns to first with std::forward(p.first) and to second with std::forward<second_type>(p.second).
26
Returns: *this. template pair& operator=(pair&& p);
27
Requires: is_assignable::value is true and is_assignable<second_type&, V&&>::value is true.
28
Effects: Assigns to first with std::forward(p.first) and to second with std::forward(p.second).
29
Returns: *this.
§ 20.3.2
478
c ISO/IEC
N3376
void swap(pair& p) noexcept(see below ); 30
Remarks: The expression inside noexcept is equivalent to: noexcept(swap(first, p.first)) && noexcept(swap(second, p.second))
31
Requires: first shall be swappable with (17.6.3.2) p.first and second shall be swappable with p.second.
32
Effects: Swaps first with p.first and second with p.second.
20.3.3
Specialized algorithms
[pairs.spec]
template bool operator==(const pair& x, const pair& y); 1
Returns: x.first == y.first && x.second == y.second. template bool operator(const pair& x, const pair& y);
4
Returns: y < x template bool operator>=(const pair& x, const pair& y);
5
Returns: !(x < y) template bool operator::type for each Ti. Then each Vi is X& if Ui equals reference_wrapper<X>, otherwise Vi is Ui.
9
[ Example: In place of: return pair(5, 3.1415926);
// explicit types
a C++ program may contain: return make_pair(5, 3.1415926);
// types are deduced
— end example ]
20.3.4
Tuple-like access to pair
[pair.astuple]
tuple_size<pair >::value 1
Returns: Integral constant expression.
2
Value: 2. tuple_element::type
3
Value: the type T1. tuple_element::type
4
Value: the type T2. template<size_t I, class T1, class T2> typename tuple_element::type& get(pair&) noexcept; template<size_t I, class T1, class T2> const typename tuple_element::type& get(const pair&) noexcept;
5
Returns: If I == 0 returns p.first; if I == 1 returns p.second; otherwise the program is ill-formed. template<size_t I, class T1, class T2> typename tuple_element::type&& get(std::pair&&) noexcept;
6
Returns: If I == 0 returns std::forward(p.first); if I == 1 returns std::forward( p.second); otherwise the program is ill-formed.
20.3.5
Piecewise construction
[pair.piecewise]
struct piecewise_construct_t { }; constexpr piecewise_construct_t piecewise_construct = piecewise_construct_t(); 1
The struct piecewise_construct_t is an empty structure type used as a unique type to disambiguate constructor and function overloading. Specifically, pair has a constructor with piecewise_construct_t as the first argument, immediately followed by two tuple (20.4) arguments used for piecewise construction of the elements of the pair object.
20.4 20.4.1 1
Tuples In general
[tuple] [tuple.general]
This subclause describes the tuple library that provides a tuple type as the class template tuple that can be instantiated with any number of arguments. Each template argument specifies the type of an element § 20.4.1
480
c ISO/IEC
2
N3376
in the tuple. Consequently, tuples are heterogeneous, fixed-size collections of values. An instantiation of tuple with two arguments is similar to an instantiation of pair with the same two arguments. See 20.3. Header synopsis namespace std { // 20.4.2, class template tuple: template class tuple; // 20.4.2.4, tuple creation functions: const unspecified ignore; template tuple make_tuple(Types&&...); template tuple forward_as_tuple(Types&&...) noexcept; template tuple tie(Types&...) noexcept; template tuple tuple_cat(Tuples&&...); // 20.4.2.5, tuple template class tuple_size;
template class tuple_size; template template template template
<size_t <size_t <size_t <size_t
I, I, I, I,
class class class class
T> T> T> T>
class class class class
tuple_element; // undefined tuple_element; tuple_element; tuple_element;
template <size_t I, class... Types> class tuple_element; // 20.4.2.6, element access: template <size_t I, class... Types> typename tuple_element::type& get(tuple&) noexcept; template <size_t I, class... types> typename tuple_element::type&& get(tuple&&) noexcept; template <size_t I, class... types> typename tuple_element::type const& get(const tuple&) noexcept; // 20.4.2.7, relational operators: template bool operator==(const tuple&, const tuple&); template bool operator(const tuple&, const tuple&); template bool operator=(const tuple&, const tuple&); // 20.4.2.8, allocator-related traits template struct uses_allocator; // 20.4.2.9, specialized algorithms: template void swap(tuple& x, tuple& y) noexcept(see below ); }
20.4.2
Class template tuple
[tuple.tuple]
namespace std { template class tuple { public: // 20.4.2.1, tuple construction constexpr tuple(); explicit tuple(const Types&...); template explicit tuple(UTypes&&...); tuple(const tuple&) = default; tuple(tuple&&) = default; template tuple(const tuple&); template tuple(tuple&&); template tuple(const pair&); template tuple(pair&&);
// iff sizeof...(Types) == 2 // iff sizeof...(Types) == 2
// allocator-extended constructors template tuple(allocator_arg_t, const Alloc& a); template tuple(allocator_arg_t, const Alloc& a, const Types&...); template tuple(allocator_arg_t, const Alloc& a, UTypes&&...); template tuple(allocator_arg_t, const Alloc& a, const tuple&); template tuple(allocator_arg_t, const Alloc& a, tuple&&); template tuple(allocator_arg_t, const Alloc& a, const tuple&); template tuple(allocator_arg_t, const Alloc& a, tuple&&); template tuple(allocator_arg_t, const Alloc& a, const pair&); template
§ 20.4.2
482
c ISO/IEC
N3376
tuple(allocator_arg_t, const Alloc& a, pair&&); // 20.4.2.2, tuple assignment tuple& operator=(const tuple&); tuple& operator=(tuple&&) noexcept(see below ); template tuple& template tuple&
operator=(const tuple&); operator=(tuple&&);
template tuple& template tuple&
operator=(const pair&); operator=(pair&&);
// iff sizeof...(Types) == 2 // iff sizeof...(Types) == 2
// 20.4.2.3, tuple swap void swap(tuple&) noexcept(see below ); }; }
20.4.2.1 1
2
Construction
[tuple.cnstr]
For each tuple constructor, an exception is thrown only if the construction of one of the types in Types throws an exception. In the constructor descriptions that follow, let i be in the range [0,sizeof...(Types)) in order, Ti be the ith type in Types, and Ui be the ith type in a template parameter pack named UTypes, where indexing is zero-based. constexpr tuple();
3
Requires: is_default_constructible<Ti >::value is true for all i.
4
Effects: Value initializes each element. explicit tuple(const Types&...);
5
Requires: is_copy_constructible<Ti >::value is true for all i.
6
Effects: Initializes each element with the value of the corresponding parameter. template explicit tuple(UTypes&&... u);
7
Requires: sizeof...(Types) == sizeof...(UTypes). is_constructible<Ti , Ui &&>::value is true for all i.
8
Effects: Initializes the elements in the tuple with the corresponding value in std::forward(u).
9
Remark: This constructor shall not participate in overload resolution unless each type in UTypes is implicitly convertible to its corresponding type in Types. tuple(const tuple& u) = default;
10
Requires: is_copy_constructible<Ti >::value is true for all i.
11
Effects: Initializes each element of *this with the corresponding element of u. § 20.4.2.1
483
c ISO/IEC
N3376
tuple(tuple&& u) = default; 12
Requires: is_move_constructible<Ti >::value is true for all i.
13
Effects: For all i, initializes the ith element of *this with std::forward<Ti >(get(u)). template tuple(const tuple& u);
14
Requires: sizeof...(Types) == sizeof...(UTypes). is_constructible<Ti , const Ui &>::value is true for all i.
15
Effects: Constructs each element of *this with the corresponding element of u.
16
Remark: This constructor shall not participate in overload resolution unless const Ui & is implicitly convertible to Ti for all i. template tuple(tuple&& u);
17
Requires: sizeof...(Types) == sizeof...(UTypes). is_constructible<Ti , Ui &&>::value is true for all i.
18
Effects: For all i, initializes the ith element of *this with std::forward(get(u)).
19
Remark: This constructor shall not participate in overload resolution unless each type in UTypes is implicitly convertible to its corresponding type in Types. template tuple(const pair& u);
20
Requires: sizeof...(Types) == 2. is_constructible::value is true for the first type T0 in Types and is_constructible::value is true for the second type T1 in Types.
21
Effects: Constructs the first element with u.first and the second element with u.second.
22
Remark: This constructor shall not participate in overload resolution unless const U1& is implicitly convertible to T0 and const U2& is implicitly convertible to T1 . template tuple(pair&& u);
23
Requires: sizeof...(Types) == 2. is_constructible::value is true for the first type T0 in Types and is_constructible::value is true for the second type T1 in Types.
24
Effects: Initializes the first element with std::forward(u.first) and the second element with std::forward(u.second).
25
Remark: This constructor shall not participate in overload resolution unless U1 is implicitly convertible to T0 and U2 is implicitly convertible to T1 . template tuple(allocator_arg_t, const Alloc& a); template tuple(allocator_arg_t, const Alloc& a, const Types&...); template tuple(allocator_arg_t, const Alloc& a, UTypes&&...); template tuple(allocator_arg_t, const Alloc& a, const tuple&);
§ 20.4.2.1
484
c ISO/IEC
N3376
template tuple(allocator_arg_t, const Alloc& a, tuple&&); template tuple(allocator_arg_t, const Alloc& a, const tuple&); template tuple(allocator_arg_t, const Alloc& a, tuple&&); template tuple(allocator_arg_t, const Alloc& a, const pair&); template tuple(allocator_arg_t, const Alloc& a, pair&&); 26
Requires: Alloc shall meet the requirements for an Allocator (17.6.3.5).
27
Effects: Equivalent to the preceding constructors except that each element is constructed with usesallocator construction (20.6.7.2). 20.4.2.2
1
Assignment
[tuple.assign]
For each tuple assignment operator, an exception is thrown only if the assignment of one of the types in Types throws an exception. In the function descriptions that follow, let i be in the range [0,sizeof... (Types)) in order, Ti be the ith type in Types, and Ui be the ith type in a template parameter pack named UTypes, where indexing is zero-based. tuple& operator=(const tuple& u);
2
Requires: is_copy_assignable<Ti >::value is true for all i.
3
Effects: Assigns each element of u to the corresponding element of *this.
4
Returns: *this tuple& operator=(tuple&& u) noexcept(see below );
5
Remark: The expression inside noexcept is equivalent to the logical and of the following expressions: is_nothrow_move_assignable<Ti >::value
where Ti is the ith type in Types. 6
Requires: is_move_assignable<Ti >::value is true for all i.
7
Effects: For all i, assigns std::forward<Ti >(get(u)) to get(*this).
8
Returns: *this. template tuple& operator=(const tuple& u);
9
Requires: sizeof...(Types) == sizeof...(UTypes) and is_assignable<Ti &, const Ui &>::value is true for all i.
10
Effects: Assigns each element of u to the corresponding element of *this.
11
Returns: *this template tuple& operator=(tuple&& u);
§ 20.4.2.2
485
c ISO/IEC
N3376
12
Requires: is_assignable<Ti&, Ui&&>::value == true for all i. sizeof...(Types) == sizeof...(UTypes).
13
Effects: For all i, assigns std::forward(get(u)) to get(*this).
14
Returns: *this. template tuple& operator=(const pair& u);
15
Requires: sizeof...(Types) == 2. is_assignable::value is true for the first type T0 in Types and is_assignable::value is true for the second type T1 in Types.
16
Effects: Assigns u.first to the first element of *this and u.second to the second element of *this.
17
Returns: *this template tuple& operator=(pair&& u);
18
Requires: sizeof...(Types) == 2. is_assignable::value is true for the first type T0 in Types and is_assignable::value is true for the second type T1 in Types.
19
Effects: Assigns std::forward(u.first) to the first element of *this and std::forward(u.second) to the second element of *this.
20
Returns: *this. 20.4.2.3
swap
[tuple.swap]
void swap(tuple& rhs) noexcept(see below ); 1
Remark: The expression inside noexcept is equivalent to the logical and of the following expressions: noexcept(swap(declval<Ti &>>(), declval<Ti &>()))
where T1 is the ith type in Types. 2
Requires: Each element in *this shall be swappable with (17.6.3.2) the corresponding element in rhs.
3
Effects: Calls swap for each element in *this and its corresponding element in rhs.
4
Throws: Nothing unless one of the element-wise swap calls throws an exception. 20.4.2.4
1
Tuple creation functions
[tuple.creation]
In the function descriptions that follow, let i be in the range [0,sizeof...(TTypes)) in order and let Ti be the ith type in a template parameter pack named TTypes; let j be in the range [0,sizeof...(UTypes)) in order and Uj be the j th type in a template parameter pack named UTypes, where indexing is zero-based. template tuple make_tuple(Types&&... t);
2
Let Ui be decay<Ti >::type for each Ti in Types. Then each Vi in VTypes is X& if Ui equals reference_wrapper<X>, otherwise Vi is Ui .
3
Returns: tuple(std::forward(t)...).
4
[ Example: int i; float j; make_tuple(1, ref(i), cref(j))
creates a tuple of type § 20.4.2.4
486
c ISO/IEC
N3376
tuple
— end example ] template tuple forward_as_tuple(Types&&... t) noexcept; 5
Effects: Constructs a tuple of references to the arguments in t suitable for forwarding as arguments to a function. Because the result may contain references to temporary variables, a program shall ensure that the return value of this function does not outlive any of its arguments. (e.g., the program should typically not store the result in a named variable).
6
Returns: tuple(std::forward(t)...) template tuple tie(Types&... t) noexcept;
7
Returns: tuple(t...). When an argument in t is ignore, assigning any value to the corresponding tuple element has no effect.
8
[ Example: tie functions allow one to create tuples that unpack tuples into variables. ignore can be used for elements that are not needed: int i; std::string s; tie(i, ignore, s) = make_tuple(42, 3.14, "C++"); // i == 42, s == "C++"
— end example ] template tuple tuple_cat(Tuples&&... tpls); 9
In the following paragraphs, let Ti be the ith type in Tuples, Ui be remove_reference<Ti>::type, and tpi be the ith parameter in the function parameter pack tpls, where all indexing is zero-based.
10
Requires: For all i, Ui shall be the type cvi tuple, where cvi is the (possibly empty) ith cv-qualifier-seq and Argsi is the parameter pack representing the element types in Ui . Let Aik be the ki th type in Argsi . For all Aik the following requirements shall be satisfied: If Ti is deduced as an lvalue reference type, then is_constructible::value == true, otherwise is_constructible::value == true.
11
Remarks: The types in Ctypes shall be equal to the ordered sequence of the extended types Args0 ..., Args1 ..., ... Argsn−1 ..., where n is equal to sizeof...(Tuples). Let ei ... be the ith ordered sequence of tuple elements of the resulting tuple object corresponding to the type sequence Argsi .
12
Returns: A tuple object constructed by initializing the ki th type element eik in ei ... with get(std::forward<Ti >(tpi )) for each valid ki and each group ei in order.
13
Note: An implementation may support additional types in the parameter pack Tuples that support the tuple-like protocol, such as pair and array.
§ 20.4.2.4
487
c ISO/IEC
20.4.2.5
Tuple helper classes
N3376
[tuple.helper]
template class tuple_size : public integral_constant<size_t, sizeof...(Types)> { }; template <size_t I, class... Types> class tuple_element { public: typedef TI type; }; 1
Requires: I < sizeof...(Types). The program is ill-formed if I is out of bounds.
2
Type: TI is the type of the Ith element of Types, where indexing is zero-based. template class tuple_size; template class tuple_size; template class tuple_size;
3
Let TS denote tuple_size of the cv-unqualified type T. Then each of the three templates shall meet the UnaryTypeTrait requirements (20.9.1) with a BaseCharacteristic of integral_constant::type, TS::value>
template <size_t I, class T> class tuple_element; template <size_t I, class T> class tuple_element; template <size_t I, class T> class tuple_element;
Let TE denote tuple_element of the cv-unqualified type T. Then each of the three templates shall meet the TransformationTrait requirements (20.9.1) with a member typedef type that names the following type: — for the first specialization, add_const::type, — for the second specialization, add_volatile::type, and — for the third specialization, add_cv::type. 20.4.2.6
Element access
[tuple.elem]
template <size_t I, class... Types> typename tuple_element::type& get(tuple& t) noexcept; 1
Requires: I < sizeof...(Types). The program is ill-formed if I is out of bounds.
2
Returns: A reference to the Ith element of t, where indexing is zero-based. template <size_t I, class... types> typename tuple_element::type&& get(tuple&& t) noexcept;
3
Effects: Equivalent to return std::forward(get(t));
4
Note: if a T in Types is some reference type X&, the return type is X&, not X&&. However, if the element type is a non-reference type T, the return type is T&&.
§ 20.4.2.6
488
c ISO/IEC
N3376
template <size_t I, class... Types> typename tuple_element::type const& get(const tuple& t) noexcept; 5
Requires: I < sizeof...(Types). The program is ill-formed if I is out of bounds.
6
Returns: A const reference to the Ith element of t, where indexing is zero-based.
7
[ Note: Constness is shallow. If a T in Types is some reference type X&, the return type is X&, not const X&. However, if the element type is non-reference type T, the return type is const T&. This is consistent with how constness is defined to work for member variables of reference type. — end note ]
8
[ Note: The reason get is a nonmember function is that if this functionality had been provided as a member function, code where the type depended on a template parameter would have required using the template keyword. — end note ] 20.4.2.7
Relational operators
[tuple.rel]
template bool operator==(const tuple& t, const tuple& u); 1
Requires: For all i, where 0 class bitset; // 20.5.4 bitset operators: template <size_t N> bitset operator&(const bitset&, const bitset&) noexcept; template <size_t N> bitset operator|(const bitset&, const bitset&) noexcept; template <size_t N> bitset operator^(const bitset&, const bitset&) noexcept; template basic_istream& operator>>(basic_istream& is, bitset& x); template basic_ostream& operator struct hash; } 2
3
4
The class template bitsetdescribes an object that can store a sequence consisting of a fixed number of bits, N. Each bit represents either the value zero (reset) or one (set). To toggle a bit is to change the value zero to one, or the value one to zero. Each bit has a non-negative position pos. When converting between an object of class bitset and a value of some integral type, bit position pos corresponds to the bit value 1 =(size_t pos) noexcept;
9
Effects: Replaces each bit at position I in *this with a value determined as follows: — If pos >= N - I, the new value is zero; — If pos < N - I, the new value is the previous value of the bit at position I + pos.
10
Returns: *this. bitset& set() noexcept;
11
Effects: Sets all bits in *this.
12
Returns: *this. bitset& set(size_t pos, bool val = true);
13
Requires: pos is valid
14
Throws: out_of_range if pos does not correspond to a valid bit position.
15
Effects: Stores a new value in the bit at position pos in *this. If val is nonzero, the stored value is one, otherwise it is zero.
16
Returns: *this. bitset& reset() noexcept;
17
Effects: Resets all bits in *this.
18
Returns: *this. bitset& reset(size_t pos);
19
Requires: pos is valid
20
Throws: out_of_range if pos does not correspond to a valid bit position.
21
Effects: Resets the bit at position pos in *this.
22
Returns: *this. bitset operator~() const noexcept;
23
Effects: Constructs an object x of class bitset and initializes it with *this.
24
Returns: x.flip(). § 20.5.2
494
c ISO/IEC
N3376
bitset& flip() noexcept; 25
Effects: Toggles all bits in *this.
26
Returns: *this. bitset& flip(size_t pos);
27
Requires: pos is valid
28
Throws: out_of_range if pos does not correspond to a valid bit position.
29
Effects: Toggles the bit at position pos in *this.
30
Returns: *this. unsigned long to_ulong() const;
31
Throws: overflow_error if the integral value x corresponding to the bits in *this cannot be represented as type unsigned long.
32
Returns: x. unsigned long long to_ullong() const;
33
Throws: overflow_error if the integral value x corresponding to the bits in *this cannot be represented as type unsigned long long.
34
Returns: x. template basic_string to_string(charT zero = charT(’0’), charT one = charT(’1’)) const;
35
Effects: Constructs a string object of the appropriate type and initializes it to a string of length N characters. Each character is determined by the value of its corresponding bit position in *this. Character position N - 1 corresponds to bit position zero. Subsequent decreasing character positions correspond to increasing bit positions. Bit value zero becomes the character zero, bit value one becomes the character one.
36
Returns: The created object. size_t count() const noexcept;
37
Returns: A count of the number of bits set in *this. constexpr size_t size() noexcept;
38
Returns: N. bool operator==(const bitset& rhs) const noexcept;
§ 20.5.2
495
c ISO/IEC
39
N3376
Returns: true if the value of each bit in *this equals the value of the corresponding bit in rhs. bool operator!=(const bitset& rhs) const noexcept;
40
Returns: true if !(*this == rhs). bool test(size_t pos) const;
41
Requires: pos is valid
42
Throws: out_of_range if pos does not correspond to a valid bit position.
43
Returns: true if the bit at position pos in *this has the value one. bool all() const noexcept;
44
Returns: count() == size() bool any() const noexcept;
45
Returns: count() != 0 bool none() const noexcept;
46
Returns: count() == 0 bitset operator= pos. constexpr bool operator[](size_t pos);
49
Requires: pos shall be valid.
50
Returns: true if the bit at position pos in *this has the value one, otherwise false.
51
Throws: Nothing. bitset::reference operator[](size_t pos);
52
Requires: pos shall be valid.
53
Returns: An object of type bitset::reference such that (*this)[pos] == this->test(pos), and such that (*this)[pos] = val is equivalent to this->set(pos, val).
54
Throws: Nothing.
55
Remark: For the purpose of determining the presence of a data race (1.10), any access or update through the resulting reference potentially accesses or modifies, respectively, the entire underlying bitset. § 20.5.2
496
c ISO/IEC
20.5.3
bitset hash support
N3376
[bitset.hash]
template <size_t N> struct hash; 1
Requires: the template specialization shall meet the requirements of class template hash (20.8.12).
20.5.4
bitset operators
[bitset.operators]
bitset operator&(const bitset& lhs, const bitset& rhs) noexcept; 1
Returns: bitset(lhs) &= rhs. bitset operator|(const bitset& lhs, const bitset& rhs) noexcept;
2
Returns: bitset(lhs) |= rhs. bitset operator^(const bitset& lhs, const bitset& rhs) noexcept;
3
Returns: bitset(lhs) ˆ= rhs. template basic_istream& operator>>(basic_istream& is, bitset& x);
4
A formatted input function (27.7.2.2).
5
Effects: Extracts up to N characters from is. Stores these characters in a temporary object str of type basic_string, then evaluates the expression x = bitset(str). Characters are extracted and stored until any of the following occurs: — N characters have been extracted and stored; — end-of-file occurs on the input sequence; — the next input character is neither is.widen(’0’) nor is.widen(’1’) (in which case the input character is not extracted).
6
If no characters are stored in str, calls is.setstate(ios_base::failbit) (which may throw ios_base::failure (27.5.5.4)).
7
Returns: is. template basic_ostream& operator synopsis
[memory.syn]
The header <memory> defines several types and function templates that describe properties of pointers and pointer-like types, manage memory for containers and other template types, and construct multiple objects in uninitialized memory buffers (20.6.3–20.6.12). The header also defines the templates unique_ptr, shared_ptr, weak_ptr, and various template functions that operate on objects of these types (20.7). namespace std { // 20.6.3, pointer traits template struct pointer_traits; template struct pointer_traits; // 20.6.4, pointer safety enum class pointer_safety { relaxed, preferred, strict }; void declare_reachable(void *p); template T *undeclare_reachable(T *p); void declare_no_pointers(char *p, size_t n); void undeclare_no_pointers(char *p, size_t n); pointer_safety get_pointer_safety() noexcept; // 20.6.5, pointer alignment function void *align(std::size_t alignment, std::size_t size, void *&ptr, std::size_t& space); // 20.6.6, allocator argument tag struct allocator_arg_t { }; constexpr allocator_arg_t allocator_arg = allocator_arg_t(); // 20.6.7, uses_allocator template struct uses_allocator; // 20.6.8, allocator traits template struct allocator_traits; // 20.6.9, the default allocator: template class allocator; template class allocator; template bool operator==(const allocator&, const allocator&) noexcept; template bool operator!=(const allocator&, const allocator&) noexcept; // 20.6.10, raw storage iterator: template class raw_storage_iterator; // 20.6.11, temporary buffers: template pair get_temporary_buffer(ptrdiff_t n) noexcept; template void return_temporary_buffer(T* p);
§ 20.6.2
498
c ISO/IEC
N3376
// 20.6.12, specialized algorithms: template T* addressof(T& r) noexcept; template ForwardIterator uninitialized_copy(InputIterator first, InputIterator last, ForwardIterator result); template ForwardIterator uninitialized_copy_n(InputIterator first, Size n, ForwardIterator result); template void uninitialized_fill(ForwardIterator first, ForwardIterator last, const T& x); template ForwardIterator uninitialized_fill_n(ForwardIterator first, Size n, const T& x); // 20.7.1 template template template template
class template unique_ptr: struct default_delete; struct default_delete; class unique_ptr; class unique_ptr;
template bool operator==(const unique_ptr& x, const unique_ptr& y); template bool operator!=(const unique_ptr& x, const unique_ptr& y); template bool operator=(const unique_ptr& x, const unique_ptr& y); template bool operator==(const unique_ptr& x, nullptr_t) noexcept; template bool operator==(nullptr_t, const unique_ptr& y) noexcept; template bool operator!=(const unique_ptr& x, nullptr_t) noexcept; template bool operator!=(nullptr_t, const unique_ptr& y) noexcept; template bool operator=(nullptr_t, const unique_ptr& y); // 20.7.2.1, class bad_weak_ptr: class bad_weak_ptr; // 20.7.2.2, class template shared_ptr: template class shared_ptr; // 20.7.2.2.7, shared_ptr comparisons: template bool operator==(shared_ptr const& a, shared_ptr const& b) noexcept; template bool operator!=(shared_ptr const& a, shared_ptr const& b) noexcept; template bool operator(shared_ptr const& a, shared_ptr const& b) noexcept; template bool operator=(shared_ptr const& a, shared_ptr const& b) noexcept; template bool operator==(const shared_ptr& x, nullptr_t) noexcept; template bool operator==(nullptr_t, const shared_ptr& y) noexcept; template bool operator!=(const shared_ptr& x, nullptr_t) noexcept; template bool operator!=(nullptr_t, const shared_ptr& y) noexcept; template bool operator=(nullptr_t, const shared_ptr& y) noexcept; // 20.7.2.2.8, shared_ptr specialized algorithms: template void swap(shared_ptr& a, shared_ptr& b) noexcept; // 20.7.2.2.9, shared_ptr casts: template shared_ptr static_pointer_cast(shared_ptr const& r) noexcept; template
§ 20.6.2
500
c ISO/IEC
N3376
shared_ptr dynamic_pointer_cast(shared_ptr const& r) noexcept; template shared_ptr const_pointer_cast(shared_ptr const& r) noexcept; // 20.7.2.2.10, shared_ptr get_deleter: template D* get_deleter(shared_ptr const& p) noexcept; // 20.7.2.2.11, shared_ptr I/O: template basic_ostream<E, T>& operator& os, shared_ptr const& p); // 20.7.2.3, class template weak_ptr: template class weak_ptr; // 20.7.2.3.6, weak_ptr specialized algorithms: template void swap(weak_ptr& a, weak_ptr& b) noexcept; // 20.7.2.3.7, class template owner_less: template class owner_less; // 20.7.2.4, class template enable_shared_from_this: template class enable_shared_from_this; // 20.7.2.5, shared_ptr atomic access: template bool atomic_is_lock_free(const shared_ptr* p); template shared_ptr atomic_load(const shared_ptr* p); template shared_ptr atomic_load_explicit(const shared_ptr* p, memory_order mo); template void atomic_store(shared_ptr* p, shared_ptr r); template void atomic_store_explicit(shared_ptr* p, shared_ptr r, memory_order mo); template shared_ptr atomic_exchange(shared_ptr* p, shared_ptr r); template shared_ptr atomic_exchange_explicit(shared_ptr* p, shared_ptr r, memory_order mo); template bool atomic_compare_exchange_weak( shared_ptr* p, shared_ptr* v, shared_ptr w); template bool atomic_compare_exchange_strong( shared_ptr* p, shared_ptr* v, shared_ptr w); template bool atomic_compare_exchange_weak_explicit( shared_ptr* p, shared_ptr* v, shared_ptr w, memory_order success, memory_order failure); template bool atomic_compare_exchange_strong_explicit(
§ 20.6.2
501
c ISO/IEC
N3376
shared_ptr* p, shared_ptr* v, shared_ptr w, memory_order success, memory_order failure); // 20.7.2.6 hash support template struct hash; template struct hash; template struct hash<shared_ptr >; // D.10, auto_ptr (deprecated) template class auto_ptr; }
20.6.3 1
Pointer traits
[pointer.traits]
The class template pointer_traits supplies a uniform interface to certain attributes of pointer-like types. namespace std { template struct pointer_traits { typedef Ptr pointer; typedef see below element_type; typedef see below difference_type; template using rebind = see below ; static pointer pointer_to(see below r); }; template struct pointer_traits { typedef T* pointer; typedef T element_type; typedef ptrdiff_t difference_type; template using rebind = U*; static pointer pointer_to(see below r) noexcept; }; }
20.6.3.1
Pointer traits member types
[pointer.traits.types]
typedef see below element_type; 1
Type: Ptr::element_type if such a type exists; otherwise, T if Ptr is a class template instantiation of the form SomePointer, where Args is zero or more type arguments; otherwise, the specialization is ill-formed. typedef see below difference_type;
2
Type: Ptr::difference_type if such a type exists; otherwise, std::ptrdiff_t. template using rebind = see below ;
3
Alias template: Ptr::rebind if such a type exists; otherwise, SomePointer if Ptr is a class template instantiation of the form SomePointer, where Args is zero or more type arguments; otherwise, the instantiation of rebind is ill-formed.
§ 20.6.3.1
502
c ISO/IEC
20.6.3.2
Pointer traits member functions
N3376
[pointer.traits.functions]
static pointer pointer_traits::pointer_to(see below r); static pointer pointer_traits::pointer_to(see below r) noexcept;
Remark: if element_type is (possibly cv-qualified) void, the type of r is unspecified; otherwise, it is element_type&. Returns: The first member function returns a dereferenceable pointer to r obtained by calling Ptr::pointer_to(r); an instantiation of this function is ill-formed if Ptr does not have a matching pointer_to static member function. The second member function returns std::addressof(r).
20.6.4 1
Pointer safety
[util.dynamic.safety]
A complete object is declared reachable while the number of calls to declare_reachable with an argument referencing the object exceeds the number of calls to undeclare_reachable with an argument referencing the object. void declare_reachable(void *p);
2
Requires: p shall be a safely-derived pointer (3.7.4.3) or a null pointer value.
3
Effects: If p is not null, the complete object referenced by p is subsequently declared reachable (3.7.4.3).
4
Throws: May throw std::bad_alloc if the system cannot allocate additional memory that may be required to track objects declared reachable. template T *undeclare_reachable(T *p);
5
Requires: If p is not null, the complete object referenced by p shall have been previously declared reachable, and shall be live (3.8) from the time of the call until the last undeclare_reachable(p) call on the object.
6
Returns: A safely derived copy of p which shall compare equal to p.
7
Throws: Nothing.
8
[ Note: It is expected that calls to declare_reachable(p) will consume a small amount of memory in addition to that occupied by the referenced object until the matching call to undeclare_reachable(p) is encountered. Long running programs should arrange that calls are matched. — end note ] void declare_no_pointers(char *p, size_t n);
9
Requires: No bytes in the specified range are currently registered with declare_no_pointers(). If the specified range is in an allocated object, then it must be entirely within a single allocated object. The object must be live until the corresponding undeclare_no_pointers() call. [ Note: In a garbage-collecting implementation, the fact that a region in an object is registered with declare_no_pointers() should not prevent the object from being collected. — end note ]
10
Effects: The n bytes starting at p no longer contain traceable pointer locations, independent of their type. Hence pointers located there may not be dereferenced if the object they point to was created by global operator new and not previously declared reachable. [ Note: This may be used to inform a garbage collector or leak detector that this region of memory need not be traced. — end note ]
11
Throws: Nothing.
12
[ Note: Under some conditions implementations may need to allocate memory. However, the request can be ignored if memory allocation fails. — end note ]
§ 20.6.4
503
c ISO/IEC
N3376
void undeclare_no_pointers(char *p, size_t n); 13
Requires: The same range must previously have been passed to declare_no_pointers().
14
Effects: Unregisters a range registered with declare_no_pointers() for destruction. It must be called before the lifetime of the object ends.
15
Throws: Nothing. pointer_safety get_pointer_safety() noexcept;
16
Returns: pointer_safety::strict if the implementation has strict pointer safety (3.7.4.3). It is implementation defined whether get_pointer_safety returns pointer_safety::relaxed or pointer_safety::preferred if the implementation has relaxed pointer safety.228
20.6.5
Align
[ptr.align]
void *align(std::size_t alignment, std::size_t size, void *&ptr, std::size_t& space); 1
Effects: If it is possible to fit size bytes of storage aligned by alignment into the buffer pointed to by ptr with length space, the function updates ptr to point to the first possible address of such storage and decreases space by the number of bytes used for alignment. Otherwise, the function does nothing.
2
Requires: — alignment shall be a fundamental alignment value or an extended alignment value supported by the implementation in this context — ptr shall point to contiguous storage of at least space bytes
3
Returns: A null pointer if the requested aligned buffer would not fit into the available space, otherwise the adjusted value of ptr.
4
[ Note: The function updates its ptr and space arguments so that it can be called repeatedly with possibly different alignment and size arguments for the same buffer.
20.6.6
Allocator argument tag
[allocator.tag]
namespace std { struct allocator_arg_t { }; constexpr allocator_arg_t allocator_arg = allocator_arg_t(); } 1
The allocator_arg_t struct is an empty structure type used as a unique type to disambiguate constructor and function overloading. Specifically, several types (see tuple 20.4) have constructors with allocator_arg_t as the first argument, immediately followed by an argument of a type that satisfies the Allocator requirements (17.6.3.5).
20.6.7 20.6.7.1
uses_allocator uses_allocator trait
[allocator.uses] [allocator.uses.trait]
template struct uses_allocator; 228) pointer_safety::preferred might be returned to indicate that a leak detector is running so that the program can avoid spurious leak reports.
§ 20.6.7.1
504
c ISO/IEC
1
N3376
Remark: automatically detects whether T has a nested allocator_type that is convertible from Alloc. Meets the BinaryTypeTrait requirements (20.9.1). The implementation shall provide a definition that is derived from true_type if a type T::allocator_type exists and is_convertible::value != false, otherwise it shall be derived from false_type. A program may specialize this template to derive from true_type for a user-defined type T that does not have a nested allocator_type but nonetheless can be constructed with an allocator where either: — the first argument of a constructor has type allocator_arg_t and the second argument has type Alloc or — the last argument of a constructor has type Alloc. 20.6.7.2
1
uses-allocator construction
[allocator.uses.construction]
Uses-allocator construction with allocator Alloc refers to the construction of an object obj of type T, using constructor arguments v1, v2, ..., vN of types V1, V2, ..., VN, respectively, and an allocator alloc of type Alloc, according to the following rules: — if uses_allocator::value is false and is_constructible::value is true, then obj is initialized as obj(v1, v2, ..., vN); — otherwise, if uses_allocator::value is true and is_constructible::value is true, then obj is initialized as obj(allocator_arg, alloc, v1, v2, ..., vN); — otherwise, if uses_allocator::value is true and is_constructible::value is true, then obj is initialized as obj(v1, v2, ..., vN, alloc); — otherwise, the request for uses-allocator construction is ill-formed. [ Note: An error will result if uses_allocator::value is true but the specific constructor does not take an allocator. This definition prevents a silent failure to pass the allocator to an element. — end note ]
20.6.8 1
Allocator traits
[allocator.traits]
The class template allocator_traits supplies a uniform interface to all allocator types. An allocator cannot be a non-class type, however, even if allocator_traits supplies the entire required interface. [ Note: Thus, it is always possible to create a derived class from an allocator. — end note ] namespace std { template struct allocator_traits { typedef Alloc allocator_type; typedef typename Alloc::value_type value_type; typedef typedef typedef typedef
see see see see
below below below below
pointer; const_pointer; void_pointer; const_void_pointer;
typedef see below difference_type; typedef see below size_type; typedef see below propagate_on_container_copy_assignment; typedef see below propagate_on_container_move_assignment; typedef see below propagate_on_container_swap; template using rebind_alloc = see below ;
§ 20.6.8
505
c ISO/IEC
N3376
template using rebind_traits = allocator_traits; static pointer allocate(Alloc& a, size_type n); static pointer allocate(Alloc& a, size_type n, const_void_pointer hint); static void deallocate(Alloc& a, pointer p, size_type n); template static void construct(Alloc& a, T* p, Args&&... args); template static void destroy(Alloc& a, T* p); static size_type max_size(const Alloc& a); static Alloc select_on_container_copy_construction(const Alloc& rhs); }; }
20.6.8.1
Allocator traits member types
[allocator.traits.types]
typedef see below pointer; 1
Type: Alloc::pointer if such a type exists; otherwise, value_type*. typedef see below const_pointer;
2
Type: Alloc::const_pointer if such a type exists; otherwise, pointer_traits<pointer>::rebind< const value_type>. typedef see below void_pointer;
3
Type: Alloc::void_pointer if such a type exists; otherwise, pointer_traits<pointer>::rebind< void>. typedef see below const_void_pointer;
4
Type: Alloc::const_void_pointer if such a type exists; otherwise, pointer_traits<pointer>:: rebind. typedef see below difference_type;
5
Type: Alloc::difference_type if such a type exists; otherwise, pointer_traits<pointer>::difference_type. typedef see below size_type;
6
Type: Alloc::size_type if such a type exists; otherwise, make_unsigned::type. typedef see below propagate_on_container_copy_assignment;
§ 20.6.8.1
506
c ISO/IEC
7
N3376
Type: Alloc::propagate_on_container_copy_assignment if such a type exists, otherwise false_type. typedef see below propagate_on_container_move_assignment;
8
Type: Alloc::propagate_on_container_move_assignment if such a type exists, otherwise false_type. typedef see below propagate_on_container_swap;
9
Type: Alloc::propagate_on_container_swap if such a type exists, otherwise false_type. template using rebind_alloc = see below ;
10
Alias template: Alloc::rebind::other if such a type exists; otherwise, Alloc if Alloc is a class template instantiation of the form Alloc, where Args is zero or more type arguments; otherwise, the instantiation of rebind_alloc is ill-formed. 20.6.8.2
Allocator traits static member functions
[allocator.traits.members]
static pointer allocate(Alloc& a, size_type n); 1
Returns: a.allocate(n). static pointer allocate(Alloc& a, size_type n, const_void_pointer hint);
2
Returns: a.allocate(n, hint) if that expression is well-formed; otherwise, a.allocate(n). static void deallocate(Alloc& a, pointer p, size_type n);
3
Effects: calls a.deallocate(p, n).
4
Throws: Nothing. template static void construct(Alloc& a, T* p, Args&&... args);
5
Effects: calls a.construct(p, std::forward(args)...) if that call is well-formed; otherwise, invokes ::new (static_cast(p)) T(std::forward(args)...). template static void destroy(Alloc& a, T* p);
6
Effects: calls a.destroy(p) if that call is well-formed; otherwise, invokes p->˜T(). static size_type max_size(Alloc& a);
7
Returns: a.max_size() if that expression is well-formed; otherwise, numeric_limits<size_type>:: max(). static Alloc select_on_container_copy_construction(const Alloc& rhs);
8
Returns: rhs.select_on_container_copy_construction() if that expression is well-formed; otherwise, rhs. § 20.6.8.2
507
c ISO/IEC
20.6.9
The default allocator
N3376
[default.allocator]
namespace std { template class allocator; // specialize for void: template class allocator { public: typedef void* pointer; typedef const void* const_pointer; // reference-to-void members are impossible. typedef void value_type; template struct rebind { typedef allocator other; }; }; template class allocator { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; template struct rebind { typedef allocator other; }; allocator() noexcept; allocator(const allocator&) noexcept; template allocator(const allocator&) noexcept; ~allocator(); pointer address(reference x) const noexcept; const_pointer address(const_reference x) const noexcept; pointer allocate( size_type, allocator::const_pointer hint = 0); void deallocate(pointer p, size_type n); size_type max_size() const noexcept; template void construct(U* p, Args&&... args); template void destroy(U* p); }; }
20.6.9.1 1
allocator members
[allocator.members]
Except for the destructor, member functions of the default allocator shall not introduce data races (1.10) as a result of concurrent calls to those member functions from different threads. Calls to these functions that allocate or deallocate a particular unit of storage shall occur in a single total order, and each such deallocation call shall happen before the next allocation (if any) in this order. pointer address(reference x) const noexcept;
2
Returns: The actual address of the object referenced by x, even in the presence of an overloaded operator&. § 20.6.9.1
508
c ISO/IEC
N3376
const_pointer address(const_reference x) const noexcept; 3
Returns: The actual address of the object referenced by x, even in the presence of an overloaded operator&. pointer allocate(size_type n, allocator::const_pointer hint = 0);
4
[ Note: In a container member function, the address of an adjacent element is often a good choice to pass for the hint argument. — end note ]
5
Returns: A pointer to the initial element of an array of storage of size n * sizeof(T), aligned appropriately for objects of type T. It is implementation-defined whether over-aligned types are supported (3.11).
6
Remark: the storage is obtained by calling ::operator new(std::size_t) (18.6.1), but it is unspecified when or how often this function is called. The use of hint is unspecified, but intended as an aid to locality if an implementation so desires.
7
Throws: bad_alloc if the storage cannot be obtained. void deallocate(pointer p, size_type n);
8
Requires: p shall be a pointer value obtained from allocate(). n shall equal the value passed as the first argument to the invocation of allocate which returned p.
9
Effects: Deallocates the storage referenced by p .
10
Remarks: Uses ::operator delete(void*) (18.6.1), but it is unspecified when this function is called. size_type max_size() const noexcept;
11
Returns: The largest value N for which the call allocate(N,0) might succeed. template void construct(U* p, Args&&... args);
12
Effects: ::new((void *)p) U(std::forward(args)...) template void destroy(U* p);
13
Effects: p->˜U() 20.6.9.2
allocator globals
[allocator.globals]
template bool operator==(const allocator&, const allocator&) noexcept; 1
Returns: true. template bool operator!=(const allocator&, const allocator&) noexcept;
2
Returns: false. § 20.6.9.2
509
c ISO/IEC
20.6.10 1
N3376
Raw storage iterator
[storage.iterator]
raw_storage_iterator is provided to enable algorithms to store their results into uninitialized memory. The formal template parameter OutputIterator is required to have its operator* return an object for which operator& is defined and returns a pointer to T, and is also required to satisfy the requirements of an output iterator (24.2.4). namespace std { template class raw_storage_iterator : public iterator { public: explicit raw_storage_iterator(OutputIterator x); raw_storage_iterator& raw_storage_iterator& raw_storage_iterator& raw_storage_iterator
operator*(); operator=(const T& element); operator++(); operator++(int);
}; } explicit raw_storage_iterator(OutputIterator x); 2
Effects: Initializes the iterator to point to the same value to which x points. raw_storage_iterator& operator*();
3
Returns: *this raw_storage_iterator& operator=(const T& element);
4
Effects: Constructs a value from element at the location to which the iterator points.
5
Returns: A reference to the iterator. raw_storage_iterator& operator++();
6
Effects: Pre-increment: advances the iterator and returns a reference to the updated iterator. raw_storage_iterator operator++(int);
7
Effects: Post-increment: advances the iterator and returns the old value of the iterator.
20.6.11
Temporary buffers
[temporary.buffer]
template pair get_temporary_buffer(ptrdiff_t n) noexcept; 1
Effects: Obtains a pointer to storage sufficient to store up to n adjacent T objects. It is implementationdefined whether over-aligned types are supported (3.11).
2
Returns: A pair containing the buffer’s address and capacity (in the units of sizeof(T)), or a pair of 0 values if no storage can be obtained or if n 0; ++result, ++first, --n) { ::new (static_cast(&*result)) typename iterator_traits::value_type(*first); }
4
Returns: result 20.6.12.3
uninitialized_fill
[uninitialized.fill]
template void uninitialized_fill(ForwardIterator first, ForwardIterator last, const T& x); 1
Effects: for (; first != last; ++first) ::new (static_cast(&*first)) typename iterator_traits::value_type(x);
§ 20.6.12.3
511
c ISO/IEC
20.6.12.4
N3376
[uninitialized.fill.n]
uninitialized_fill_n
template ForwardIterator uninitialized_fill_n(ForwardIterator first, Size n, const T& x); 1
Effects: for (; n--; ++first) ::new (static_cast(&*first)) typename iterator_traits::value_type(x); return first;
20.6.13 1
C library
[c.malloc]
Table 45 describes the header . Table 45 — Header synopsis Type Functions:
2 3
4
5
6
Name(s) calloc malloc free realloc
The contents are the same as the Standard C library header <stdlib.h>, with the following changes: The functions calloc(), malloc(), and realloc() do not attempt to allocate storage by calling ::operator new() (18.6). The function free() does not attempt to deallocate storage by calling ::operator delete(). See also: ISO C Clause 7.11.2. Storage allocated directly with malloc(), calloc(), or realloc() is implicitly declared reachable (see 3.7.4.3) on allocation, ceases to be declared reachable on deallocation, and need not cease to be declared reachable as the result of an undeclare_reachable() call. [ Note: This allows existing C libraries to remain unaffected by restrictions on pointers that are not safely derived, at the expense of providing far fewer garbage collection and leak detection options for malloc()-allocated objects. It also allows malloc() to be implemented with a separate allocation arena, bypassing the normal declare_reachable() implementation. The above functions should never intentionally be used as a replacement for declare_reachable(), and newly written code is strongly encouraged to treat memory allocated with these functions as though it were allocated with operator new. — end note ] Table 46 describes the header . Table 46 — Header synopsis Type Macro: Type: Functions: memcpy
7
Name(s) NULL size_t memchr memcmp memmove memset
The contents are the same as the Standard C library header <string.h>, with the change to memchr() specified in 21.7. See also: ISO C Clause 7.11.2.
§ 20.6.13
512
c ISO/IEC
20.7 20.7.1 1
2
3
4
Smart pointers Class template unique_ptr
N3376
[smartptr] [unique.ptr]
A unique pointer is an object that owns another object and manages that other object through a pointer. More precisely, a unique pointer is an object u that stores a pointer to a second object p and will dispose of p when u is itself destroyed (e.g., when leaving block scope (6.7)). In this context, u is said to own p. The mechanism by which u disposes of p is known as p’s associated deleter, a function object whose correct invocation results in p’s appropriate disposition (typically its deletion). Let the notation u.p denote the pointer stored by u, and let u.d denote the associated deleter. Upon request, u can reset (replace) u.p and u.d with another pointer and deleter, but must properly dispose of its owned object via the associated deleter before such replacement is considered completed. Additionally, u can, upon request, transfer ownership to another unique pointer u2. Upon completion of such a transfer, the following postconditions hold: — u2.p is equal to the pre-transfer u.p, — u.p is equal to nullptr, and — if the pre-transfer u.d maintained state, such state has been transferred to u2.d.
5
6
As in the case of a reset, u2 must properly dispose of its pre-transfer owned object via the pre-transfer associated deleter before the ownership transfer is considered complete. [ Note: A deleter’s state need never be copied, only moved or swapped as ownership is transferred. — end note ] Each object of a type U instantiated from the unique_ptr template specified in this subclause has the strict ownership semantics, specified above, of a unique pointer. In partial satisfaction of these semantics, each such U is MoveConstructible and MoveAssignable, but is not CopyConstructible nor CopyAssignable. The template parameter T of unique_ptr may be an incomplete type. [ Note: The uses of unique_ptr include providing exception safety for dynamically allocated memory, passing ownership of dynamically allocated memory to a function, and returning dynamically allocated memory from a function. — end note ] namespace std { template struct default_delete; template struct default_delete; template class unique_ptr; template class unique_ptr; template void swap(unique_ptr& x, unique_ptr& y) noexcept; template bool operator==(const unique_ptr& x, const unique_ptr& y); template bool operator!=(const unique_ptr& x, const unique_ptr& y); template bool operator=(const unique_ptr& x, const unique_ptr& y); template bool operator==(const unique_ptr& x, nullptr_t) noexcept;
§ 20.7.1
513
c ISO/IEC
N3376
template bool operator==(nullptr_t, const unique_ptr& y) noexcept; template bool operator!=(const unique_ptr& x, nullptr_t) noexcept; template bool operator!=(nullptr_t, const unique_ptr& y) noexcept; template bool operator=(nullptr_t, const unique_ptr& y); }
20.7.1.1 20.7.1.1.1 1
2
Default deleters In general
[unique.ptr.dltr] [unique.ptr.dltr.general]
The class template default_delete serves as the default deleter (destruction policy) for the class template unique_ptr. The template parameter T of default_delete may be an incomplete type. 20.7.1.1.2 default_delete [unique.ptr.dltr.dflt] namespace std { template struct default_delete { constexpr default_delete() noexcept = default; template default_delete(const default_delete&) noexcept; void operator()(T*) const; }; } template default_delete(const default_delete& other) noexcept;
1
Effects: Constructs a default_delete object from another default_delete object.
2
Remarks: This constructor shall not participate in overload resolution unless U* is implicitly convertible to T*. void operator()(T *ptr) const;
3
Effects: calls delete on ptr.
4
Remarks: If T is an incomplete type, the program is ill-formed.
§ 20.7.1.1.2
514
c ISO/IEC
20.7.1.1.3
N3376
default_delete
[unique.ptr.dltr.dflt1]
namespace std { template struct default_delete { constexpr default_delete() noexcept = default; void operator()(T*) const; template void operator()(U*) const = delete; }; } void operator()(T* ptr) const; 1
Effects: calls delete[] on ptr.
2
Remarks: If T is an incomplete type, the program is ill-formed. 20.7.1.2
unique_ptr for single objects
[unique.ptr.single]
namespace std { template class unique_ptr { public: typedef see below pointer; typedef T element_type; typedef D deleter_type; // 20.7.1.2.1, constructors constexpr unique_ptr() noexcept; explicit unique_ptr(pointer p) noexcept; unique_ptr(pointer p, see below d1) noexcept; unique_ptr(pointer p, see below d2) noexcept; unique_ptr(unique_ptr&& u) noexcept; constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { } template unique_ptr(unique_ptr&& u) noexcept; template unique_ptr(auto_ptr&& u) noexcept; // 20.7.1.2.2, destructor ~unique_ptr(); // 20.7.1.2.3, assignment unique_ptr& operator=(unique_ptr&& u) noexcept; template unique_ptr& operator=(unique_ptr&& u) noexcept; unique_ptr& operator=(nullptr_t) noexcept; // 20.7.1.2.4, observers typename add_lvalue_reference::type operator*() const; pointer operator->() const noexcept; pointer get() const noexcept; deleter_type& get_deleter() noexcept; const deleter_type& get_deleter() const noexcept; explicit operator bool() const noexcept; // 20.7.1.2.5 modifiers pointer release() noexcept; void reset(pointer p = pointer()) noexcept;
§ 20.7.1.2
515
c ISO/IEC
N3376
void swap(unique_ptr& u) noexcept; // disable copy from lvalue unique_ptr(const unique_ptr&) = delete; unique_ptr& operator=(const unique_ptr&) = delete; }; } 1
2 3
4
The default type for the template parameter D is default_delete. A client-supplied template argument D shall be a function object type (20.8), lvalue-reference to function, or lvalue-reference to function object type for which, given a value d of type D and a value ptr of type unique_ptr::pointer, the expression d(ptr) is valid and has the effect of disposing of the pointer as appropriate for that deleter. If the deleter’s type D is not a reference type, D shall satisfy the requirements of Destructible (Table 24). If the type remove_reference::type::pointer exists, then unique_ptr::pointer shall be a synonym for remove_reference::type::pointer. Otherwise unique_ptr::pointer shall be a synonym for T*. The type unique_ptr::pointer shall satisfy the requirements of NullablePointer (17.6.3.3). [ Example: Given an allocator type X (17.6.3.5) and letting A be a synonym for allocator_traits<X>, the types A::pointer, A::const_pointer, A::void_pointer, and A::const_void_pointer may be used as unique_ptr::pointer. — end example ] 20.7.1.2.1 unique_ptr constructors [unique.ptr.single.ctor] constexpr unique_ptr() noexcept;
1
Requires: D shall satisfy the requirements of DefaultConstructible (Table 19), and that construction shall not throw an exception.
2
Effects: Constructs a unique_ptr object that owns nothing, value-initializing the stored pointer and the stored deleter.
3
Postconditions: get() == nullptr. get_deleter() returns a reference to the stored deleter.
4
Remarks: If this constructor is instantiated with a pointer type or reference type for the template argument D, the program is ill-formed. explicit unique_ptr(pointer p) noexcept;
5
Requires: D shall satisfy the requirements of DefaultConstructible (Table 19), and that construction shall not throw an exception.
6
Effects: Constructs a unique_ptr which owns p, initializing the stored pointer with p and valueinitializing the stored deleter.
7
Postconditions: get() == p. get_deleter() returns a reference to the stored deleter.
8
Remarks: If this constructor is instantiated with a pointer type or reference type for the template argument D, the program is ill-formed. unique_ptr(pointer p, see below d1) noexcept; unique_ptr(pointer p, see below d2) noexcept;
9
The signature of these constructors depends upon whether D is a reference type. If D is non-reference type A, then the signatures are: unique_ptr(pointer p, const A& d); unique_ptr(pointer p, A&& d);
10
If D is an lvalue-reference type A&, then the signatures are: § 20.7.1.2.1
516
c ISO/IEC
N3376
unique_ptr(pointer p, A& d); unique_ptr(pointer p, A&& d); 11
If D is an lvalue-reference type const A&, then the signatures are: unique_ptr(pointer p, const A& d); unique_ptr(pointer p, const A&& d);
12
Requires: — If D is not an lvalue-reference type then — If d is an lvalue or const rvalue then the first constructor of this pair will be selected. D shall satisfy the requirements of CopyConstructible (Table 21), and the copy constructor of D shall not throw an exception. This unique_ptr will hold a copy of d. — Otherwise, d is a non-const rvalue and the second constructor of this pair will be selected. D shall satisfy the requirements of MoveConstructible (Table 20), and the move constructor of D shall not throw an exception. This unique_ptr will hold a value move constructed from d. — Otherwise D is an lvalue-reference type. d shall be reference-compatible with one of the constructors. If d is an rvalue, it will bind to the second constructor of this pair and the program is ill-formed. [ Note: The diagnostic could be implemented using a static_assert which assures that D is not a reference type. — end note ] Else d is an lvalue and will bind to the first constructor of this pair. The type which D references need not be CopyConstructible nor MoveConstructible. This unique_ptr will hold a D which refers to the lvalue d. [ Note: D may not be an rvalue-reference type. — end note ]
13
Effects: Constructs a unique_ptr object which owns p, initializing the stored pointer with p and initializing the deleter as described above.
14
Postconditions: get() == p. get_deleter() returns a reference to the stored deleter. If D is a reference type then get_deleter() returns a reference to the lvalue d. [ Example: D d; unique_ptr p4(new int, D());
// // // // //
D must be MoveConstructible D must be CopyConstructible p3 holds a reference to d error: rvalue deleter object combined with reference deleter type
— end example ] unique_ptr(unique_ptr&& u) noexcept; 15
Requires: If D is not a reference type, D shall satisfy the requirements of MoveConstructible (Table 20). Construction of the deleter from an rvalue of type D shall not throw an exception.
16
Effects: Constructs a unique_ptr by transferring ownership from u to *this. If D is a reference type, this deleter is copy constructed from u’s deleter; otherwise, this deleter is move constructed from u’s deleter. [ Note: The deleter constructor can be implemented with std::forward. — end note ]
17
Postconditions: get() yields the value u.get() yielded before the construction. get_deleter() returns a reference to the stored deleter that was constructed from u.get_deleter(). If D is a reference type then get_deleter() and u.get_deleter() both reference the same lvalue deleter. § 20.7.1.2.1
517
c ISO/IEC
N3376
template unique_ptr(unique_ptr&& u) noexcept; 18
Requires: If E is not a reference type, construction of the deleter from an rvalue of type E shall be well formed and shall not throw an exception. Otherwise, E is a reference type and construction of the deleter from an lvalue of type E shall be well formed and shall not throw an exception.
19
Remarks: This constructor shall not participate in overload resolution unless: — unique_ptr::pointer is implicitly convertible to pointer, — U is not an array type, and — either D is a reference type and E is the same type as D, or D is not a reference type and E is implicitly convertible to D.
20
Effects: Constructs a unique_ptr by transferring ownership from u to *this. If E is a reference type, this deleter is copy constructed from u’s deleter; otherwise, this deleter is move constructed from u’s deleter. [ Note: The deleter constructor can be implemented with std::forward<E>. — end note ]
21
Postconditions: get() yields the value u.get() yielded before the construction. get_deleter() returns a reference to the stored deleter that was constructed from u.get_deleter(). template unique_ptr(auto_ptr&& u) noexcept;
22
Effects: Constructs a unique_ptr object, initializing the stored pointer with u.release() and valueinitializing the stored deleter.
23
Postconditions: get() yields the value u.get() yielded before the construction. u.get() == nullptr. get_deleter() returns a reference to the stored deleter.
24
Remarks: This constructor shall not participate in overload resolution unless U* is implicitly convertible to T* and D is the same type as default_delete. 20.7.1.2.2
unique_ptr destructor
[unique.ptr.single.dtor]
~unique_ptr(); 1
Requires: The expression get_deleter()(get()) shall be well formed, shall have well-defined behavior, and shall not throw exceptions. [ Note: The use of default_delete requires T to be a complete type. — end note ]
2
Effects: If get() == nullptr there are no effects. Otherwise get_deleter()(get()). 20.7.1.2.3
unique_ptr assignment
[unique.ptr.single.asgn]
unique_ptr& operator=(unique_ptr&& u) noexcept; 1
Requires: If D is not a reference type, D shall satisfy the requirements of MoveAssignable (Table 22) and assignment of the deleter from an rvalue of type D shall not throw an exception. Otherwise, D is a reference type; remove_reference::type shall satisfy the CopyAssignable requirements and assignment of the deleter from an lvalue of type D shall not throw an exception.
2
Effects: Transfers ownership from u to *this as if by calling reset(u.release()) followed by an assignment from std::forward(u.get_deleter()).
3
Returns: *this. template unique_ptr& operator=(unique_ptr&& u) noexcept;
§ 20.7.1.2.3
518
c ISO/IEC
N3376
4
Requires: If E is not a reference type, assignment of the deleter from an rvalue of type E shall be well-formed and shall not throw an exception. Otherwise, E is a reference type and assignment of the deleter from an lvalue of type E shall be well-formed and shall not throw an exception.
5
Remarks: This operator shall not participate in overload resolution unless: — unique_ptr::pointer is implicitly convertible to pointer and — U is not an array type.
6
Effects: Transfers ownership from u to *this as if by calling reset(u.release()) followed by an assignment from std::forward<E>(u.get_deleter()).
7
Returns: *this. unique_ptr& operator=(nullptr_t) noexcept;
8
Effects: reset().
9
Postcondition: get() == nullptr
10
Returns: *this. 20.7.1.2.4
unique_ptr observers
[unique.ptr.single.observers]
typename add_lvalue_reference::type operator*() const; 1
Requires: get() != nullptr.
2
Returns: *get(). pointer operator->() const noexcept;
3
Requires: get() != nullptr.
4
Returns: get().
5
Note: use typically requires that T be a complete type. pointer get() const noexcept;
6
Returns: The stored pointer. deleter_type& get_deleter() noexcept; const deleter_type& get_deleter() const noexcept;
7
Returns: A reference to the stored deleter. explicit operator bool() const noexcept;
8
Returns: get() != nullptr.
§ 20.7.1.2.4
519
c ISO/IEC
20.7.1.2.5
N3376
unique_ptr modifiers
[unique.ptr.single.modifiers]
pointer release() noexcept; 1
Postcondition: get() == nullptr.
2
Returns: The value get() had at the start of the call to release. void reset(pointer p = pointer()) noexcept;
3
Requires: The expression get_deleter()(get()) shall be well formed, shall have well-defined behavior, and shall not throw exceptions.
4
Effects: assigns p to the stored pointer, and then if the old value of the stored pointer, old_p, was not equal to nullptr, calls get_deleter()(old_p). [ Note: The order of these operations is significant because the call to get_deleter() may destroy *this. — end note ]
5
Postconditions: get() == p. [ Note: The postcondition does not hold if the call to get_deleter() destroys *this since this->get() is no longer a valid expression. — end note ] void swap(unique_ptr& u) noexcept;
6
Requires: get_deleter() shall be swappable (17.6.3.2) and shall not throw an exception under swap.
7
Effects: Invokes swap on the stored pointers and on the stored deleters of *this and u. 20.7.1.3
unique_ptr for array objects with a runtime length
[unique.ptr.runtime]
namespace std { template class unique_ptr { public: typedef see below pointer; typedef T element_type; typedef D deleter_type; // 20.7.1.3.1, constructors constexpr unique_ptr() noexcept; explicit unique_ptr(pointer p) noexcept; unique_ptr(pointer p, see below d) noexcept; unique_ptr(pointer p, see below d) noexcept; unique_ptr(unique_ptr&& u) noexcept; constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { } // destructor ~unique_ptr(); // assignment unique_ptr& operator=(unique_ptr&& u) noexcept; unique_ptr& operator=(nullptr_t) noexcept; // 20.7.1.3.2, observers T& operator[](size_t i) const; pointer get() const noexcept; deleter_type& get_deleter() noexcept; const deleter_type& get_deleter() const noexcept; explicit operator bool() const noexcept;
§ 20.7.1.3
520
c ISO/IEC
N3376
// 20.7.1.3.3 modifiers pointer release() noexcept; void reset(pointer p = pointer()) noexcept; void reset(nullptr_t) noexcept; template void reset(U) = delete; void swap(unique_ptr& u) noexcept; // disable copy from lvalue unique_ptr(const unique_ptr&) = delete; unique_ptr& operator=(const unique_ptr&) = delete; }; } 1
A specialization for array types is provided with a slightly altered interface. — Conversions between different types of unique_ptr or to or from the non-array forms of unique_ptr produce an ill-formed program. — Pointers to types derived from T are rejected by the constructors, and by reset. — The observers operator* and operator-> are not provided. — The indexing observer operator[] is provided. — The default deleter will call delete[].
2
3
Descriptions are provided below only for member functions that have behavior different from the primary template. The template argument T shall be a complete type. 20.7.1.3.1
unique_ptr constructors
[unique.ptr.runtime.ctor]
explicit unique_ptr(pointer p) noexcept; unique_ptr(pointer p, see below d) noexcept; unique_ptr(pointer p, see below d) noexcept;
These constructors behave the same as in the primary template except that they do not accept pointer types which are convertible to pointer. [ Note: One implementation technique is to create private templated overloads of these members. — end note ] 20.7.1.3.2
unique_ptr observers
[unique.ptr.runtime.observers]
T& operator[](size_t i) const; 1
Requires: i < the number of elements in the array to which the stored pointer points.
2
Returns: get()[i]. 20.7.1.3.3
unique_ptr modifiers
[unique.ptr.runtime.modifiers]
void reset(pointer p = pointer()) noexcept; void reset(nullptr_t p) noexcept; 1
Effects: If get() == nullptr there are no effects. Otherwise get_deleter()(get()).
2
Postcondition: get() == p.
§ 20.7.1.3.3
521
c ISO/IEC
20.7.1.4
unique_ptr specialized algorithms
N3376
[unique.ptr.special]
template void swap(unique_ptr& x, unique_ptr& y) noexcept; 1
Effects: Calls x.swap(y). template bool operator==(const unique_ptr& x, const unique_ptr& y);
2
Returns: x.get() == y.get(). template bool operator!=(const unique_ptr& x, const unique_ptr& y);
3
Returns: x.get() != y.get(). template bool operator=(const unique_ptr& x, const unique_ptr& y);
9
Returns: !(x < y). template bool operator==(const unique_ptr& x, nullptr_t) noexcept; template bool operator==(nullptr_t, const unique_ptr& x) noexcept;
10
Returns: !x.
§ 20.7.1.4
522
c ISO/IEC
N3376
template bool operator!=(const unique_ptr& x, nullptr_t) noexcept; template bool operator!=(nullptr_t, const unique_ptr& x) noexcept; 11
Returns: (bool)x. template bool operator(nullptr_t, const unique_ptr& x);
14
Returns: The first function template returns nullptr < x. The second function template returns x < nullptr. template bool operator=(nullptr_t, const unique_ptr& x);
16
Returns: The first function template returns !(x < nullptr). The second function template returns !(nullptr < x).
20.7.2 20.7.2.1
Shared-ownership pointers Class bad_weak_ptr
[util.smartptr] [util.smartptr.weakptr]
namespace std { class bad_weak_ptr: public std::exception { public: bad_weak_ptr() noexcept; }; } // namespace std
§ 20.7.2.1
523
c ISO/IEC
1
N3376
An exception of type bad_weak_ptr is thrown by the shared_ptr constructor taking a weak_ptr. bad_weak_ptr() noexcept;
2
Postconditions: what() returns "bad_weak_ptr". 20.7.2.2
1
Class template shared_ptr
[util.smartptr.shared]
The shared_ptr class template stores a pointer, usually obtained via new. shared_ptr implements semantics of shared ownership; the last remaining owner of the pointer is responsible for destroying the object, or otherwise releasing the resources associated with the stored pointer. A shared_ptr object is empty if it does not own a pointer. namespace std { template class shared_ptr { public: typedef T element_type; // 20.7.2.2.1, constructors: constexpr shared_ptr() noexcept; template explicit shared_ptr(Y* p); template shared_ptr(Y* p, D d); template shared_ptr(Y* p, D d, A a); template shared_ptr(nullptr_t p, D d) template shared_ptr(nullptr_t p, D d, A a) template shared_ptr(const shared_ptr& r, T *p) noexcept; shared_ptr(const shared_ptr& r) noexcept; template shared_ptr(const shared_ptr& r) noexcept; shared_ptr(shared_ptr&& r) noexcept; template shared_ptr(shared_ptr&& r) noexcept; template explicit shared_ptr(const weak_ptr& r); template shared_ptr(auto_ptr&& r); template shared_ptr(unique_ptr&& r); constexpr shared_ptr(nullptr_t) : shared_ptr() { } // 20.7.2.2.2, destructor: ~shared_ptr(); // 20.7.2.2.3, assignment: shared_ptr& operator=(const shared_ptr& r) noexcept; template shared_ptr& operator=(const shared_ptr& r) noexcept; shared_ptr& operator=(shared_ptr&& r) noexcept; template shared_ptr& operator=(shared_ptr&& r) noexcept; template shared_ptr& operator=(auto_ptr&& r); template shared_ptr& operator=(unique_ptr&& r); // 20.7.2.2.4, modifiers: void swap(shared_ptr& r) noexcept; void reset() noexcept; template void reset(Y* p); template void reset(Y* p, D d); template void reset(Y* p, D d, A a); // T* T& T*
20.7.2.2.5, observers: get() const noexcept; operator*() const noexcept; operator->() const noexcept;
§ 20.7.2.2
524
c ISO/IEC
N3376
long use_count() const noexcept; bool unique() const noexcept; explicit operator bool() const noexcept; template bool owner_before(shared_ptr const& b) const; template bool owner_before(weak_ptr const& b) const; }; // 20.7.2.2.6, shared_ptr creation template shared_ptr make_shared(Args&&... args); template shared_ptr allocate_shared(const A& a, Args&&... args); // 20.7.2.2.7, shared_ptr comparisons: template bool operator==(const shared_ptr& a, const shared_ptr& b) noexcept; template bool operator!=(const shared_ptr& a, const shared_ptr& b) noexcept; template bool operator(const shared_ptr& a, const shared_ptr& b) noexcept; template bool operator=(const shared_ptr& a, const shared_ptr& b) noexcept; template bool operator==(const shared_ptr& a, nullptr_t) noexcept; template bool operator==(nullptr_t, const shared_ptr& b) noexcept; template bool operator!=(const shared_ptr& a, nullptr_t) noexcept; template bool operator!=(nullptr_t, const shared_ptr& b) noexcept; template bool operator=(nullptr_t, const shared_ptr& b) noexcept; // 20.7.2.2.8, shared_ptr specialized algorithms: template void swap(shared_ptr& a, shared_ptr& b) noexcept; // 20.7.2.2.9, shared_ptr casts:
§ 20.7.2.2
525
c ISO/IEC
N3376
template shared_ptr static_pointer_cast(const shared_ptr& r) noexcept; template shared_ptr dynamic_pointer_cast(const shared_ptr& r) noexcept; template shared_ptr const_pointer_cast(const shared_ptr& r) noexcept; // 20.7.2.2.10, shared_ptr get_deleter: template D* get_deleter(const shared_ptr& p) noexcept; // 20.7.2.2.11, shared_ptr I/O: template basic_ostream<E, T>& operator& os, const shared_ptr& p); } // namespace std 2
3
Specializations of shared_ptr shall be CopyConstructible, CopyAssignable, and LessThanComparable, allowing their use in standard containers. Specializations of shared_ptr shall be convertible to bool, allowing their use in boolean expressions and declarations in conditions. The template parameter T of shared_ptr may be an incomplete type. [ Example: if(shared_ptr<X> px = dynamic_pointer_cast<X>(py)) { // do something with px }
4
— end example ] For purposes of determining the presence of a data race, member functions shall access and modify only the shared_ptr and weak_ptr objects themselves and not objects they refer to. Changes in use_count() do not reflect modifications that can introduce data races. 20.7.2.2.1 shared_ptr constructors [util.smartptr.shared.const] constexpr shared_ptr() noexcept;
1
Effects: Constructs an empty shared_ptr object.
2
Postconditions: use_count() == 0 && get() == 0. template explicit shared_ptr(Y* p);
3
Requires: p shall be convertible to T*. Y shall be a complete type. The expression delete p shall be well formed, shall have well defined behavior, and shall not throw exceptions.
4
Effects: Constructs a shared_ptr object that owns the pointer p.
5
Postconditions: use_count() == 1 && get() == p.
6
Throws: bad_alloc, or an implementation-defined exception when a resource other than memory could not be obtained.
7
Exception safety: If an exception is thrown, delete p is called. template shared_ptr(Y* p, D d); template shared_ptr(Y* p, D d, A a); template shared_ptr(nullptr_t p, D d); template shared_ptr(nullptr_t p, D d, A a);
§ 20.7.2.2.1
526
c ISO/IEC
N3376
8
Requires: p shall be convertible to T*. D shall be CopyConstructible. The copy constructor and destructor of D shall not throw exceptions. The expression d(p) shall be well formed, shall have well defined behavior, and shall not throw exceptions. A shall be an allocator (17.6.3.5). The copy constructor and destructor of A shall not throw exceptions.
9
Effects: Constructs a shared_ptr object that owns the object p and the deleter d. The second and fourth constructors shall use a copy of a to allocate memory for internal use.
10
Postconditions: use_count() == 1 && get() == p.
11
Throws: bad_alloc, or an implementation-defined exception when a resource other than memory could not be obtained.
12
Exception safety: If an exception is thrown, d(p) is called. template shared_ptr(const shared_ptr& r, T *p) noexcept;
13
Effects: Constructs a shared_ptr instance that stores p and shares ownership with r.
14
Postconditions: get() == p && use_count() == r.use_count()
15
[ Note: To avoid the possibility of a dangling pointer, the user of this constructor must ensure that p remains valid at least until the ownership group of r is destroyed. — end note ]
16
[ Note: This constructor allows creation of an empty shared_ptr instance with a non-NULL stored pointer. — end note ] shared_ptr(const shared_ptr& r) noexcept; template shared_ptr(const shared_ptr& r) noexcept;
17
Requires: The second constructor shall not participate in the overload resolution unless Y* is implicitly convertible to T*.
18
Effects: If r is empty, constructs an empty shared_ptr object; otherwise, constructs a shared_ptr object that shares ownership with r.
19
Postconditions: get() == r.get() && use_count() == r.use_count(). shared_ptr(shared_ptr&& r) noexcept; template shared_ptr(shared_ptr&& r) noexcept;
20
Remark: The second constructor shall not participate in overload resolution unless Y* is convertible to T*.
21
Effects: Move-constructs a shared_ptr instance from r.
22
Postconditions: *this shall contain the old value of r. r shall be empty. r.get() == 0. template explicit shared_ptr(const weak_ptr& r);
23
Requires: Y* shall be convertible to T*.
24
Effects: Constructs a shared_ptr object that shares ownership with r and stores a copy of the pointer stored in r.
25
Postconditions: use_count() == r.use_count().
26
Throws: bad_weak_ptr when r.expired().
27
Exception safety: If an exception is thrown, the constructor has no effect. § 20.7.2.2.1
527
c ISO/IEC
N3376
template shared_ptr(auto_ptr&& r); 28
Requires: r.release() shall be convertible to T*. Y shall be a complete type. The expression delete r.release() shall be well formed, shall have well defined behavior, and shall not throw exceptions.
29
Effects: Constructs a shared_ptr object that stores and owns r.release().
30
Postconditions: use_count() == 1 && r.get() == 0.
31
Throws: bad_alloc, or an implementation-defined exception when a resource other than memory could not be obtained.
32
Exception safety: If an exception is thrown, the constructor has no effect. template shared_ptr(unique_ptr&&r);
33
Effects: Equivalent to shared_ptr(r.release(), r.get_deleter()) when D is not a reference type, otherwise shared_ptr(r.release(), ref(r.get_deleter())).
34
Exception safety: If an exception is thrown, the constructor has no effect. 20.7.2.2.2
shared_ptr destructor
[util.smartptr.shared.dest]
~shared_ptr(); 1
Effects: — If *this is empty or shares ownership with another shared_ptr instance (use_count() > 1), there are no side effects. — Otherwise, if *this owns an object p and a deleter d, d(p) is called. — Otherwise, *this owns a pointer p, and delete p is called.
2
[ Note: Since the destruction of *this decreases the number of instances that share ownership with *this by one, after *this has been destroyed all shared_ptr instances that shared ownership with *this will report a use_count() that is one less than its previous value. — end note ] 20.7.2.2.3
shared_ptr assignment
[util.smartptr.shared.assign]
shared_ptr& operator=(const shared_ptr& r) noexcept; template shared_ptr& operator=(const shared_ptr& r) noexcept; template shared_ptr& operator=(auto_ptr&& r); 1
Effects: Equivalent to shared_ptr(r).swap(*this).
2
Returns: *this.
3
[ Note: The use count updates caused by the temporary object construction and destruction are not observable side effects, so the implementation may meet the effects (and the implied guarantees) via different means, without creating a temporary. In particular, in the example: shared_ptr p(new int); shared_ptr q(p); p = p; q = p;
both assignments may be no-ops. — end note ] shared_ptr& operator=(shared_ptr&& r) noexcept; template shared_ptr& operator=(shared_ptr&& r) noexcept;
§ 20.7.2.2.3
528
c ISO/IEC
N3376
4
Effects: Equivalent to shared_ptr(std::move(r)).swap(*this).
5
Returns: *this. template shared_ptr& operator=(unique_ptr&& r);
6
Effects: Equivalent to shared_ptr(std::move(r)).swap(*this).
7
Returns: *this 20.7.2.2.4
shared_ptr modifiers
[util.smartptr.shared.mod]
void swap(shared_ptr& r) noexcept; 1
Effects: Exchanges the contents of *this and r. void reset() noexcept;
2
Effects: Equivalent to shared_ptr().swap(*this). template void reset(Y* p);
3
Effects: Equivalent to shared_ptr(p).swap(*this). template void reset(Y* p, D d);
4
Effects: Equivalent to shared_ptr(p, d).swap(*this). template void reset(Y* p, D d, A a);
5
Effects: Equivalent to shared_ptr(p, d, a).swap(*this). 20.7.2.2.5
shared_ptr observers
[util.smartptr.shared.obs]
T* get() const noexcept; 1
Returns: the stored pointer. T& operator*() const noexcept;
2
Requires: get() != 0.
3
Returns: *get().
4
Remarks: When T is void, it is unspecified whether this member function is declared. If it is declared, it is unspecified what its return type is, except that the declaration (although not necessarily the definition) of the function shall be well formed. T* operator->() const noexcept;
5
Requires: get() != 0.
6
Returns: get().
§ 20.7.2.2.5
529
c ISO/IEC
N3376
long use_count() const noexcept; 7
Returns: the number of shared_ptr objects, *this included, that share ownership with *this, or 0 when *this is empty.
8
[ Note: use_count() is not necessarily efficient. — end note ] bool unique() const noexcept;
9 10
Returns: use_count() == 1. [ Note: unique() may be faster than use_count(). If you are using unique() to implement copy on write, do not rely on a specific value when get() == 0. — end note ] explicit operator bool() const noexcept;
11
Returns: get() != 0. template bool owner_before(shared_ptr const& b) const; template bool owner_before(weak_ptr const& b) const;
12
Returns: An unspecified value such that — x.owner_before(y) defines a strict weak ordering as defined in 25.4; — under the equivalence relation defined by owner_before, !a.owner_before(b) && !b.owner_before(a), two shared_ptr or weak_ptr instances are equivalent if and only if they share ownership or are both empty. 20.7.2.2.6
shared_ptr creation
[util.smartptr.shared.create]
template shared_ptr make_shared(Args&&... args); template shared_ptr allocate_shared(const A& a, Args&&... args); 1
Requires: The expression ::new (pv) T(std::forward(args)...), where pv has type void* and points to storage suitable to hold an object of type T, shall be well formed. A shall be an allocator (17.6.3.5). The copy constructor and destructor of A shall not throw exceptions.
2
Effects: Allocates memory suitable for an object of type T and constructs an object in that memory via the placement new expression ::new (pv) T(std::forward(args)...). The template allocate_shared uses a copy of a to allocate memory. If an exception is thrown, the functions have no effect.
3
Returns: A shared_ptr instance that stores and owns the address of the newly constructed object of type T.
4
Postconditions: get() != 0 && use_count() == 1
5
Throws: bad_alloc, or an exception thrown from A::allocate or from the constructor of T.
6
Remarks: Implementations are encouraged, but not required, to perform no more than one memory allocation. [ Note: This provides efficiency equivalent to an intrusive smart pointer. — end note ]
7
[ Note: These functions will typically allocate more memory than sizeof(T) to allow for internal bookkeeping structures such as the reference counts. — end note ]
§ 20.7.2.2.6
530
c ISO/IEC
20.7.2.2.7
N3376
shared_ptr comparison
[util.smartptr.shared.cmp]
template bool operator==(const shared_ptr& a, const shared_ptr& b) noexcept; 1
Returns: a.get() == b.get(). template bool operator& operator& os, shared_ptr const& p); 1
Effects: os { typedef bool result_type; typedef shared_ptr first_argument_type; typedef shared_ptr second_argument_type; bool operator()(shared_ptr const&, shared_ptr const&) const; bool operator()(shared_ptr const&, weak_ptr const&) const; bool operator()(weak_ptr const&, shared_ptr const&) const; }; template struct owner_less<weak_ptr > { typedef bool result_type; typedef weak_ptr first_argument_type; typedef weak_ptr second_argument_type; bool operator()(weak_ptr const&, weak_ptr const&) const; bool operator()(shared_ptr const&, weak_ptr const&) const; bool operator()(weak_ptr const&, shared_ptr const&) const; }; }
2
operator()(x,y) shall return x.owner_before(y). [ Note: Note that — operator() defines a strict weak ordering as defined in 25.4; — under the equivalence relation defined by operator(), !operator()(a, b) && !operator()(b, a), two shared_ptr or weak_ptr instances are equivalent if and only if they share ownership or are both empty. § 20.7.2.3.7
535
c ISO/IEC
20.7.2.4 1
2
Class template enable_shared_from_this
N3376
[util.smartptr.enab]
A class T can inherit from enable_shared_from_this to inherit the shared_from_this member functions that obtain a shared_ptr instance pointing to *this. [ Example: struct X: public enable_shared_from_this<X> { }; int main() { shared_ptr<X> p(new X); shared_ptr<X> q = p->shared_from_this(); assert(p == q); assert(!(p < q ) && !(q < p)); // p and q share ownership }
— end example ] namespace std { template class enable_shared_from_this { protected: constexpr enable_shared_from_this() noexcept; enable_shared_from_this(enable_shared_from_this const&) noexcept; enable_shared_from_this& operator=(enable_shared_from_this const&) noexcept; ~enable_shared_from_this(); public: shared_ptr shared_from_this(); shared_ptr shared_from_this() const; }; } // namespace std 3
The template parameter T of enable_shared_from_this may be an incomplete type. constexpr enable_shared_from_this() noexcept; enable_shared_from_this(const enable_shared_from_this&) noexcept;
4
Effects: Constructs an enable_shared_from_this object. enable_shared_from_this& operator=(const enable_shared_from_this&) noexcept;
5
Returns: *this. ~enable_shared_from_this();
6
Effects: Destroys *this. shared_ptr shared_from_this(); shared_ptr shared_from_this() const;
7
Requires: enable_shared_from_this shall be an accessible base class of T. *this shall be a subobject of an object t of type T. There shall be at least one shared_ptr instance p that owns &t.
8
Returns: A shared_ptr object r that shares ownership with p.
9
Postconditions: r.get() == this.
10
[ Note: A possible implementation is shown below: § 20.7.2.4
536
c ISO/IEC
N3376
template class enable_shared_from_this { private: weak_ptr __weak_this; protected: constexpr enable_shared_from_this() : __weak_this() { } enable_shared_from_this(enable_shared_from_this const &) { } enable_shared_from_this& operator=(enable_shared_from_this const &) { return *this; } ~enable_shared_from_this() { } public: shared_ptr shared_from_this() { return shared_ptr(__weak_this); } shared_ptr shared_from_this() const { return shared_ptr(__weak_this); } }; 11
The shared_ptr constructors that create unique pointers can detect the presence of an enable_shared_from_this base and assign the newly created shared_ptr to its __weak_this member. — end note ] 20.7.2.5
1
2
shared_ptr atomic access
[util.smartptr.shared.atomic]
Concurrent access to a shared_ptr object from multiple threads does not introduce a data race if the access is done exclusively via the functions in this section and the instance is passed as their first argument. The meaning of the arguments of type memory_order is explained in 29.3. template bool atomic_is_lock_free(const shared_ptr* p);
3
Requires: p shall not be null.
4
Returns: true if atomic access to *p is lock-free, false otherwise.
5
Throws: Nothing. template shared_ptr atomic_load(const shared_ptr* p);
6
Requires: p shall not be null.
7
Returns: atomic_load_explicit(p, memory_order_seq_cst).
8
Throws: Nothing. template shared_ptr atomic_load_explicit(const shared_ptr* p, memory_order mo);
9
Requires: p shall not be null.
10
Requires: mo shall not be memory_order_release or memory_order_acq_rel.
11
Returns: *p.
12
Throws: Nothing. template void atomic_store(shared_ptr* p, shared_ptr r);
13
Requires: p shall not be null.
14
Effects: atomic_store_explicit(p, r, memory_order_seq_cst).
15
Throws: Nothing.
§ 20.7.2.5
537
c ISO/IEC
N3376
template void atomic_store_explicit(shared_ptr* p, shared_ptr r, memory_order mo); 16
Requires: p shall not be null.
17
Requires: mo shall not be memory_order_acquire or memory_order_acq_rel.
18
Effects: p->swap(r).
19
Throws: Nothing. template shared_ptr atomic_exchange(shared_ptr* p, shared_ptr r);
20
Requires: p shall not be null.
21
Returns: atomic_exchange_explicit(p, r, memory_order_seq_cst).
22
Throws: Nothing. template shared_ptr atomic_exchange_explicit(shared_ptr* p, shared_ptr r, memory_order mo);
23
Requires: p shall not be null.
24
Effects: p->swap(r).
25
Returns: The previous value of *p.
26
Throws: Nothing. template bool atomic_compare_exchange_weak( shared_ptr* p, shared_ptr* v, shared_ptr w);
27
Requires: p shall not be null.
28
Returns: atomic_compare_exchange_weak_explicit(p, v, w, memory_order_seq_cst, memory_order_seq_cst).
29
Throws: Nothing. template bool atomic_compare_exchange_strong( shared_ptr* p, shared_ptr* v, shared_ptr w);
30
Returns: atomic_compare_exchange_strong_explicit(p, v, w, memory_order_seq_cst, memory_order_seq_cst). template bool atomic_compare_exchange_weak_explicit( shared_ptr* p, shared_ptr* v, shared_ptr w, memory_order success, memory_order failure); template bool atomic_compare_exchange_strong_explicit( shared_ptr* p, shared_ptr* v, shared_ptr w, memory_order success, memory_order failure);
§ 20.7.2.5
538
c ISO/IEC
N3376
31
Requires: p shall not be null.
32
Requires: failure shall not be memory_order_release, memory_order_acq_rel, or stronger than success.
33
Effects: If *p is equivalent to *v, assigns w to *p and has synchronization semantics corresponding to the value of success, otherwise assigns *p to *v and has synchronization semantics corresponding to the value of failure.
34
Returns: true if *p was equivalent to *v, false otherwise.
35
Throws: Nothing.
36
Remarks: two shared_ptr objects are equivalent if they store the same pointer value and share ownership.
37
Remarks: the weak forms may fail spuriously. See 29.6. 20.7.2.6
Smart pointer hash support
[util.smartptr.hash]
template struct hash; 1
Requires: The template specialization shall meet the requirements of class template hash (20.8.12). For an object p of type UP, where UP is unique_ptr, hash()(p) shall evaluate to the same value as hash()(p.get()). The specialization hash shall be well-formed. template struct hash<shared_ptr >;
2
Requires: The template specialization shall meet the requirements of class template hash (20.8.12). For an object p of type shared_ptr, hash<shared_ptr >()(p) shall evaluate to the same value as hash()(p.get()).
20.8 1
2
Function objects
[function.objects]
A function object type is an object type (3.9) that can be the type of the postfix-expression in a function call (5.2.2, 13.3.1.1).229 A function object is an object of a function object type. In the places where one would expect to pass a pointer to a function to an algorithmic template (Clause 25), the interface is specified to accept a function object. This not only makes algorithmic templates work with pointers to functions, but also enables them to work with arbitrary function objects. Header synopsis namespace std { // D.8.1, base (deprecated): template struct unary_function; template struct binary_function; // 20.8.3, reference_wrapper: template class reference_wrapper; template template template template
reference_wrapper ref(T&) noexcept; reference_wrapper cref(const T&) noexcept; void ref(const T&&) = delete; void cref(const T&&) = delete;
229) Such a type is a function pointer or a class type which has a member operator() or a class type which has a conversion to a pointer to function.
§ 20.8
539
c ISO/IEC
N3376
template reference_wrapper ref(reference_wrapper) noexcept; template reference_wrapper cref(reference_wrapper) noexcept; // 20.8.4, arithmetic template template template template template template
operations: struct plus; struct minus; struct multiplies; struct divides; struct modulus; struct negate;
// 20.8.5, comparisons: template struct template struct template struct template struct template struct template struct
equal_to; not_equal_to; greater; less; greater_equal; less_equal;
// 20.8.6, logical operations: template struct logical_and; template struct logical_or; template struct logical_not; // 20.8.7, bitwise template struct bit_xor;
// 20.8.8, negators: template template unary_negate template template binary_negate
class unary_negate; not1(const Predicate&); class binary_negate; not2(const Predicate&);
// 20.8.9, bind: template struct is_bind_expression; template struct is_placeholder; template bind(F&&, BoundArgs&&...);
namespace placeholders { // M is the implementation-defined number of placeholders extern unspecified _1; extern unspecified _2; . . . extern unspecified _M; }
§ 20.8
540
c ISO/IEC
N3376
// D.9, binders (deprecated): template class binder1st; template binder1st bind1st(const Fn&, const T&); template class binder2nd; template binder2nd bind2nd(const Fn&, const T&); // D.8.2.1, adaptors (deprecated): template class pointer_to_unary_function; template pointer_to_unary_function ptr_fun(Result (*)(Arg)); template class pointer_to_binary_function; template pointer_to_binary_function ptr_fun(Result (*)(Arg1,Arg2)); // D.8.2.2, adaptors (deprecated): template class mem_fun_t; template class mem_fun1_t; template mem_fun_t<S,T> mem_fun(S (T::*f)()); template mem_fun1_t<S,T,A> mem_fun(S (T::*f)(A)); template class mem_fun_ref_t; template class mem_fun1_ref_t; template mem_fun_ref_t<S,T> mem_fun_ref(S (T::*f)()); template mem_fun1_ref_t<S,T,A> mem_fun_ref(S (T::*f)(A)); template class const_mem_fun_t; template class const_mem_fun1_t; template const_mem_fun_t<S,T> mem_fun(S (T::*f)() const); template const_mem_fun1_t<S,T,A> mem_fun(S (T::*f)(A) const); template class const_mem_fun_ref_t; template class const_mem_fun1_ref_t; template const_mem_fun_ref_t<S,T> mem_fun_ref(S (T::*f)() const); template const_mem_fun1_ref_t<S,T,A> mem_fun_ref(S (T::*f)(A) const); // 20.8.10, member function adaptors: template unspecified mem_fn(R T::*); template unspecified mem_fn(R (T::*)(Args...)); template unspecified mem_fn(R (T::*)(Args...) const); template unspecified mem_fn(R (T::*)(Args...) volatile); template
§ 20.8
541
c ISO/IEC
unspecified template (T::*)(Args...) const volatile &&);
// 20.8.11 polymorphic function wrappers: class bad_function_call; template class function; // undefined template class function; template void swap(function&, function&); template bool operator==(const function&, nullptr_t); template bool operator==(nullptr_t, const function&); template bool operator!=(const function&, nullptr_t); template bool operator!=(nullptr_t, const function&); // 20.8.12, hash function base template: template struct hash; // Hash function specializations template struct hash; template struct hash; template struct hash<signed char>; template struct hash; template struct hash; template struct hash; template struct hash<wchar_t>; template struct hash<short>; template struct hash; template struct hash; template struct hash; template struct hash; template struct hash; template struct hash; template struct hash;
§ 20.8
542
c ISO/IEC
N3376
template struct hash; template struct hash<double>; template struct hash; template struct hash; } 3
[ Example: If a C++ program wants to have a by-element addition of two vectors a and b containing double and put the result into a, it can do: transform(a.begin(), a.end(), b.begin(), a.begin(), plus<double>());
4
— end example ] [ Example: To negate every element of a: transform(a.begin(), a.end(), a.begin(), negate<double>());
5
— end example ] To enable adaptors and other components to manipulate function objects that take one or two arguments it is required that the function objects correspondingly provide typedefs argument_type and result_type for function objects that take one argument and first_argument_type, second_argument_type, and result_type for function objects that take two arguments.
20.8.1 1 2
3 4 5
6 7
[func.def]
The following definitions apply to this Clause: A call signature is the name of a return type followed by a parenthesized comma-separated list of zero or more argument types. A callable type is a function object type (20.8) or a pointer to member. A callable object is an object of a callable type. A call wrapper type is a type that holds a callable object and supports a call operation that forwards to that object. A call wrapper is an object of a call wrapper type. A target object is the callable object held by a call wrapper.
20.8.2 1
Definitions
Requirements
[func.require]
Define INVOKE (f, t1, t2, ..., tN) as follows: — (t1.*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is an object of type T or a reference to an object of type T or a reference to an object of a type derived from T; — ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is not one of the types described in the previous item; — t1.*f when N == 1 and f is a pointer to member data of a class T and t1 is an object of type T or a reference to an object of type T or a reference to an object of a type derived from T; — (*t1).*f when N == 1 and f is a pointer to member data of a class T and t1 is not one of the types described in the previous item; — f(t1, t2, ..., tN) in all other cases.
2 3
Define INVOKE (f, t1, t2, ..., tN, R) as INVOKE (f, t1, t2, ..., tN) implicitly converted to R. If a call wrapper (20.8.1) has a weak result type the type of its member type result_type is based on the type T of the wrapper’s target object (20.8.1): — if T is a pointer to function type, result_type shall be a synonym for the return type of T; — if T is a pointer to member function, result_type shall be a synonym for the return type of T; § 20.8.2
543
c ISO/IEC
N3376
— if T is a class type with a member type result_type, then result_type shall be a synonym for T::result_type; — otherwise result_type shall not be defined. 4
Every call wrapper (20.8.1) shall be MoveConstructible. A simple call wrapper is a call wrapper that is CopyConstructible and CopyAssignable and whose copy constructor, move constructor, and assignment operator do not throw exceptions. A forwarding call wrapper is a call wrapper that can be called with an arbitrary argument list and delivers the arguments to the wrapped callable object as references. This forwarding step shall ensure that rvalue arguments are delivered as rvalue-references and lvalue arguments are delivered as lvalue-references. [ Note: In a typical implementation forwarding call wrappers have an overloaded function call operator of the form template R operator()(UnBoundArgs&&... unbound_args) cv-qual ;
— end note ]
20.8.3
Class template reference_wrapper
namespace std { template class reference_wrapper { public : // types typedef T type; typedef see below result_type; typedef see below argument_type; typedef see below first_argument_type; typedef see below second_argument_type;
[refwrap]
// // // //
not not not not
always always always always
defined defined defined defined
// construct/copy/destroy reference_wrapper(T&) noexcept; reference_wrapper(T&&) = delete; // do not bind to temporary objects reference_wrapper(const reference_wrapper& x) noexcept; // assignment reference_wrapper& operator=(const reference_wrapper& x) noexcept; // access operator T& () const noexcept; T& get() const noexcept; // invocation template typename result_of::type operator() (ArgTypes&&...) const; }; } 1
2
3
reference_wrapper is a CopyConstructible and CopyAssignable wrapper around a reference to an object or function of type T. reference_wrapper has a weak result type (20.8.2). If T is a function type, result_type shall be a synonym for the return type of T. The template instantiation reference_wrapper shall define a nested type named argument_type as a synonym for T1 only if the type T is any of the following: — a function type or a pointer to function type taking one argument of type T1 § 20.8.3
544
c ISO/IEC
N3376
— a pointer to member function R T0::f cv (where cv represents the member function’s cv-qualifiers); the type T1 is cv T0* — a class type with a member type argument_type; the type T1 is T::argument_type. 4
The template instantiation reference_wrapper shall define two nested types named first_argument_type and second_argument_type as synonyms for T1 and T2, respectively, only if the type T is any of the following: — a function type or a pointer to function type taking two arguments of types T1 and T2 — a pointer to member function R T0::f(T2) cv (where cv represents the member function’s cv-qualifiers); the type T1 is cv T0* — a class type with member types first_argument_type and second_argument_type; the type T1 is T::first_argument_type. and the type T2 is T::second_argument_type. 20.8.3.1
reference_wrapper construct/copy/destroy
[refwrap.const]
reference_wrapper(T& t) noexcept; 1
Effects: Constructs a reference_wrapper object that stores a reference to t. reference_wrapper(const reference_wrapper& x) noexcept;
2
Effects: Constructs a reference_wrapper object that stores a reference to x.get(). 20.8.3.2
reference_wrapper assignment
[refwrap.assign]
reference_wrapper& operator=(const reference_wrapper& x) noexcept; 1
Postconditions: *this stores a reference to x.get(). 20.8.3.3
reference_wrapper access
[refwrap.access]
operator T& () const noexcept; 1
Returns: The stored reference. T& get() const noexcept;
2
Returns: The stored reference. 20.8.3.4
reference_wrapper invocation
[refwrap.invoke]
template typename result_of::type operator()(ArgTypes&&... args) const; 1
Returns: INVOKE (get(), std::forward(args)...). (20.8.2)
2
Remark: operator() is described for exposition only. Implementations are not required to provide an actual reference_wrapper::operator(). Implementations are permitted to support reference_wrapper function invocation through multiple overloaded operators or through other means.
§ 20.8.3.4
545
c ISO/IEC
20.8.3.5
N3376
reference_wrapper helper functions
[refwrap.helpers]
template reference_wrapper ref(T& t) noexcept; 1
Returns: reference_wrapper(t) template reference_wrapper ref(reference_wrappert) noexcept;
2
Returns: ref(t.get()) template reference_wrapper cref(const T& t) noexcept;
3
Returns: reference_wrapper (t) template reference_wrapper cref(reference_wrapper t) noexcept;
4
Returns: cref(t.get());
20.8.4 1
Arithmetic operations
[arithmetic.operations]
The library provides basic function object classes for all of the arithmetic operators in the language (5.6, 5.7). template struct plus { T operator()(const T& x, const T& y) const; typedef T first_argument_type; typedef T second_argument_type; typedef T result_type; };
2
operator() returns x + y. template struct minus { T operator()(const T& x, const T& y) const; typedef T first_argument_type; typedef T second_argument_type; typedef T result_type; };
3
operator() returns x - y. template struct multiplies { T operator()(const T& x, const T& y) const; typedef T first_argument_type; typedef T second_argument_type; typedef T result_type; };
4
operator() returns x * y.
§ 20.8.4
546
c ISO/IEC
N3376
template struct divides { T operator()(const T& x, const T& y) const; typedef T first_argument_type; typedef T second_argument_type; typedef T result_type; }; 5
operator() returns x / y. template struct modulus { T operator()(const T& x, const T& y) const; typedef T first_argument_type; typedef T second_argument_type; typedef T result_type; };
6
operator() returns x % y. template struct negate { T operator()(const T& x) const; typedef T argument_type; typedef T result_type; };
7
operator() returns -x.
20.8.5 1
Comparisons
[comparisons]
The library provides basic function object classes for all of the comparison operators in the language (5.9, 5.10). template struct equal_to { bool operator()(const T& x, const T& y) const; typedef T first_argument_type; typedef T second_argument_type; typedef bool result_type; };
2
operator() returns x == y. template struct not_equal_to { bool operator()(const T& x, const T& y) const; typedef T first_argument_type; typedef T second_argument_type; typedef bool result_type; };
3
operator() returns x != y. template struct greater { bool operator()(const T& x, const T& y) const; typedef T first_argument_type; typedef T second_argument_type; typedef bool result_type; };
§ 20.8.5
547
c ISO/IEC
4
N3376
operator() returns x > y. template struct less { bool operator()(const T& x, const T& y) const; typedef T first_argument_type; typedef T second_argument_type; typedef bool result_type; };
5
operator() returns x < y. template struct greater_equal { bool operator()(const T& x, const T& y) const; typedef T first_argument_type; typedef T second_argument_type; typedef bool result_type; };
6
operator() returns x >= y. template struct less_equal { bool operator()(const T& x, const T& y) const; typedef T first_argument_type; typedef T second_argument_type; typedef bool result_type; };
7 8
operator() returns x 0 to indicate that T should be treated as a placeholder type. 20.8.9.1.3 Function template bind [func.bind.bind] 1
In the text that follows, the following names have the following meanings: — FD is the type decay::type, — fd is an lvalue of type FD constructed from std::forward(f), — Ti is the ith type in the template parameter back BoundArgs, — TiD is the type decay<Ti>::type, — ti is the ith argument in the function parameter pack bound_args, — tid is an lvalue of type TiD constructed from std::forward<Ti>(ti), — Uj is the j th deduced type of the UnBoundArgs&&... parameter of the forwarding call wrapper, and — uj is the j th argument associated with Uj. template unspecified bind(F&& f, BoundArgs&&... bound_args);
2
Requires: is_constructible::value shall be true. For each Ti in BoundArgs, is_constructible<TiD, Ti>::value shall be true. INVOKE (fd, w1, w2, ..., wN) (20.8.2) shall be a valid expression for some values w1, w2, ..., wN, where N == sizeof...(bound_args).
3
Returns: A forwarding call wrapper g with a weak result type (20.8.2). The effect of g(u1, u2, ..., uM) shall be INVOKE (fd, std::forward(v1), std::forward(v2), ..., std::forward(vN), result_of::type), where cv represents the cv-qualifiers of g and the values and types of the bound arguments v1, v2, ..., vN are determined as specified below. The copy constructor and move constructor of the forwarding call wrapper shall throw an exception if and only if the corresponding constructor of FD or of any of the types TiD throws an exception.
4
Throws: Nothing unless the construction of fd or of one of the values tid throws an exception.
5
Remarks: The return type shall satisfy the requirements of MoveConstructible. If all of FD and TiD satisfy the requirements of CopyConstructible, then the return type shall satisfy the requirements of CopyConstructible. [ Note: This implies that all of FD and TiD are MoveConstructible. — end note ] template unspecified bind(F&& f, BoundArgs&&... bound_args);
6
Requires: is_constructible::value shall be true. For each Ti in BoundArgs, is_constructible<TiD, Ti>::value shall be true. INVOKE (fd, w1, w2, ..., wN) shall be a valid expression for some values w1, w2, ..., wN, where N == sizeof...(bound_args).
7
Returns: A forwarding call wrapper g with a nested type result_type defined as a synonym for R. The effect of g(u1, u2, ..., uM) shall be INVOKE (fd, std::forward(v1), std::forward(v2), ..., std::forward(vN), R), where the values and types of the bound arguments v1, v2, ..., vN are determined as specified below. The copy constructor and move constructor of the forwarding
§ 20.8.9.1.3
551
c ISO/IEC
N3376
call wrapper shall throw an exception if and only if the corresponding constructor of FD or of any of the types TiD throws an exception. 8
Throws: Nothing unless the construction of fd or of one of the values tid throws an exception.
9
Remarks: The return type shall satisfy the requirements of MoveConstructible. If all of FD and TiD satisfy the requirements of CopyConstructible, then the return type shall satisfy the requirements of CopyConstructible. [ Note: This implies that all of FD and TiD are MoveConstructible. — end note ]
10
The values of the bound arguments v1, v2, ..., vN and their corresponding types V1, V2, ..., VN depend on the types TiD derived from the call to bind and the cv-qualifiers cv of the call wrapper g as follows: — if TiD is reference_wrapper, the argument is tid.get() and its type Vi is T&; — if the value of is_bind_expression<TiD>::value is true, the argument is tid(std::forward( uj)...) and its type Vi is result_of<TiD cv & (Uj&&...)>::type&&; — if the value j of is_placeholder<TiD>::value is not zero, the argument is std::forward(uj) and its type Vi is Uj&&; — otherwise, the value is tid and its type Vi is TiD cv &. 20.8.9.1.4
Placeholders
[func.bind.place]
namespace std { namespace placeholders { // M is the implementation-defined number of placeholders extern unspecified _1; extern unspecified _2; . . . extern unspecified _M; } } 1
All placeholder types shall be DefaultConstructible and CopyConstructible, and their default constructors and copy/move constructors shall not throw exceptions. It is implementation-defined whether placeholder types are CopyAssignable. CopyAssignable placeholders’ copy assignment operators shall not throw exceptions.
20.8.10
Function template mem_fn
template (T::* pm)(Args...) &);
552
c ISO/IEC
N3376
template (T::* pm)(Args...)
const &); volatile &); const volatile &); &&); const &&); volatile &&); const volatile &&);
1
Returns: A simple call wrapper (20.8.1) fn such that the expression fn(t, a2, ..., aN) is equivalent to INVOKE (pm, t, a2, ..., aN) (20.8.2). fn shall have a nested type result_type that is a synonym for the return type of pm when pm is a pointer to member function.
2
The simple call wrapper shall define two nested types named argument_type and result_type as synonyms for cv T* and Ret, respectively, when pm is a pointer to member function with cv-qualifier cv and taking no arguments, where Ret is pm’s return type.
3
The simple call wrapper shall define three nested types named first_argument_type, second_argument_type, and result_type as synonyms for cv T*, T1, and Ret, respectively, when pm is a pointer to member function with cv-qualifier cv and taking one argument of type T1, where Ret is pm’s return type.
4
Throws: Nothing.
20.8.11
Polymorphic function wrappers
[func.wrap]
1
This subclause describes a polymorphic wrapper class that encapsulates arbitrary callable objects. 20.8.11.1 Class bad_function_call [func.wrap.badcall]
1
An exception of type bad_function_call is thrown by function::operator() (20.8.11.2.4) when the function wrapper object has no target. namespace std { class bad_function_call : public std::exception { public: // 20.8.11.1.1, constructor: bad_function_call() noexcept; }; } // namespace std
20.8.11.1.1
bad_function_call constructor
[func.wrap.badcall.const]
bad_function_call() noexcept; 1
Effects: constructs a bad_function_call object. 20.8.11.2
Class template function
[func.wrap.func]
namespace std { template class function; // undefined template class function {
§ 20.8.11.2
553
c ISO/IEC
public: typedef R result_type; typedef T1 argument_type; typedef T1 first_argument_type; typedef T2 second_argument_type;
N3376
// // // // // //
iff sizeof...(ArgTypes) == 1 and the type in ArgTypes is T1 iff sizeof...(ArgTypes) == 2 and ArgTypes contains T1 and T2 iff sizeof...(ArgTypes) == 2 and ArgTypes contains T1 and T2
// 20.8.11.2.1, construct/copy/destroy: function() noexcept; function(nullptr_t) noexcept; function(const function&); function(function&&); template function(F); template function(allocator_arg_t, const A&) noexcept; template function(allocator_arg_t, const A&, nullptr_t) noexcept; template function(allocator_arg_t, const A&, const function&); template function(allocator_arg_t, const A&, function&&); template function(allocator_arg_t, const A&, F); function& operator=(const function&); function& operator=(function&&); function& operator=(nullptr_t); template function& operator=(F&&); template function& operator=(reference_wrapper) noexcept; ~function(); // 20.8.11.2.2, function modifiers: void swap(function&) noexcept; template void assign(F&&, const A&); // 20.8.11.2.3, function capacity: explicit operator bool() const noexcept; // 20.8.11.2.4, function invocation: R operator()(ArgTypes...) const; // 20.8.11.2.5, function target access: const std::type_info& target_type() const noexcept; template T* target() noexcept; template const T* target() const noexcept; }; // 20.8.11.2.6, Null pointer comparisons: template bool operator==(const function&, nullptr_t) noexcept; template bool operator==(nullptr_t, const function&) noexcept;
§ 20.8.11.2
554
c ISO/IEC
N3376
template bool operator!=(const function&, nullptr_t) noexcept; template bool operator!=(nullptr_t, const function&) noexcept; // 20.8.11.2.7, specialized algorithms: template void swap(function&, function&); template struct uses_allocator : true_type { }; } 1
2
3
1
The function class template provides polymorphic wrappers that generalize the notion of a function pointer. Wrappers can store, copy, and call arbitrary callable objects (20.8.1), given a call signature (20.8.1), allowing functions to be first-class objects. A callable object f of type F is Callable for argument types ArgTypes and return type R if the expression INVOKE (f, declval()..., R), considered as an unevaluated operand (Clause 5), is well formed (20.8.2). The function class template is a call wrapper (20.8.1) whose call signature (20.8.1) is R(ArgTypes...). 20.8.11.2.1 function construct/copy/destroy [func.wrap.func.con] When any function constructor that takes a first argument of type allocator_arg_t is invoked, the second argument shall have a type that conforms to the requirements for Allocator (Table 17.6.3.5). A copy of the allocator argument is used to allocate memory, if necessary, for the internal data structures of the constructed function object. function() noexcept; template function(allocator_arg_t, const A& a) noexcept;
2
Postconditions: !*this. function(nullptr_t) noexcept; template function(allocator_arg_t, const A& a, nullptr_t) noexcept;
3
Postconditions: !*this. function(const function& f); template function(allocator_arg_t, const A& a, const function& f);
4
Postconditions: !*this if !f; otherwise, *this targets a copy of f.target().
5
Throws: shall not throw exceptions if f’s target is a callable object passed via reference_wrapper or a function pointer. Otherwise, may throw bad_alloc or any exception thrown by the copy constructor of the stored callable object. [ Note: Implementations are encouraged to avoid the use of dynamically allocated memory for small callable objects, for example, where f’s target is an object holding only a pointer or reference to an object and a member function pointer. — end note ] function(function&& f); template function(allocator_arg_t, const A& a, function&& f);
§ 20.8.11.2.1
555
c ISO/IEC
6
N3376
Effects: If !f, *this has no target; otherwise, move-constructs the target of f into the target of *this, leaving f in a valid state with an unspecified value. template function(F f); template function(allocator_arg_t, const A& a, F f);
7
Requires: F shall be CopyConstructible. f shall be Callable (20.8.11.2) for argument types ArgTypes and return type R. The copy constructor and destructor of A shall not throw exceptions.
8
Postconditions: !*this if any of the following hold: — f is a NULL function pointer. — f is a NULL pointer to member. — F is an instance of the function class template, and !f
9
Otherwise, *this targets a copy of f initialized with std::move(f). [ Note: Implementations are encouraged to avoid the use of dynamically allocated memory for small callable objects, for example, where f’s target is an object holding only a pointer or reference to an object and a member function pointer. — end note ]
10
Throws: shall not throw exceptions when f is a function pointer or a reference_wrapper for some T. Otherwise, may throw bad_alloc or any exception thrown by F’s copy or move constructor. function& operator=(const function& f);
11
Effects: function(f).swap(*this);
12
Returns: *this function& operator=(function&& f);
13
Effects: Replaces the target of *this with the target of f.
14
Returns: *this function& operator=(nullptr_t);
15
Effects: If *this != NULL, destroys the target of this.
16
Postconditions: !(*this).
17
Returns: *this template function& operator=(F&& f);
18
Effects: function(std::forward(f)).swap(*this);
19
Returns: *this template function& operator=(reference_wrapper f) noexcept;
20
Effects: function(f).swap(*this);
21
Returns: *this ~function();
22
Effects: If *this != NULL, destroys the target of this. § 20.8.11.2.1
556
c ISO/IEC
20.8.11.2.2
N3376
function modifiers
[func.wrap.func.mod]
void swap(function& other) noexcept; 1
Effects: interchanges the targets of *this and other. template void assign(F&& f, const A& a);
2
Effects: function(allocator_arg, a, std::forward(f)).swap(*this) 20.8.11.2.3
function capacity
[func.wrap.func.cap]
explicit operator bool() const noexcept; 1
Returns: true if *this has a target, otherwise false. 20.8.11.2.4
function invocation
[func.wrap.func.inv]
R operator()(ArgTypes... args) const 1
Effects: INVOKE (f, std::forward(args)..., R) (20.8.2), where f is the target object (20.8.1) of *this.
2
Returns: Nothing if R is void, otherwise the return value of INVOKE (f, std::forward( args)..., R).
3
Throws: bad_function_call if !*this; otherwise, any exception thrown by the wrapped callable object. 20.8.11.2.5
function target access
[func.wrap.func.targ]
const std::type_info& target_type() const noexcept; 1
Returns: If *this has a target of type T, typeid(T); otherwise, typeid(void). template T* target() noexcept; template const T* target() const noexcept;
2
Requires: T shall be a type that is Callable (20.8.11.2) for parameter types ArgTypes and return type R.
3
Returns: If target_type() == typeid(T) a pointer to the stored function target; otherwise a null pointer. 20.8.11.2.6
null pointer comparison operators
[func.wrap.func.nullptr]
template bool operator==(const function& f, nullptr_t) noexcept; template bool operator==(nullptr_t, const function& f) noexcept; 1
Returns: !f. template bool operator!=(const function& f, nullptr_t) noexcept; template bool operator!=(nullptr_t, const function& f) noexcept;
2
Returns: § 20.8.11.2.6
(bool) f. 557
c ISO/IEC
20.8.11.2.7
N3376
specialized algorithms
[func.wrap.func.alg]
template void swap(function& f1, function& f2); 1
Effects: f1.swap(f2);
20.8.12 1
Class template hash
[unord.hash]
The unordered associative containers defined in 23.5 use specializations of the class template hash as the default hash function. For all object types Key for which there exists a specialization hash, the instantiation hash shall: — satisfy the Hash requirements (17.6.3.4), with Key as the function call argument type, the DefaultConstructible requirements (Table 19), the CopyAssignable requirements (Table 23), — be swappable (17.6.3.2) for lvalues, — provide two nested types result_type and argument_type which shall be synonyms for size_t and Key, respectively, — satisfy the requirement that if k1 == k2 is true, h(k1) == h(k2) is also true, where h is an object of type hash and k1 and k2 are objects of type Key; — satisfy the requirement that the expression h(k), where h is an object of type hash and k is an object of type Key, shall not throw an exception unless hash is a user-defined specialization that depends on at least one user-defined type. template template template template template template template template template template template template template template template template template template template
2
hash; hash; hash<signed char>; hash; hash; hash; hash<wchar_t>; hash<short>; hash; hash; hash; hash; hash; hash; hash; hash; hash<double>; hash; struct hash;
Requires: the template specializations shall meet the requirements of class template hash (20.8.12).
20.9 1
struct struct struct struct struct struct struct struct struct struct struct struct struct struct struct struct struct struct
Metaprogramming and type traits
[meta]
C++
This subclause describes components used by programs, particularly in templates, to support the widest possible range of types, optimise template code usage, detect type related user errors, and perform type inference and transformation at compile time. It includes type classification traits, type property inspection traits, and type transformations. The type classification traits describe a complete taxonomy § 20.9
558
c ISO/IEC
N3376
of all possible C++ types, and state where in that taxonomy a given type belongs. The type property inspection traits allow important characteristics of types or of combinations of types to be inspected. The type transformations allow certain properties of types to be manipulated.
20.9.1 1
2
3
Requirements
[meta.rqmts]
A UnaryTypeTrait describes a property of a type. It shall be a class template that takes one template type argument and, optionally, additional arguments that help define the property being described. It shall be DefaultConstructible, CopyConstructible, and publicly and unambiguously derived, directly or indirectly, from its BaseCharacteristic, which is a specialization of the template integral_constant (20.9.3), with the arguments to the template integral_constant determined by the requirements for the particular property being described. The member names of the BaseCharacteristic shall not be hidden and shall be unambiguously available in the UnaryTypeTrait. A BinaryTypeTrait describes a relationship between two types. It shall be a class template that takes two template type arguments and, optionally, additional arguments that help define the relationship being described. It shall be DefaultConstructible, CopyConstructible, and publicly and unambiguously derived, directly or indirectly, from its BaseCharacteristic, which is a specialization of the template integral_constant (20.9.3), with the arguments to the template integral_constant determined by the requirements for the particular relationship being described. The member names of the BaseCharacteristic shall not be hidden and shall be unambiguously available in the BinaryTypeTrait. A TransformationTrait modifies a property of a type. It shall be a class template that takes one template type argument and, optionally, additional arguments that help define the modification. It shall define a nested type named type, which shall be a synonym for the modified type.
20.9.2
Header synopsis
[meta.type.synop]
namespace std { // 20.9.3, helper class: template struct integral_constant; typedef integral_constant true_type; typedef integral_constant false_type; // 20.9.4.1, primary type categories: template struct is_void; template struct is_integral; template struct is_floating_point; template struct is_array; template struct is_pointer; template struct is_lvalue_reference; template struct is_rvalue_reference; template struct is_member_object_pointer; template struct is_member_function_pointer; template struct is_enum; template struct is_union; template struct is_class; template struct is_function; // 20.9.4.2, composite type categories: template struct is_reference; template struct is_arithmetic; template struct is_fundamental; template struct is_object; template struct is_scalar; template struct is_compound; template struct is_member_pointer;
§ 20.9.2
559
c ISO/IEC
N3376
// 20.9.4.3, type properties: template struct template struct template struct template struct template struct template struct template struct template struct template struct template struct
is_const; is_volatile; is_trivial; is_trivially_copyable; is_standard_layout; is_pod; is_literal_type; is_empty; is_polymorphic; is_abstract;
template struct is_signed; template struct is_unsigned; template template template template
struct is_constructible; struct is_default_constructible; struct is_copy_constructible; struct is_move_constructible;
template struct is_assignable; template struct is_copy_assignable; template struct is_move_assignable; template struct is_destructible; template template template template
struct is_trivially_constructible; struct is_trivially_default_constructible; struct is_trivially_copy_constructible; struct is_trivially_move_constructible;
template template template template
struct is_trivially_assignable; struct is_trivially_copy_assignable; struct is_trivially_move_assignable; struct is_trivially_destructible;
template template template template
struct is_nothrow_constructible; struct is_nothrow_default_constructible; struct is_nothrow_copy_constructible; struct is_nothrow_move_constructible;
template struct is_nothrow_assignable; template struct is_nothrow_copy_assignable; template struct is_nothrow_move_assignable; template struct is_nothrow_destructible; template struct has_virtual_destructor; // 20.9.5, type property queries: template struct alignment_of; template struct rank; template struct extent; // 20.9.6, type relations: template struct is_same;
§ 20.9.2
560
c ISO/IEC
N3376
template struct is_base_of; template struct is_convertible; // 20.9.7.1, const-volatile modifications: template struct remove_const; template struct remove_volatile; template struct remove_cv; template struct add_const; template struct add_volatile; template struct add_cv; // 20.9.7.2, reference template template template
modifications: struct remove_reference; struct add_lvalue_reference; struct add_rvalue_reference;
// 20.9.7.3, sign modifications: template struct make_signed; template struct make_unsigned; // 20.9.7.4, array modifications: template struct remove_extent; template struct remove_all_extents; // 20.9.7.5, pointer modifications: template struct remove_pointer; template struct add_pointer; // 20.9.7.6, other transformations: template <std::size_t Len, std::size_t Align = default-alignment> // see 20.9.7.6 struct aligned_storage; template <std::size_t Len, class... Types> struct aligned_union; template struct decay; template struct enable_if; template struct conditional; template struct common_type; template struct underlying_type; template class result_of; // not defined template class result_of; } // namespace std 1
The behavior of a program that adds specializations for any of the class templates defined in this subclause is undefined unless otherwise specified.
20.9.3
Helper classes
[meta.help]
namespace std { template struct integral_constant { static constexpr T value = v; typedef T value_type; typedef integral_constant type; constexpr operator value_type() { return value; } }; typedef integral_constant true_type; typedef integral_constant false_type;
§ 20.9.3
561
c ISO/IEC
N3376
} 1
The class template integral_constant and its associated typedefs true_type and false_type are used as base classes to define the interface for various type traits.
20.9.4 1 2
1 2
3
Unary type traits
[meta.unary]
This sub-clause contains templates that may be used to query the properties of a type at compile time. Each of these templates shall be a UnaryTypeTrait (20.9.1) with a BaseCharacteristic of true_type if the corresponding condition is true, otherwise false_type. 20.9.4.1 Primary type categories [meta.unary.cat] The primary type categories correspond to the descriptions given in section 3.9 of the C++ standard. For any given type T, the result of applying one of these templates to T and to cv-qualified T shall yield the same result. [ Note: For any given type T, exactly one of the primary type categories has a value member that evaluates to true. — end note ] Table 47 — Primary type category predicates
1
Template template struct is_void; template struct is_integral; template struct is_floating_point; template struct is_array;
Condition T is void
template struct is_pointer;
T is a pointer type (3.9.2)
template struct is_lvalue_reference; template struct is_rvalue_reference; template struct is_member_object_pointer; template struct is_member_function_pointer; template struct is_enum; template struct is_union; template struct is_class; template struct is_function;
T is an lvalue reference type (8.3.2) T is an rvalue reference type (8.3.2) T is a pointer to non-static data member T is a pointer to non-static member function
Comments
T is an integral type (3.9.1) T is a floating point type (3.9.1) T is an array type (3.9.2) of known or unknown extent
Class template array (23.3.2) is not an array type. Includes pointers to functions but not pointers to non-static members.
T is an enumeration type (3.9.2) T is a union type (3.9.2) T is a class type but not a union type (3.9.2) T is a function type (3.9.2)
20.9.4.2 Composite type traits [meta.unary.comp] These templates provide convenient compositions of the primary type categories, corresponding to the de§ 20.9.4.2
562
c ISO/IEC
2
N3376
scriptions given in section 3.9. For any given type T, the result of applying one of these templates to T, and to cv-qualified T shall yield the same result. Table 48 — Composite type category predicates Template template struct is_reference; template struct is_arithmetic; template struct is_fundamental; template struct is_object; template struct is_scalar; template struct is_compound; template struct is_member_pointer;
20.9.4.3 1 2 3
Condition T is an lvalue reference or an rvalue reference T is an arithmetic type (3.9.1) T is a fundamental type (3.9.1) T is an object type (3.9)
Comments
T is a scalar type (3.9) T is a compound type (3.9.2) T is a pointer to non-static data member or non-static member function
Type properties
[meta.unary.prop]
These templates provide access to some of the more important properties of types. It is unspecified whether the library defines any full or partial specializations of any of these templates. For all of the class templates X declared in this Clause, instantiating that template with a template-argument that is a class template specialization may result in the implicit instantiation of the template argument if and only if the semantics of X require that the argument must be a complete type. Table 49 — Type property predicates Template template struct is_const; template struct is_volatile; template struct is_trivial;
Condition T is const-qualified (3.9.3)
template struct is_trivially_copyable;
T is a trivially copyable type (3.9)
§ 20.9.4.3
T is volatile-qualified (3.9.3) T is a trivial type (3.9)
Preconditions
remove_all_extents::type shall be a complete type or (possibly cv-qualified) void. remove_all_extents::type shall be a complete type or (possibly cv-qualified) void.
563
c ISO/IEC
N3376
Table 49 — Type property predicates (continued) Template template struct is_standard_layout;
Condition T is a standard-layout type (3.9)
template struct is_pod;
T is a POD type (3.9)
template struct is_literal_type;
T is a literal type (3.9)
template struct is_empty;
template struct is_polymorphic;
T is a class type, but not a union type, with no non-static data members other than bit-fields of length 0, no virtual member functions, no virtual base classes, and no base class B for which is_empty::value is false. T is a polymorphic class (10.3)
template struct is_abstract;
T is an abstract class (10.4)
template struct is_signed;
is_arithmetic::value && T(-1) < T(0) is_arithmetic::value && T(0) < T(-1) see below
template struct is_unsigned; template
template struct is_default_constructible;
§ 20.9.4.3
Preconditions remove_all_extents::type shall be a complete type or (possibly cv-qualified) void. remove_all_extents::type shall be a complete type or (possibly cv-qualified) void. remove_all_extents::type shall be a complete type or (possibly cv-qualified) void. If T is a non-union class type, T shall be a complete type.
If T is a non-union class type, T shall be a complete type. If T is a non-union class type, T shall be a complete type.
T and all types in the parameter pack Args shall be complete types, (possibly cv-qualified) void, or arrays of unknown bound. is_T shall be a complete type, constructible::value (possibly cv-qualified) is true. void, or an array of unknown bound. 564
c ISO/IEC
N3376
Table 49 — Type property predicates (continued) Template template struct is_copy_constructible;
Condition is_constructible::value is true.
template struct is_move_constructible;
is_constructible::value is true.
template struct is_assignable;
The expression declval() = declval() is well-formed when treated as an unevaluated operand (Clause 5). Access checking is performed as if in a context unrelated to T and U. Only the validity of the immediate context of the assignment expression is considered. [ Note: The compilation of the expression can result in side effects such as the instantiation of class template specializations and function template specializations, the generation of implicitly-defined functions, and so on. Such side effects are not in the “immediate context” and can result in the program being ill-formed. — end note ] is_assignable::value is true.
template struct is_copy_assignable;
template struct is_move_assignable;
§ 20.9.4.3
is_assignable::value is true.
Preconditions T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound. T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound. T and U shall be complete types, (possibly cv-qualified) void, or arrays of unknown bound.
T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound. T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound.
565
c ISO/IEC
N3376
Table 49 — Type property predicates (continued) Template template struct is_destructible;
template struct is_trivially_default_constructible;
Condition For a complete type T and given template struct test { U u; };, test::˜test() is not deleted. is_constructible::value is true and the variable definition for is_constructible, as defined below, is known to call no operation that is not trivial ( 3.9, 12). is_trivially_constructible::value is true.
template struct is_trivially_copy_constructible;
is_trivially_constructible::value is true.
template struct is_trivially_move_constructible;
is_trivially_constructible::value is true.
template struct is_trivially_assignable;
template struct is_trivially_copy_assignable;
is_assignable::value is true and the assignment, as defined by is_assignable, is known to call no operation that is not trivial (3.9, 12). is_trivially_assignable::value is true.
template struct is_trivially_move_assignable;
is_trivially_assignable::value is true.
template struct is_trivially_destructible;
is_destructible::value is true and the indicated destructor is known to be trivial.
template
Preconditions T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound.
T and all types in the parameter pack Args shall be complete types, (possibly cv-qualified) void, or arrays of unknown bound. T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound. T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound. T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound. T and U shall be complete types, (possibly cv-qualified) void, or arrays of unknown bound.
T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound. T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound. T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound.
566
c ISO/IEC
N3376
Table 49 — Type property predicates (continued) Template template struct is_nothrow_constructible;
template struct is_nothrow_default_constructible;
Condition is_constructible::value is true and the variable definition for is_constructible, as defined below, is known not to throw any exceptions (5.3.7). is_nothrow_constructible::value is true.
template struct is_nothrow_copy_constructible;
is_nothrow_constructible::value is true.
template struct is_nothrow_move_constructible;
is_nothrow_constructible::value is true.
template struct is_nothrow_assignable;
is_assignable::value is true and the assignment is known not to throw any exceptions (5.3.7). is_nothrow_assignable::value is true.
template struct is_nothrow_copy_assignable;
template struct is_nothrow_move_assignable;
is_nothrow_assignable::value is true.
template struct is_nothrow_destructible;
is_destructible::value is true and the indicated destructor is known not to throw any exceptions (5.3.7). T has a virtual destructor (12.4)
template struct has_virtual_destructor;
4
Preconditions T and all types in the parameter pack Args shall be complete types, (possibly cv-qualified) void, or arrays of unknown bound. T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound. T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound. T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound. T and U shall be complete types, (possibly cv-qualified) void, or arrays of unknown bound. T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound. T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound. T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound.
If T is a non-union class type, T shall be a complete type.
[ Example: is_const::value is_const::value is_const::value is_const::value
§ 20.9.4.3
// // // //
true false false false
567
c ISO/IEC
N3376
// true
is_const::value 5
— end example ] [ Example: remove_const::type
// // // //
volatile int const int* const int& int[3]
— end example ] Given the following function prototype: template typename add_rvalue_reference::type create();
the predicate condition for a template specialization is_constructible shall be satisfied if and only if the following variable definition would be well-formed for some invented variable t: T t(create()...);
[ Note: These tokens are never interpreted as a function declaration. — end note ] Access checking is performed as if in a context unrelated to T and any of the Args. Only the validity of the immediate context of the variable initialization is considered. [ Note: The evaluation of the initialization can result in side effects such as the instantiation of class template specializations and function template specializations, the generation of implicitly-defined functions, and so on. Such side effects are not in the “immediate context” and can result in the program being ill-formed. — end note ]
20.9.5 1
Type property queries
[meta.unary.prop.query]
This sub-clause contains templates that may be used to query properties of types at compile time. Table 50 — Type property queries Template template struct alignment_of; template struct rank; template struct extent;
2
Value alignof(T). Requires:alignof(T) shall be a valid expression (5.3.6) If T names an array type, an integer value representing the number of dimensions of T; otherwise, 0. If T is not an array type, or if it has rank less than or equal to I, or if I is 0 and T has type “array of unknown bound of U”, then 0; otherwise, the bound (8.3.4) of the I’th dimension of T, where indexing of I is zero-based
[ Example: // the following assertions hold: assert(rank::value == 0); assert(rank::value == 1); assert(rank::value == 2);
3
— end example ] [ Example: // the following assertions hold: assert(extent::value == 0); assert(extent::value == 2); assert(extent::value == 2);
§ 20.9.5
568
c ISO/IEC
N3376
assert(extent::value == 0); assert((extent::value) == 0); assert((extent::value) == 0); assert((extent::value) == 4); assert((extent::value) == 4);
— end example ]
20.9.6 1 2
Relationships between types
[meta.rel]
This sub-clause contains templates that may be used to query relationships between types at compile time. Each of these templates shall be a BinaryTypeTrait (20.9.1) with a BaseCharacteristic of true_type if the corresponding condition is true, otherwise false_type. Table 51 — Type relationship predicates Template template struct is_same;
Condition T and U name the same type with the same cv-qualifications Base is a base class of Derived (10) without regard to cv-qualifiers or Base and Derived are not unions and name the same class type without regard to cv-qualifiers
template struct is_base_of;
template struct is_convertible;
3
If Base and Derived are non-union class types and are different types (ignoring possible cv-qualifiers) then Derived shall be a complete type. [ Note: Base classes that are private, protected, or ambiguous are, nonetheless, base classes. — end note ] From and To shall be complete types, arrays of unknown bound, or (possibly cv-qualified) void types.
[ Example: struct struct struct struct
B {}; B1 : B {}; B2 : B {}; D : private B1, private B2 {};
is_base_of::value is_base_of::value is_base_of::value is_base_of::value is_base_of::value is_base_of::value is_base_of::value is_base_of::value 4
see below
Comments
// // // // // // // //
true true true true false false false false
— end example ] Given the following function prototype: template typename add_rvalue_reference::type create();
§ 20.9.6
569
c ISO/IEC
N3376
the predicate condition for a template specialization is_convertible shall be satisfied if and only if the return expression in the following code would be well-formed, including any implicit conversions to the return type of the function: To test() { return create(); }
[ Note: This requirement gives well defined results for reference types, void types, array types, and function types. — end note ] Access checking is performed as if in a context unrelated to To and From. Only the validity of the immediate context of the expression of the return-statement (including conversions to the return type) is considered. [ Note: The evaluation of the conversion can result in side effects such as the instantiation of class template specializations and function template specializations, the generation of implicitly-defined functions, and so on. Such side effects are not in the “immediate context” and can result in the program being ill-formed. — end note ]
20.9.7 1
2
Transformations between types
[meta.trans]
This sub-clause contains templates that may be used to transform one type to another following some predefined rule. Each of the templates in this subclause shall be a TransformationTrait (20.9.1). 20.9.7.1 Const-volatile modifications [meta.trans.cv] Table 52 — Const-volatile modifications Template template struct remove_const;
template struct remove_volatile;
template struct remove_cv;
template struct add_const; template struct add_volatile; template struct add_cv; 20.9.7.2
§ 20.9.7.2
Comments The member typedef type shall name the same type as T except that any top-level const-qualifier has been removed. [ Example:remove_const::type evaluates to volatile int, whereas remove_const::type evaluates to const int*. — end example ] The member typedef type shall name the same type as T except that any top-level volatile-qualifier has been removed. [ Example:remove_volatile::type evaluates to const int, whereas remove_volatile::type evaluates to volatile int*. — end example ] The member typedef type shall be the same as T except that any top-level cv-qualifier has been removed. [ Example:remove_cv::type evaluates to int, whereas remove_cv::type evaluates to const volatile int*. — end example ] If T is a reference, function, or top-level const-qualified type, then type shall name the same type as T, otherwise T const. If T is a reference, function, or top-level volatile-qualified type, then type shall name the same type as T, otherwise T volatile. The member typedef type shall name the same type as add_const::type.
Reference modifications
[meta.trans.ref]
570
c ISO/IEC
N3376
Table 53 — Reference modifications Template template struct remove_reference; template struct add_lvalue_reference; template struct add_rvalue_reference;
20.9.7.3
Comments If T has type “reference to T1” then the member typedef type shall name T1; otherwise, type shall name T. If T names an object or function type then the member typedef type shall name T&; otherwise, if T names a type “rvalue reference to T1” then the member typedef type shall name T1&; otherwise, type shall name T. If T names an object or function type then the member typedef type shall name T&&; otherwise, type shall name T. [ Note: This rule reflects the semantics of reference collapsing (8.3.2). For example, when a type T names a type T1&, the type add_rvalue_reference::type is not an rvalue reference. — end note ]
Sign modifications
[meta.trans.sign] Table 54 — Sign modifications
Template template struct make_signed;
template struct make_unsigned;
§ 20.9.7.3
Comments If T names a (possibly cv-qualified) signed integer type (3.9.1) then the member typedef type shall name the type T; otherwise, if T names a (possibly cv-qualified) unsigned integer type then type shall name the corresponding signed integer type, with the same cv-qualifiers as T; otherwise, type shall name the signed integer type with smallest rank (4.13) for which sizeof(T) == sizeof(type), with the same cv-qualifiers as T. Requires:T shall be a (possibly cv-qualified) integral type or enumeration but not a bool type. If T names a (possibly cv-qualified) unsigned integer type (3.9.1) then the member typedef type shall name the type T; otherwise, if T names a (possibly cv-qualified) signed integer type then type shall name the corresponding unsigned integer type, with the same cv-qualifiers as T; otherwise, type shall name the unsigned integer type with smallest rank (4.13) for which sizeof(T) == sizeof(type), with the same cv-qualifiers as T. Requires:T shall be a (possibly cv-qualified) integral type or enumeration but not a bool type.
571
c ISO/IEC
20.9.7.4
N3376
Array modifications
[meta.trans.arr] Table 55 — Array modifications
Template template struct remove_extent;
template struct remove_all_extents; 1
Comments If T names a type “array of U”, the member typedef type shall be U, otherwise T. [ Note: For multidimensional arrays, only the first array dimension is removed. For a type “array of const U”, the resulting type is const U. — end note ] If T is “multi-dimensional array of U”, the resulting member typedef type is U, otherwise T.
[Example // the following assertions hold: assert((is_same::value)); assert((is_same::value)); assert((is_same::value)); assert((is_same::value));
2
— end example ] [Example // the following assertions hold: assert((is_same::value)); assert((is_same::value)); assert((is_same::value)); assert((is_same::value));
— end example ] 20.9.7.5 Pointer modifications
[meta.trans.ptr] Table 56 — Pointer modifications
Template template struct remove_pointer; template struct add_pointer;
§ 20.9.7.5
Comments If T has type “(possibly cv-qualified) pointer to T1” then the member typedef type shall name T1; otherwise, it shall name T. The member typedef type shall name the same type as remove_reference::type*.
572
c ISO/IEC
20.9.7.6
N3376
Other transformations
[meta.trans.other]
Table 57 — Other transformations Template template <std::size_t Len, std::size_t Align = default-alignment > struct aligned_storage;
Condition Len shall not be zero. Align shall be equal to alignof(T) for some type T or to default-alignment.
template <std::size_t Len, class... Types> struct aligned_union;
At least one type is provided.
template struct decay;
template struct enable_if; template struct conditional;
§ 20.9.7.6
Comments The value of default-alignment shall be the most stringent alignment requirement for any C++ object type whose size is no greater than Len (3.9). The member typedef type shall be a POD type suitable for use as uninitialized storage for any object whose size is at most Len and whose alignment is a divisor of Align. The member typedef type shall be a POD type suitable for use as uninitialized storage for any object whose type is listed in Types; its size shall be at least Len. The static member alignment_value shall be an integral constant of type std::size_t whose value is the strictest alignment of all types listed in Types. Let U be remove_reference::type. If is_array::value is true, the member typedef type shall equal remove_extent::type*. If is_function::value is true, the member typedef type shall equal add_pointer::type. Otherwise the member typedef type equals remove_cv::type. [ Note: This behavior is similar to the lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) conversions applied when an lvalue expression is used as an rvalue, but also strips cv-qualifiers from class types in order to more closely model by-value argument passing. — end note ] If B is true, the member typedef type shall equal T; otherwise, there shall be no member typedef type. If B is true, the member typedef type shall equal T. If B is false, the member typedef type shall equal F.
573
c ISO/IEC
N3376
Table 57 — Other transformations (continued) Template template struct common_type;
template struct underlying_type; template struct result_of;
1
Condition
Comments The member typedef type shall be defined as set out below. All types in the parameter pack T shall be complete or (possibly cv) void. A program may specialize this trait if at least one template parameter in the specialization is a user-defined type. [ Note: Such specializations are needed when only explicit conversions are desired among the template arguments. — end note ] The member typedef type shall name the underlying type of T. The member typedef type shall name the type decltype(INVOKE(declval(), declval()...))
T shall be an enumeration type (7.2) Fn shall be a callable type (20.8.1), reference to function, or reference to callable type. The expression decltype(INVOKE(declval(), declval()...)) shall be well formed.
[ Note: A typical implementation would define aligned_storage as: template <std::size_t Len, std::size_t Alignment> struct aligned_storage { typedef struct { alignas(Alignment) unsigned char __data[Len]; } type; };
2 3
— end note ] It is implementation-defined whether any extended alignment is supported (3.11). The nested typedef common_type::type shall be defined as follows: template struct common_type; template struct common_type { typedef T type; }; template struct common_type { typedef decltype(true ? declval() : declval()) type; }; template struct common_type { typedef typename common_type::type type; };
§ 20.9.7.6
574
c ISO/IEC
4
N3376
[ Example: Given these definitions: typedef bool (&PF1)(); typedef short (*PF2)(long); struct S { operator PF2() const; double operator()(char, int&); void fn(long) const; char data; }; typedef void (S::*PMF)(long) const; typedef char S::*PMD;
the following assertions will hold: static_assert(is_same::type, short>::value, "Error!"); static_assert(is_same::type, double>::value, "Error!"); static_assert(is_same::value, "Error!"); static_assert(is_same::type, void>::value, "Error!"); static_assert(is_same::value, "Error!"); static_assert(is_same::value, "Error!");
— end example ]
20.10 20.10.1 1
2
Compile-time rational arithmetic
[ratio]
In general
[ratio.general]
This subclause describes the ratio library. It provides a class template ratio which exactly represents any finite rational number with a numerator and denominator representable by compile-time constants of type intmax_t. Throughout this subclause, if the template argument types R1 and R2 are not specializations of the ratio template, the program is ill-formed.
20.10.2
Header synopsis
[ratio.syn]
namespace std { // 20.10.3, class template ratio template class ratio; // 20.10.4, ratio arithmetic template
using using using using
// 20.10.5, ratio comparison template
struct struct struct struct struct struct
ratio_add = see below ; ratio_subtract = see below ; ratio_multiply = see below ; ratio_divide = see below ;
ratio_equal; ratio_not_equal; ratio_less; ratio_less_equal; ratio_greater; ratio_greater_equal;
// 20.10.6, convenience SI typedefs typedef ratio yocto; typedef ratio zepto;
§ 20.10.2
// see below // see below
575
c ISO/IEC
typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef
N3376
ratio ratio ratio ratio ratio ratio ratio ratio ratio< 10, 1> ratio< 100, 1> ratio< 1000, 1> ratio< 1000000, 1> ratio< 1000000000, 1> ratio< 1000000000000, 1> ratio< 1000000000000000, 1> ratio< 1000000000000000000, 1> ratio< 1000000000000000000000, 1> ratio
atto; femto; pico; nano; micro; milli; centi; deci; deca; hecto; kilo; mega; giga; tera; peta; exa; zetta; yotta;
// see below // see below
}
20.10.3
Class template ratio
[ratio.ratio]
namespace std { template class ratio { public: typedef ratio type; static constexpr intmax_t num; static constexpr intmax_t den; }; } 1
2
If the template argument D is zero or the absolute values of either of the template arguments N and D is not representable by type intmax_t, the program is ill-formed. [ Note: These rules ensure that infinite ratios are avoided and that for any negative input, there exists a representable value of its absolute value which is positive. In a two’s complement representation, this excludes the most negative value. — end note ] The static data members num and den shall have the following values, where gcd represents the greatest common divisor of the absolute values of N and D: — num shall have the value sign(N) * sign(D) * abs(N) / gcd. — den shall have the value abs(D) / gcd.
20.10.4 1
2
3
Arithmetic on ratios
[ratio.arithmetic]
Each of the alias templates ratio_add, ratio_subtract, ratio_multiply, and ratio_divide denotes the result of an arithmetic computation on two ratios R1 and R2. With X and Y computed (in the absence of arithmetic overflow) as specified by Table 58, each alias denotes a ratio such that U is the same as ratio<X, Y>::num and V is the same as ratio<X, Y>::den. If it is not possible to represent U or V with intmax_t, the program is ill-formed. Otherwise, an implementation should yield correct values of U and V. If it is not possible to represent X or Y with intmax_t, the program is ill-formed unless the implementation yields correct values of U and V. [ Example: static_assert(ratio_add::num == 1, "1/3+1/6 == 1/2"); static_assert(ratio_add::den == 2, "1/3+1/6 == 1/2"); static_assert(ratio_multiply::num == 1, "1/3*3/2 == 1/2");
§ 20.10.4
576
c ISO/IEC
N3376
Table 58 — Expressions used to perform ratio arithmetic Type ratio_add ratio_subtract ratio_multiply ratio_divide
Value of X R1::num * R2::den + R2::num * R1::den R1::num * R2::den R2::num * R1::den R1::num * R2::num R1::num * R2::den
Value of Y R1::den * R2::den R1::den * R2::den R1::den * R2::den R1::den * R2::num
static_assert(ratio_multiply::den == 2, "1/3*3/2 == 1/2"); // The following cases may cause the program to be ill-formed under some implementations static_assert(ratio_add::num == 2, "1/MAX+1/MAX == 2/MAX"); static_assert(ratio_add::den == INT_MAX, "1/MAX+1/MAX == 2/MAX"); static_assert(ratio_multiply::num == 1, "1/MAX * MAX/2 == 1/2"); static_assert(ratio_multiply::den == 2, "1/MAX * MAX/2 == 1/2");
— end example ]
20.10.5
Comparison of ratios
[ratio.comparison]
template struct ratio_equal : integral_constant { }; 1
If R1::num == R2::num and R1::den == R2::den, ratio_equal shall be derived from integral_constant; otherwise it shall be derived from integral_constant. template struct ratio_not_equal : integral_constant { }; template struct ratio_less : integral_constant { };
2
If R1::num * R2::den < R2::num * R1::den, ratio_less shall be derived from integral_constant; otherwise it shall be derived from integral_constant. Implementations may use other algorithms to compute this relationship to avoid overflow. If overflow occurs, the program is ill-formed. template struct ratio_less_equal : integral_constant { }; template struct ratio_greater : integral_constant { }; template struct ratio_greater_equal : integral_constant { };
§ 20.10.5
577
c ISO/IEC
20.10.6 1
SI types for ratio
[ratio.si]
For each of the typedefs yocto, zepto, zetta, and yotta, if both of the constants used in its specification are representable by intmax_t, the typedef shall be defined; if either of the constants is not representable by intmax_t, the typedef shall not be defined.
20.11 Time utilities 20.11.1 In general 1
N3376
[time] [time.general]
This subclause describes the chrono library (20.11.2) and various C functions (20.11.8) that provide generally useful time utilities.
20.11.2
Header synopsis
[time.syn]
namespace std { namespace chrono { // 20.11.5, class template duration template class duration; // 20.11.6, class template time_point template class time_point; }
// namespace chrono
// 20.11.4.3 common_type specializations template struct common_type; template struct common_type; namespace chrono { // 20.11.4, customization traits template struct treat_as_floating_point; template struct duration_values; // 20.11.5.5, duration arithmetic template typename common_type::type constexpr operator+(const duration& lhs, const duration& rhs); template typename common_type::type constexpr operator-(const duration& lhs, const duration& rhs); template duration constexpr operator*(const duration& d, const Rep2& s); template duration constexpr operator*(const Rep1& s, const duration& d); template duration constexpr operator/(const duration& d, const Rep2& s); template typename common_type::type constexpr operator/(const duration& lhs, const duration& rhs); template
§ 20.11.2
578
c ISO/IEC
N3376
duration constexpr operator%(const duration& d, const Rep2& s); template typename common_type::type constexpr operator%(const duration& lhs, const duration& rhs); // 20.11.5.6, duration comparisons template & lhs, Period2>& rhs);
// 20.11.5.7, duration_cast template constexpr ToDuration duration_cast(const duration& d); // convenience typedefs typedef duration<signed typedef duration<signed typedef duration<signed typedef duration<signed typedef duration<signed typedef duration<signed
integer integer integer integer integer integer
type type type type type type
of of of of of of
at at at at at at
least least least least least least
64 55 45 35 29 23
bits , nano> nanoseconds; bits , micro> microseconds; bits , milli> milliseconds; bits > seconds; bits , ratio< 60>> minutes; bits , ratio> hours;
// 20.11.6.5, time_point arithmetic template time_point operator+(const time_point& lhs, const duration& rhs); template time_point operator+(const duration& lhs, const time_point& rhs); template time_point operator-(const time_point& lhs, const duration& rhs); template typename common_type::type operator-(const time_point& lhs, const time_point& rhs); // 20.11.6.6 time_point comparisons template bool operator==(const time_point& lhs,
§ 20.11.2
579
c ISO/IEC
N3376
const time_point& rhs); template bool operator!=(const time_point& lhs, const time_point& rhs); template bool operator< (const time_point& lhs, const time_point& rhs); template bool operator (const time_point& lhs, const time_point& rhs); template bool operator>=(const time_point& lhs, const time_point& rhs); // 20.11.6.7, time_point_cast template time_point time_point_cast(const time_point& t); // 20.11.7, clocks class system_clock; class steady_clock; class high_resolution_clock; } }
// namespace chrono // namespace std
20.11.3 1
2
Clock requirements
[time.clock.req]
A clock is a bundle consisting of a duration, a time_point, and a function now() to get the current time_point. The origin of the clock’s time_point is referred to as the clock’s epoch. A clock shall meet the requirements in Table 59. In Table 59 C1 and C2 denote clock types. t1 and t2 are values returned by C1::now() where the call returning t1 happens before (1.10) the call returning t2 and both of these calls occur before C1::time_point::max(). [ Note: this means C1 did not wrap around between t1 and t2. — end note ] Table 59 — Clock requirements Expression C1::rep C1::period C1::duration C1::time_point
§ 20.11.3
Return type An arithmetic type or a class emulating an arithmetic type a specialization of ratio chrono::duration chrono::time_point or chrono::time_point
Operational semantics The representation type of C1::duration. The tick period of the clock in seconds. The duration type of the clock. The time_point type of the clock. C1 and C2 shall refer to the same epoch.
580
c ISO/IEC
N3376
Table 59 — Clock requirements (continued)
3
4
Expression C1::is_steady
Return type const bool
C1::now()
C1::time_point
Operational semantics true if t1
// // d2; // //
holds a count of minutes using a long holds a count of milliseconds using a long long 1 holds a count with a tick period of 30 of a second (30 Hz) using a double
— end example ] 20.11.5.1
duration constructors
[time.duration.cons]
template constexpr explicit duration(const Rep2& r);
§ 20.11.5.1
583
c ISO/IEC
1
N3376
Remarks: This constructor shall not participate in overload resolution unless Rep2 is implicitly convertible to rep and — treat_as_floating_point::value is true or — treat_as_floating_point::value is false. [ Example: duration d(3); duration d(3.5);
// OK // error
— end example ] 2
Effects: Constructs an object of type duration.
3
Postcondition: count() == static_cast(r). template constexpr duration(const duration& d);
4
Remarks: This constructor shall not participate in overload resolution unless treat_as_floating_point::value is true or both ratio_divide::den is 1 and treat_as_floating_point::value is false. [ Note: This requirement prevents implicit truncation error when converting between integral-based duration types. Such a construction could easily lead to confusion about the value of the duration. — end note ] [ Example: duration ms(3); duration us = ms; duration ms2 = us;
// OK // error
— end example ] 5
Effects: Constructs an object of type duration, constructing rep_ from duration_cast(d).count(). 20.11.5.2
duration observer
[time.duration.observer]
constexpr rep count() const; 1
Returns: rep_. 20.11.5.3
duration arithmetic
[time.duration.arithmetic]
constexpr duration operator+() const; 1
Returns: *this. constexpr duration operator-() const;
2
Returns: duration(-rep_);. duration& operator++();
3
Effects: ++rep_.
4
Returns: *this.
§ 20.11.5.3
584
c ISO/IEC
N3376
duration operator++(int); 5
Returns: duration(rep_++);. duration& operator--();
6
Effects: --rep_.
7
Returns: *this. duration operator--(int);
8
Returns: duration(rep_--);. duration& operator+=(const duration& d);
9 10
Effects: rep_ += d.count(). Returns: *this. duration& operator-=(const duration& d);
11
Effects: rep_ -= d.count().
12
Returns: *this. duration& operator*=(const rep& rhs);
13
Effects: rep_ *= rhs.
14
Returns: *this. duration& operator/=(const rep& rhs);
15
Effects: rep_ /= rhs.
16
Returns: *this. duration& operator%=(const rep& rhs);
17
Effects: rep_ %= rhs.
18
Returns: *this. duration& operator%=(const duration& rhs);
19
Effects: rep_ %= rhs.count().
20
Returns: *this.
§ 20.11.5.3
585
c ISO/IEC
20.11.5.4
N3376
duration special values
[time.duration.special]
static constexpr duration zero(); 1
Returns: duration(duration_values::zero()). static constexpr duration min();
2
Returns: duration(duration_values::min()). static constexpr duration max();
3
Returns: duration(duration_values::max()). 20.11.5.5
1
duration non-member arithmetic
[time.duration.nonmember]
In the function descriptions that follow, CD represents the return type of the function. CR(A,B) represents common_type::type. template constexpr typename common_type::type operator+(const duration& lhs, const duration& rhs);
2
Returns: CD(CD(lhs).count() + CD(rhs).count()). template constexpr typename common_type::type operator-(const duration& lhs, const duration& rhs);
3
Returns: CD(CD(lhs).count() - CD(rhs).count()). template constexpr duration operator*(const duration& d, const Rep2& s);
4
Remarks: This operator shall not participate in overload resolution unless Rep2 is implicitly convertible to CR(Rep1, Rep2).
5
Returns: CD(CD(d).count() * s). template constexpr duration operator*(const Rep1& s, const duration& d);
6
Remarks: This operator shall not participate in overload resolution unless Rep1 is implicitly convertible to CR(Rep1, Rep2).
7
Returns: d * s. template constexpr duration operator/(const duration& d, const Rep2& s);
§ 20.11.5.5
586
c ISO/IEC
N3376
8
Remarks: This operator shall not participate in overload resolution unless Rep2 is implicitly convertible to CR(Rep1, Rep2) and Rep2 is not an instantiation of duration.
9
Returns: CD(CD(d).count() / s). template constexpr typename common_type::type operator/(const duration& lhs, const duration& rhs);
10
Returns: CD(lhs).count() / CD(rhs).count(). template constexpr duration operator%(const duration& d, const Rep2& s);
11
Remarks: This operator shall not participate in overload resolution unless Rep2 is implicitly convertible to CR(Rep1, Rep2) and Rep2 is not an instantiation of duration.
12
Returns: CD(CD(d).count() % s). template constexpr typename common_type::type operator%(const duration& lhs, const duration& rhs);
13
Returns: CD(CD(lhs).count() % CD(rhs).count()). 20.11.5.6
1
duration comparisons
[time.duration.comparisons]
In the function descriptions that follow, CT represents common_type::type, where A and B are the types of the two arguments to the function. template constexpr bool operator==(const duration& lhs, const duration& rhs);
2
Returns: CT(lhs).count() == CT(rhs).count(). template constexpr bool operator!=(const duration& lhs, const duration& rhs);
3
Returns: !(lhs == rhs). template constexpr bool operator=(const duration& lhs, const duration& rhs);
7
Returns: !(lhs < rhs). 20.11.5.7
duration_cast
[time.duration.cast]
template constexpr ToDuration duration_cast(const duration& d); 1
Remarks: This function shall not participate in overload resolution unless ToDuration is an instantiation of duration.
2
Returns: Let CF be ratio_divide, and CR be common_type< typename ToDuration::rep, Rep, intmax_t>::type. — If CF::num == 1 and CF::den == 1, returns ToDuration(static_cast(d.count()))
— otherwise, if CF::num != 1 and CF::den == 1, returns ToDuration(static_cast( static_cast(d.count()) * static_cast(CF::num)))
— otherwise, if CF::num == 1 and CF::den != 1, returns ToDuration(static_cast( static_cast(d.count()) / static_cast(CF::den)))
— otherwise, returns ToDuration(static_cast( static_cast(d.count()) * static_cast(CF::num) / static_cast(CF::den)))
Notes: This function does not use any implicit conversions; all conversions are done with static_cast. It avoids multiplications and divisions when it is known at compile time that one or more arguments is 1. Intermediate computations are carried out in the widest representation and only converted to the destination representation at the final step.
20.11.6
Class template time_point
[time.point]
template class time_point { public: typedef Clock clock; typedef Duration duration; typedef typename duration::rep rep; typedef typename duration::period period; private: duration d_; // exposition only public: // 20.11.6.1, construct: time_point(); // has value epoch
§ 20.11.6
588
c ISO/IEC
N3376
explicit time_point(const duration& d); // same as time_point() + d template time_point(const time_point& t); // 20.11.6.2, observer: duration time_since_epoch() const; // 20.11.6.3, arithmetic: time_point& operator+=(const duration& d); time_point& operator-=(const duration& d); // 20.11.6.4, special values: static constexpr time_point min(); static constexpr time_point max(); }; 1 2
Clock shall meet the Clock requirements (20.11.7). If Duration is not an instance of duration, the program is ill-formed. 20.11.6.1 time_point constructors
[time.point.cons]
time_point(); 1
Effects: Constructs an object of type time_point, initializing d_ with duration::zero(). Such a time_point object represents the epoch. time_point(const duration& d);
2
Effects: Constructs an object of type time_point, initializing d_ with d. Such a time_point object represents the epoch + d. template time_point(const time_point& t);
3
Remarks: This constructor shall not participate in overload resolution unless Duration2 is implicitly convertible to duration.
4
Effects: Constructs an object of type time_point, initializing d_ with t.time_since_epoch(). 20.11.6.2
time_point observer
[time.point.observer]
duration time_since_epoch() const; 1
Returns: d_. 20.11.6.3
time_point arithmetic
[time.point.arithmetic]
time_point& operator+=(const duration& d); 1
Effects: d_ += d.
2
Returns: *this. time_point& operator-=(const duration& d);
3
Effects: d_ -= d.
4
Returns: *this. § 20.11.6.3
589
c ISO/IEC
20.11.6.4
N3376
time_point special values
[time.point.special]
static constexpr time_point min(); 1
Returns: time_point(duration::min()). static constexpr time_point max();
2
Returns: time_point(duration::max()). 20.11.6.5
time_point non-member arithmetic
[time.point.nonmember]
template time_point operator+(const time_point& lhs, const duration& rhs); 1
Returns: CT(lhs) += rhs, where CT is the type of the return value. template time_point operator+(const duration& lhs, const time_point& rhs);
2
Returns: rhs + lhs. template time_point operator-(const time_point& lhs, const duration& rhs);
3
Returns: lhs + (-rhs). template typename common_type::type operator-(const time_point& lhs, const time_point& rhs);
4
Returns: lhs.time_since_epoch() - rhs.time_since_epoch(). 20.11.6.6
time_point comparisons
[time.point.comparisons]
template bool operator==(const time_point& lhs, const time_point& rhs); 1
Returns: lhs.time_since_epoch() == rhs.time_since_epoch(). template bool operator!=(const time_point& lhs, const time_point& rhs);
2
Returns: !(lhs == rhs). template bool operator=(const time_point& lhs, const time_point& rhs);
6
Returns: !(lhs < rhs). 20.11.6.7
time_point_cast
[time.point.cast]
template time_point time_point_cast(const time_point& t); 1
Remarks: This function shall not participate in overload resolution unless ToDuration is an instantiation of duration.
2
Returns: time_point(duration_cast(t.time_since_epoch())).
20.11.7
Clocks
[time.clock]
1
The types defined in this subclause shall satisfy the TrivialClock requirements (20.11.3). 20.11.7.1 Class system_clock [time.clock.system]
1
Objects of class system_clock represent wall clock time from the system-wide realtime clock. class system_clock { public: typedef see below rep; typedef ratio period; typedef chrono::duration duration; typedef chrono::time_point<system_clock> time_point; static const bool is_steady = unspecified ; static time_point now() noexcept; // Map to C API static time_t static time_point }; typedef unspecified
2
to_time_t (const time_point& t) noexcept; from_time_t(time_t t) noexcept;
system_clock::rep;
Requires: system_clock::duration::min() < system_clock::duration::zero() shall be true. [ Note: This implies that rep is a signed type. — end note ] static time_t to_time_t(const time_point& t) noexcept;
3
Returns: A time_t object that represents the same point in time as t when both values are restricted to the coarser of the precisions of time_t and time_point. It is implementation defined whether values are rounded or truncated to the required precision. § 20.11.7.1
591
c ISO/IEC
N3376
static time_point from_time_t(time_t t) noexcept; 4
1
Returns: A time_point object that represents the same point in time as t when both values are restricted to the coarser of the precisions of time_t and time_point. It is implementation defined whether values are rounded or truncated to the required precision. 20.11.7.2 Class steady_clock [time.clock.steady] Objects of class steady_clock represent clocks for which values of time_point never decrease as physical time advances and for which values of time_point advance at a steady rate relative to real time. That is, the clock may not be adjusted. class steady_clock { public: typedef unspecified rep; typedef ratio period; typedef chrono::duration duration; typedef chrono::time_point time_point; static const bool is_steady = true; static time_point now() noexcept; };
1
20.11.7.3 Class high_resolution_clock [time.clock.hires] Objects of class high_resolution_clock represent clocks with the shortest tick period. high_resolution_clock may be a synonym for system_clock or steady_clock. class high_resolution_clock { public: typedef unspecified rep; typedef ratio period; typedef chrono::duration duration; typedef chrono::time_point time_point; static const bool is_steady = unspecified ; static time_point now() noexcept; };
20.11.8 1
Date and time functions
[date.time]
Table 60 describes the header . Table 60 — Header synopsis Type Macros: NULL Types: size_t Struct: tm Functions: asctime clock ctime gmtime
2
Name(s) CLOCKS_PER_SEC clock_t time_t
difftime mktime
localtime time
strftime
The contents are the same as the Standard C library header .230 The functions asctime, ctime, gmtime, and localtime are not required to avoid data races (17.6.5.9). See also: ISO C Clause 7.12, Amendment 1 Clause 4.6.4. 230) strftime supports the C conversion specifiers C, D, e, F, g, G, h, r, R, t, T, u, V, and z, and the modifiers E and O.
§ 20.11.8
592
c ISO/IEC
20.12 20.12.1
N3376
Class template scoped_allocator_adaptor Header <scoped_allocator> synopsis
[allocator.adaptor] [allocator.adaptor.syn]
// scoped allocator adaptor template class scoped_allocator_adaptor; template bool operator==(const scoped_allocator_adaptor& const scoped_allocator_adaptor& template bool operator!=(const scoped_allocator_adaptor& const scoped_allocator_adaptor& 1
a, b) noexcept; a, b) noexcept;
The class template scoped_allocator_adaptor is an allocator template that specifies the memory resource (the outer allocator) to be used by a container (as any other allocator does) and also specifies an inner allocator resource to be passed to the constructor of every element within the container. This adaptor is instantiated with one outer and zero or more inner allocator types. If instantiated with only one allocator type, the inner allocator becomes the scoped_allocator_adaptor itself, thus using the same allocator resource for the container and every element within the container and, if the elements themselves are containers, each of their elements recursively. If instantiated with more than one allocator, the first allocator is the outer allocator for use by the container, the second allocator is passed to the constructors of the container’s elements, and, if the elements themselves are containers, the third allocator is passed to the elements’ elements, and so on. If containers are nested to a depth greater than the number of allocators, the last allocator is used repeatedly, as in the single-allocator case, for any remaining recursions. [ Note: The scoped_allocator_adaptor is derived from the outer allocator type so it can be substituted for the outer allocator type in most expressions. — end note ] namespace std { template class scoped_allocator_adaptor : public OuterAlloc { private: typedef allocator_traits OuterTraits; // exposition only scoped_allocator_adaptor inner; // exposition only public: typedef OuterAlloc outer_allocator_type; typedef see below inner_allocator_type; typedef typedef typedef typedef typedef typedef typedef
typename typename typename typename typename typename typename
OuterTraits::value_type value_type; OuterTraits::size_type size_type; OuterTraits::difference_type difference_type; OuterTraits::pointer pointer; OuterTraits::const_pointer const_pointer; OuterTraits::void_pointer void_pointer; OuterTraits::const_void_pointer const_void_pointer;
typedef see below propagate_on_container_copy_assignment; typedef see below propagate_on_container_move_assignment; typedef see below propagate_on_container_swap; template struct rebind { typedef scoped_allocator_adaptor< OuterTraits::template rebind_alloc, InnerAllocs...> other; };
§ 20.12.1
593
c ISO/IEC
N3376
scoped_allocator_adaptor(); template scoped_allocator_adaptor(OuterA2&& outerAlloc, const InnerAllocs&... innerAllocs) noexcept; scoped_allocator_adaptor(const scoped_allocator_adaptor& other) noexcept; scoped_allocator_adaptor(scoped_allocator_adaptor&& other) noexcept; template scoped_allocator_adaptor( const scoped_allocator_adaptor& other) noexcept; template scoped_allocator_adaptor( scoped_allocator_adaptor&& other) noexcept; ~scoped_allocator_adaptor(); inner_allocator_type& inner_allocator() noexcept; const inner_allocator_type& inner_allocator() const noexcept; outer_allocator_type& outer_allocator() noexcept; const outer_allocator_type& outer_allocator() const noexcept; pointer allocate(size_type n); pointer allocate(size_type n, const_void_pointer hint); void deallocate(pointer p, size_type n); size_type max_size() const; template void construct(T* p, Args&& args); template void construct(pair* p, piecewise_construct_t, tuple x, tuple y); template void construct(pair* p); template void construct(pair* p, U&& x, V&& y); template void construct(pair* p, const pair& x); template void construct(pair* p, pair&& x); template void destroy(T* p); scoped_allocator_adaptor select_on_container_copy_construction() const; }; template bool operator==(const scoped_allocator_adaptor& const scoped_allocator_adaptor& template bool operator!=(const scoped_allocator_adaptor& const scoped_allocator_adaptor&
a, b) noexcept; a, b) noexcept;
}
§ 20.12.1
594
c ISO/IEC
20.12.2
Scoped allocator adaptor member types
N3376
[allocator.adaptor.types]
typedef see below inner_allocator_type; 1
Type: scoped_allocator_adaptor if sizeof...(InnerAllocs) is zero; otherwise, scoped_allocator_adaptor. typedef see below propagate_on_container_copy_assignment;
2
Type: true_type if allocator_traits::propagate_on_container_copy_assignment::value is true for any A in the set of OuterAlloc and InnerAllocs...; otherwise, false_type. typedef see below propagate_on_container_move_assignment;
3
Type: true_type if allocator_traits::propagate_on_container_move_assignment::value is true for any A in the set of OuterAlloc and InnerAllocs...; otherwise, false_type. typedef see below propagate_on_container_swap;
4
Type: true_type if allocator_traits::propagate_on_container_swap::value is true for any A in the set of OuterAlloc and InnerAllocs...; otherwise, false_type.
20.12.3
Scoped allocator adaptor constructors
[allocator.adaptor.cnstr]
scoped_allocator_adaptor(); 1
Effects: value-initializes the OuterAlloc base class and the inner allocator object. template scoped_allocator_adaptor(OuterA2&& outerAlloc, const InnerAllocs&... innerAllocs) noexcept;
2
Requires: OuterAlloc shall be constructible from OuterA2.
3
Effects: initializes the OuterAlloc base class with std::forward(outerAlloc) and inner with innerAllocs... (hence recursively initializing each allocator within the adaptor with the corresponding allocator from the argument list). scoped_allocator_adaptor(const scoped_allocator_adaptor& other) noexcept;
4
Effects: initializes each allocator within the adaptor with the corresponding allocator from other. scoped_allocator_adaptor(scoped_allocator_adaptor&& other) noexcept;
5
Effects: move constructs each allocator within the adaptor with the corresponding allocator from other. template scoped_allocator_adaptor(const scoped_allocator_adaptor& other) noexcept;
§ 20.12.3
595
c ISO/IEC
N3376
6
Requires: OuterAlloc shall be constructible from OuterA2.
7
Effects: initializes each allocator within the adaptor with the corresponding allocator from other. template scoped_allocator_adaptor(scoped_allocator_adaptor&& other) noexcept;
8
Requires: OuterAlloc shall be constructible from OuterA2.
9
Effects: initializes each allocator within the adaptor with the corresponding allocator rvalue from other.
20.12.4 1
Scoped allocator adaptor members
[allocator.adaptor.members]
In the construct member functions, OUTERMOST(x) is x if x does not have an outer_allocator() member function and OUTERMOST(x.outer_allocator()) otherwise; OUTERMOST_ALLOC_TRAITS(x) is allocator_traits<decltype(OUTERMOST (x))>. [ Note: OUTERMOST (x) and OUTERMOST_ALLOC_TRAITS(x) are recursive operations. It is incumbent upon the definition of outer_allocator() to ensure that the recursion terminates. It will terminate for all instantiations of scoped_allocator_adaptor. — end note ] inner_allocator_type& inner_allocator() noexcept; const inner_allocator_type& inner_allocator() const noexcept;
2
Returns: *this if sizeof...(InnerAllocs) is zero; otherwise, inner. outer_allocator_type& outer_allocator() noexcept;
3
Returns: static_cast(*this). const outer_allocator_type& outer_allocator() const noexcept;
4
Returns: static_cast(*this). pointer allocate(size_type n);
5
Returns: allocator_traits::allocate(outer_allocator(), n). pointer allocate(size_type n, const_void_pointer hint);
6
Returns: allocator_traits::allocate(outer_allocator(), n, hint). void deallocate(pointer p, size_type n) noexcept;
7
Effects: allocator_traits::deallocate(outer_allocator(), p, n); size_type max_size() const;
8
Returns: allocator_traits::max_size(outer_allocator()).
§ 20.12.4
596
c ISO/IEC
N3376
template void construct(T* p, Args&&... args); 9
Effects: — If uses_allocator::value is false and is_constructible::value is true, calls OUTERMOST_ALLOC_TRAITS(*this)::construct( OUTERMOST (*this), p, std::forward(args)...). — Otherwise, if uses_allocator::value is true and is_constructible::value is true, calls OUTERMOST_ALLOC_TRAITS(*this)::construct(OUTERMOST (*this), p, allocator_arg, inner_allocator(), std::forward(args)...). — Otherwise, if uses_allocator::value is true and is_constructible::value is true, calls OUTERMOST_ALLOC_TRAITS(*this):: construct(OUTERMOST (*this), p, std::forward(args)..., inner_allocator()). — Otherwise, the program is ill-formed. [ Note: An error will result if uses_allocator evaluates to true but the specific constructor does not take an allocator. This definition prevents a silent failure to pass an inner allocator to a contained element. — end note ] template void construct(pair* p,piecewise_construct_t, tuple x, tuple y);
10
Requires: all of the types in Args1 and Args2 shall be CopyConstructible (Table 21).
11
Effects: Constructs a tuple object xprime from x by the following rules: — If uses_allocator::value is false and is_constructible::value is true, then xprime is x. — Otherwise, if uses_allocator::value is true and is_constructible::value is true, then xprime is tuple_cat(tuple( allocator_arg, inner_allocator_type()), x). — Otherwise, if uses_allocator::value is true and is_constructible::value is true, then xprime is tuple_cat(x, tuple(inner_allocator_type())). — Otherwise, the program is ill-formed. and constructs a tuple object yprime from y by the following rules: — If uses_allocator::value is false and is_constructible::value is true, then yprime is y. — Otherwise, if uses_allocator::value is true and is_constructible::value is true, then yprime is tuple_cat(tuple( allocator_arg, inner_allocator_type()), y). — Otherwise, if uses_allocator::value is true and is_constructible::value is true, then yprime is tuple_cat(y, tuple(inner_allocator_type())). § 20.12.4
597
c ISO/IEC
N3376
— Otherwise, the program is ill-formed. then calls OUTERMOST_ALLOC_TRAITS (*this)::construct(OUTERMOST (*this), p, piecewise_construct, xprime, yprime). template void construct(pair* p); 12
Effects: equivalent to this->construct(p, piecewise_construct, tuple(), tuple()). template void construct(pair* p, U&& x, V&& y);
13
Effects: equivalent to this->construct(p, piecewise_construct, forward_as_tuple(std::forward(x)), forward_as_tuple(std::forward(y))). template void construct(pair* p, const pair& x);
14
Effects: equivalent to this->construct(p, piecewise_construct, forward_as_tuple(x.first), forward_as_tuple(x.second)). template void construct(pair* p, pair&& x);
15
Effects: equivalent to this->construct(p, piecewise_construct, forward_as_tuple(std::forward(x.first)), forward_as_tuple(std::forward(x.second))). template void destroy(T* p);
16
Effects: calls OUTERMOST_ALLOC_TRAITS (*this)::destroy(OUTERMOST (*this), p). scoped_allocator_adaptor select_on_container_copy_construction() const;
17
Returns: A new scoped_allocator_adaptor object where each allocator A in the adaptor is initialized from the result of calling allocator_traits::select_on_container_copy_construction() on the corresponding allocator in *this.
20.12.5
Scoped allocator operators
[scoped.adaptor.operators]
template bool operator==(const scoped_allocator_adaptor& a, const scoped_allocator_adaptor& b) noexcept; 1
Returns: a.outer_allocator() == b.outer_allocator() if sizeof...(InnerAllocs) is zero; otherwise, a.outer_allocator() == b.outer_allocator() && a.inner_allocator() == b.inner_allocator(). template bool operator!=(const scoped_allocator_adaptor& a, const scoped_allocator_adaptor& b) noexcept;
2
Returns: !(a == b). § 20.12.5
598
c ISO/IEC
20.13 20.13.1
N3376
Class type_index
[type.index]
Header synopsis
[type.index.synopsis]
namespace std { class type_index; template struct hash; template struct hash; }
20.13.2
type_index overview
[type.index.overview]
namespace std { class type_index { public: type_index(const type_info& rhs) noexcept; bool operator==(const type_index& rhs) const noexcept; bool operator!=(const type_index& rhs) const noexcept; bool operator< (const type_index& rhs) const noexcept; bool operator (const type_index& rhs) const noexcept; bool operator>= (const type_index& rhs) const noexcept; size_t hash_code() const; const char* name() const; private: const type_info* target; // exposition only // Note that the use of a pointer here, rather than a reference, // means that the default copy/move constructor and assignment // operators will be provided and work as expected. }; } 1
The class type_index provides a simple wrapper for type_info which can be used as an index type in associative containers (23.4) and in unordered associative containers (23.5).
20.13.3
type_index members
[type.index.members]
type_index(const type_info& rhs) noexcept; 1
Effects: constructs a type_index object, the equivalent of target = &rhs. bool operator==(const type_index& rhs) const noexcept;
2
Returns: *target == *rhs.target bool operator!=(const type_index& rhs) const noexcept;
3
Returns: *target != *rhs.target bool operatorbefore(*rhs.target) bool operatorbefore(*target) § 20.13.3
599
c ISO/IEC
N3376
bool operator>(const type_index& rhs) const noexcept; 6
Returns: rhs.target->before(*target) bool operator>=(const type_index& rhs) const noexcept;
7
Returns: !target->before(*rhs.target) size_t hash_code() const;
8
Returns: target->hash_code() const char* name() const;
9
Returns: target->name()
20.13.4
Hash support
[type.index.hash]
template struct hash; 1
Requires: the template specialization shall meet the requirements of class template hash (20.8.12). For an object index of type type_index, hash()(index) shall evaluate to the same result as index.hash_code().
§ 20.13.4
600
c ISO/IEC
21 21.1 1
2
N3376
Strings library
[strings]
General
[strings.general]
This Clause describes components for manipulating sequences of any non-array POD (3.9) type. In this Clause such types are called char-like types , and objects of char-like types are called char-like objects or simply characters. The following subclauses describe a character traits class, a string class, and null-terminated sequence utilities, as summarized in Table 61. Table 61 — Strings library summary
21.2 1
2
3
4
21.7
Null-terminated sequence utilities
Character traits
Header(s) <string> <string> <cuchar>
[char.traits]
This subclause defines requirements on classes representing character traits, and defines a class template char_traits, along with four specializations, char_traits, char_traits, char_traits, and char_traits<wchar_t>, that satisfy those requirements. Most classes specified in Clauses 21.3 and 27 need a set of related types and functions to complete the definition of their semantics. These types and functions are provided as a set of member typedefs and functions in the template parameter ‘traits’ used by each such template. This subclause defines the semantics guaranteed by these members. To specialize those templates to generate a string or iostream class to handle a particular character container type CharT, that and its related character traits class Traits are passed as a pair of parameters to the string or iostream template as formal parameters charT and traits. Traits::char_type shall be the same as CharT. This subclause specifies a struct template, char_traits, and four explicit specializations of it, char_traits, char_traits, char_traits, and char_traits<wchar_t>, all of which appear in the header <string> and satisfy the requirements below.
21.2.1 1
21.2 21.3
Subclause Character traits String classes
Character traits requirements
[char.traits.require]
In Table 62, X denotes a Traits class defining types and functions for the character container type CharT; c and d denote values of type CharT; p and q denote values of type const CharT*; s denotes a value of type CharT*; n, i and j denote values of type std::size_t; e and f denote values of type X::int_type; pos denotes a value of type X::pos_type; state denotes a value of type X::state_type; and r denotes an lvalue of type CharT. Operations on Traits shall not throw exceptions.
§ 21.2.1
601
c ISO/IEC
N3376
Table 62 — Character traits requirements Expression
Return type
X::char_type X::int_type X::off_type X::pos_type X::state_type X::eq(c,d)
bool
X::lt(c,d)
bool
X::compare(p,q,n)
int
X::length(p)
std::size_t
X::find(p,n,c)
const X::char_type*
X::move(s,p,n)
X::char_type*
X::copy(s,p,n)
X::char_type*
X::assign(r,d) X::assign(s,n,c)
(not used) X::char_type*
X::not_eof(e)
int_type
X::to_char_type(e)
X::char_type
§ 21.2.1
charT
Assertion/note pre-/post-condition (described in 21.2.2) (described in 21.2.2) (described in 21.2.2) (described in 21.2.2) (described in 21.2.2) yields: whether c is to be treated as equal to d. yields: whether c is to be treated as less than d. yields: 0 if for each i in [0,n), X::eq(p[i],q[i]) is true; else, a negative value if, for some j in [0,n), X::lt(p[j],q[j]) is true and for each i in [0,j) X::eq(p[i],q[i]) is true; else a positive value. yields: the smallest i such that X::eq(p[i],charT()) is true. yields: the smallest q in [p,p+n) such that X::eq(*q,c) is true, zero otherwise. for each i in [0,n), performs X::assign(s[i],p[i]). Copies correctly even where the ranges [p,p+n) and [s,s+n) overlap. yields: s. pre: p not in [s,s+n). yields: s. for each i in [0,n), performs X::assign(s[i],p[i]). assigns r=d. for each i in [0,n), performs X::assign(s[i],c). yields: s. yields: e if X::eq_int_type(e,X::eof()) is false, otherwise a value f such that X::eq_int_type(f,X::eof()) is false. yields: if for some c, X::eq_int_type(e,X::to_int_type(c)) is true, c; else some unspecified value.
Complexity compile-time compile-time compile-time compile-time compile-time constant constant linear
linear linear
linear
linear
constant linear constant
constant
602
c ISO/IEC
N3376
Table 62 — Character traits requirements (continued) Expression
2
Return type
X::to_int_type(c)
X::int_type
X::eq_int_type(e,f)
bool
X::eof()
X::int_type
Assertion/note pre-/post-condition yields: some value e, constrained by the definitions of to_char_type and eq_int_type. yields: for all c and d, X::eq(c,d) is equal to X::eq_int_type(X::to_int_type(c), X::to_int_type(d)); otherwise, yields true if e and f are both copies of X::eof(); otherwise, yields false if one of e and f is a copy of X::eof() and the other is not; otherwise the value is unspecified. yields: a value e such that X::eq_int_type(e,X::to_int_type(c)) is false for all values c.
Complexity constant
constant
constant
The struct template template struct char_traits;
shall be provided in the header <string> as a basis for explicit specializations.
21.2.2
traits typedefs
[char.traits.typedefs]
typedef CHAR_T char_type; 1
The type char_type is used to refer to the character container type in the implementation of the library classes defined in 21.3 and Clause 27. typedef INT_T int_type;
2
Requires: For a certain character container type char_type, a related container type INT_T shall be a type or class which can represent all of the valid characters converted from the corresponding char_type values, as well as an end-of-file value, eof(). The type int_type represents a character container type which can hold end-of-file to be used as a return type of the iostream class member functions.231 typedef implementation-defined off_type; typedef implementation-defined pos_type;
3
Requires: Requirements for off_type and pos_type are described in 27.2.2 and 27.3. typedef STATE_T state_type;
4
Requires: state_type shall meet the requirements of CopyAssignable (Table 23), CopyConstructible (Table 21), and DefaultConstructible (Table 19) types. 231) If eof() can be held in char_type then some iostreams operations may give surprising results.
§ 21.2.2
603
c ISO/IEC
21.2.3
N3376
char_traits specializations
namespace std { template struct template struct template struct template struct } 1
2
[char.traits.specializations]
char_traits; char_traits; char_traits; char_traits<wchar_t>;
The header <string> shall define four specializations of the template struct char_traits: char_traits< char>, char_traits, char_traits, and char_traits<wchar_t>. The requirements for the members of these specializations are given in Clause 21.2.1. 21.2.3.1 struct char_traits [char.traits.specializations.char] namespace std { template struct char_traits { typedef char char_type; typedef int int_type; typedef streamoff off_type; typedef streampos pos_type; typedef mbstate_t state_type; static void assign(char_type& c1, const char_type& c2) noexcept; static constexpr bool eq(char_type c1, char_type c2) noexcept; static constexpr bool lt(char_type c1, char_type c2) noexcept; static int compare(const char_type* s1, const char_type* s2, size_t n); static size_t length(const char_type* s); static const char_type* find(const char_type* s, size_t n, const char_type& a); static char_type* move(char_type* s1, const char_type* s2, size_t n); static char_type* copy(char_type* s1, const char_type* s2, size_t n); static char_type* assign(char_type* s, size_t n, char_type a); static static static static static
constexpr constexpr constexpr constexpr constexpr
int_type not_eof(int_type c) noexcept; char_type to_char_type(int_type c) noexcept; int_type to_int_type(char_type c) noexcept; bool eq_int_type(int_type c1, int_type c2) noexcept; int_type eof() noexcept;
}; } 1
2
3
4
5
6
The defined types for int_type, pos_type, off_type, and state_type shall be int, streampos, streamoff, and mbstate_t respectively. The type streampos shall be an implementation-defined type that satisfies the requirements for pos_type in 27.2.2 and 27.3. The type streamoff shall be an implementation-defined type that satisfies the requirements for off_type in 27.2.2 and 27.3. The type mbstate_t is defined in and can represent any of the conversion states that can occur in an implementation-defined set of supported multibyte character encoding rules. The two-argument member assign shall be defined identically to the built-in operator =. The two-argument members eq and lt shall be defined identically to the built-in operators == and < for type unsigned char. The member eof() shall return EOF. 21.2.3.2 struct char_traits [char.traits.specializations.char16_t]
§ 21.2.3.2
604
c ISO/IEC
N3376
namespace std { template struct char_traits { typedef char16_t char_type; typedef uint_least16_t int_type; typedef streamoff off_type; typedef u16streampos pos_type; typedef mbstate_t state_type; static void assign(char_type& c1, const char_type& c2) noexcept; static constexpr bool eq(char_type c1, char_type c2) noexcept; static constexpr bool lt(char_type c1, char_type c2) noexcept; static int compare(const char_type* s1, const char_type* s2, size_t n); static size_t length(const char_type* s); static const char_type* find(const char_type* s, size_t n, const char_type& a); static char_type* move(char_type* s1, const char_type* s2, size_t n); static char_type* copy(char_type* s1, const char_type* s2, size_t n); static char_type* assign(char_type* s, size_t n, char_type a); static static static static static
constexpr constexpr constexpr constexpr constexpr
int_type not_eof(int_type c) noexcept; char_type to_char_type(int_type c) noexcept; int_type to_int_type(char_type c) noexcept; bool eq_int_type(int_type c1, int_type c2) noexcept; int_type eof() noexcept;
}; } 1
2
3
The type u16streampos shall be an implementation-defined type that satisfies the requirements for pos_type in 27.2.2 and 27.3. The two-argument members assign, eq, and lt shall be defined identically to the built-in operators =, ==, and < respectively. The member eof() shall return an implementation-defined constant that cannot appear as a valid UTF-16 code unit. 21.2.3.3 struct char_traits [char.traits.specializations.char32_t] namespace std { template struct char_traits { typedef char32_t char_type; typedef uint_least32_t int_type; typedef streamoff off_type; typedef u32streampos pos_type; typedef mbstate_t state_type; static void assign(char_type& c1, const char_type& c2) noexcept; static constexpr bool eq(char_type c1, char_type c2) noexcept; static constexpr bool lt(char_type c1, char_type c2) noexcept; static int compare(const char_type* s1, const char_type* s2, size_t n); static size_t length(const char_type* s); static const char_type* find(const char_type* s, size_t n, const char_type& a); static char_type* move(char_type* s1, const char_type* s2, size_t n); static char_type* copy(char_type* s1, const char_type* s2, size_t n); static char_type* assign(char_type* s, size_t n, char_type a);
§ 21.2.3.3
605
c ISO/IEC
static static static static static
N3376
constexpr constexpr constexpr constexpr constexpr
int_type not_eof(int_type c) noexcept; char_type to_char_type(int_type c) noexcept; int_type to_int_type(char_type c) noexcept; bool eq_int_type(int_type c1, int_type c2) noexcept; int_type eof() noexcept;
}; } 1
2
3
The type u32streampos shall be an implementation-defined type that satisfies the requirements for pos_type in 27.2.2 and 27.3. The two-argument members assign, eq, and lt shall be defined identically to the built-in operators =, ==, and < respectively. The member eof() shall return an implementation-defined constant that cannot appear as a Unicode code point. 21.2.3.4 struct char_traits<wchar_t> [char.traits.specializations.wchar.t] namespace std { template struct char_traits<wchar_t> { typedef wchar_t char_type; typedef wint_t int_type; typedef streamoff off_type; typedef wstreampos pos_type; typedef mbstate_t state_type; static void assign(char_type& c1, const char_type& c2) noexcept; static constexpr bool eq(char_type c1, char_type c2) noexcept; static constexpr bool lt(char_type c1, char_type c2) noexcept; static int compare(const char_type* s1, const char_type* s2, size_t n); static size_t length(const char_type* s); static const char_type* find(const char_type* s, size_t n, const char_type& a); static char_type* move(char_type* s1, const char_type* s2, size_t n); static char_type* copy(char_type* s1, const char_type* s2, size_t n); static char_type* assign(char_type* s, size_t n, char_type a); static static static static static
constexpr constexpr constexpr constexpr constexpr
int_type not_eof(int_type c) noexcept; char_type to_char_type(int_type c) noexcept; int_type to_int_type(char_type c) noexcept; bool eq_int_type(int_type c1, int_type c2) noexcept; int_type eof() noexcept;
}; } 1
2
3
4
The defined types for int_type, pos_type, and state_type shall be wint_t, wstreampos, and mbstate_t respectively. The type wstreampos shall be an implementation-defined type that satisfies the requirements for pos_type in 27.2.2 and 27.3. The type mbstate_t is defined in and can represent any of the conversion states that can occur in an implementation-defined set of supported multibyte character encoding rules. The two-argument members assign, eq, and lt shall be defined identically to the built-in operators =, ==, and < respectively.
§ 21.2.3.4
606
c ISO/IEC
5
The member eof() shall return WEOF.
21.3 1
N3376
String classes
[string.classes]
The header <string> defines the basic_string class template for manipulating varying-length sequences of char-like objects and four typedefs, string, u16string, u32string, and wstring, that name the specializations basic_string, basic_string, basic_string, and basic_string< wchar_t>, respectively. Header <string> synopsis #include namespace std { // 21.2, character traits: template struct char_traits; template struct char_traits; template struct char_traits; template struct char_traits; template struct char_traits<wchar_t>; // 21.4, basic_string: template class basic_string; template basic_string operator+(const basic_string& lhs, const basic_string& rhs); template basic_string operator+(basic_string&& lhs, const basic_string& rhs); template basic_string operator+(const basic_string& lhs, basic_string&& rhs); template basic_string operator+(basic_string&& lhs, basic_string&& rhs); template basic_string operator+(const charT* lhs, const basic_string& rhs); template basic_string operator+(const charT* lhs, basic_string&& rhs); template basic_string operator+(charT lhs, const basic_string& rhs); template basic_string operator+(charT lhs, basic_string&& rhs); template
§ 21.3
607
c ISO/IEC
N3376
basic_string operator+(const basic_string& lhs, const charT* rhs); template basic_string operator+(basic_string&& lhs, const charT* rhs); template basic_string operator+(const basic_string& lhs, charT rhs); template basic_string operator+(basic_string&& lhs, charT rhs); template bool operator==(const basic_string& const basic_string& template bool operator==(const charT* lhs, const basic_string& template bool operator==(const basic_string& const charT* rhs); template bool operator!=(const basic_string& const basic_string& template bool operator!=(const charT* lhs, const basic_string& template bool operator!=(const basic_string& const charT* rhs); template bool operator< (const basic_string& const basic_string& template bool operator< (const basic_string& const charT* rhs); template bool operator< (const charT* lhs, const basic_string& template bool operator> (const basic_string& const basic_string& template bool operator> (const basic_string& const charT* rhs); template bool operator> (const charT* lhs, const basic_string&
lhs, rhs) noexcept;
rhs); lhs,
lhs, rhs) noexcept;
rhs); lhs,
lhs, rhs) noexcept; lhs,
rhs); lhs, rhs) noexcept; lhs,
rhs);
template bool operator=(const charT* lhs, const basic_string&
N3376
lhs,
rhs); lhs, rhs) noexcept; lhs,
rhs);
// 21.4.8.8, swap: template void swap(basic_string& lhs, basic_string& rhs); // 21.4.8.9, inserters and extractors: template basic_istream& operator>>(basic_istream& is, basic_string& str); template basic_ostream& operator; template struct hash; template struct hash; template struct hash<wstring>; }
21.4 1
2
3
Class template basic_string
[basic.string]
The class template basic_string describes objects that can store a sequence consisting of a varying number of arbitrary char-like objects with the first element of the sequence at position zero. Such a sequence is also called a “string” if the type of the char-like objects that it holds is clear from context. In the rest of this Clause, the type of the char-like objects held in a basic_string object is designated by charT. The member functions of basic_string use an object of the Allocator class passed as a template parameter to allocate and free storage for the contained char-like objects.232 The iterators supported by basic_string are random access iterators (24.2.7). 232) Allocator::value_type must name the same type as charT (21.4.1).
§ 21.4
610
c ISO/IEC
4 5
N3376
In all cases, size() ()
(21.4.8.9),
and
615
c ISO/IEC
N3376
Table 64 — basic_string(const basic_string&) effects Element data()
size() capacity()
Value points at the first element of an allocated copy of the array whose first element is pointed at by str.data() str.size() a value at least as large as size()
3
Requires: pos str.size().
5
Effects: Constructs an object of class basic_string and determines the effective length rlen of the initial string value as the smaller of n and str.size() - pos, as indicated in Table 65. Table 65 — basic_string(const basic_string&, size_type, size_type, const Allocator&) effects Element data()
size() capacity()
Value points at the first element of an allocated copy of rlen consecutive elements of the string controlled by str beginning at position pos rlen a value at least as large as size()
basic_string(const charT* s, size_type n, const Allocator& a = Allocator()); 6
Requires: s shall not be a null pointer and n < npos.
7
Effects: Constructs an object of class basic_string and determines its initial string value from the array of charT of length n whose first element is designated by s, as indicated in Table 66. Table 66 — basic_string(const charT*, size_type, const Allocator&) effects Element data() size() capacity()
Value points at the first element of an allocated copy of the array whose first element is pointed at by s n a value at least as large as size()
basic_string(const charT* s, const Allocator& a = Allocator()); 8
Requires: s shall not be a null pointer.
9
Effects: Constructs an object of class basic_string and determines its initial string value from the array of charT of length traits::length(s) whose first element is designated by s, as indicated in Table 67. § 21.4.2
616
c ISO/IEC
N3376
Table 67 — basic_string(const charT*, const Allocator&) effects Element data() size() capacity()
10
Value points at the first element of an allocated copy of the array whose first element is pointed at by s traits::length(s) a value at least as large as size()
Remarks: Uses traits::length(). basic_string(size_type n, charT c, const Allocator& a = Allocator());
11
Requires: n < npos
12
Effects: Constructs an object of class basic_string and determines its initial string value by repeating the char-like object c for all n elements, as indicated in Table 68. Table 68 — basic_string(size_t, charT, const Allocator&) effects Element data() size() capacity()
Value points at the first element of an allocated array of n elements, each storing the initial value c n a value at least as large as size()
template basic_string(InputIterator begin, InputIterator end, const Allocator& a = Allocator()); 13
Effects: If InputIterator is an integral type, equivalent to basic_string(static_cast<size_type>(begin), static_cast(end), a)
14
Otherwise constructs a string from the values in the range [begin, end), as indicated in the Sequence Requirements table (see 23.2.3). basic_string(initializer_list il, const Allocator& a = Allocator());
15
Effects: Same as basic_string(il.begin(), il.end(), a). basic_string(const basic_string& str, const Allocator& alloc); basic_string(basic_string&& str, const Allocator& alloc);
16
Effects: Constructs an object of class basic_string as indicated in Table 69. The stored allocator is constructed from alloc. In the second form, str is left in a valid state with an unspecified value.
17
Throws: The second form throws nothing if alloc == str.get_allocator().
§ 21.4.2
617
c ISO/IEC
N3376
Table 69 — basic_string(const basic_string&, const Allocator&) and basic_string(basic_string&&, const Allocator&) effects Element data()
size() capacity() get_allocator()
Value points at the first element of an allocated copy of the array whose first element is pointed at by the original value of str.data(). the original value of str.size() a value at least as large as size() alloc
basic_string& operator=(const basic_string& str); 18
Effects: If *this and str are not the same object, modifies *this as shown in Table 70.
19
If *this and str are the same object, the member has no effect.
20
Returns: *this Table 70 — operator=(const basic_string&) effects Element data()
size() capacity()
Value points at the first element of an allocated copy of the array whose first element is pointed at by str.data() str.size() a value at least as large as size()
basic_string& operator=(basic_string&& str) noexcept; 21
Effects: If *this and str are not the same object, modifies *this as shown in Table 71. [ Note: A valid implementation is swap(str). — end note ]
22
If *this and str are the same object, the member has no effect.
23
Returns: *this Table 71 — operator=(const basic_string&&) effects Element data() size() capacity()
§ 21.4.2
Value points at the array whose first element was pointed at by str.data() previous value of str.size() a value at least as large as size()
618
c ISO/IEC
N3376
basic_string& operator=(const charT* s); 24
Returns: *this = basic_string(s).
25
Remarks: Uses traits::length(). basic_string& operator=(charT c);
26
Returns: *this = basic_string(1,c). basic_string& operator=(initializer_list il);
27
Effects: *this = basic_string(il).
28
Returns: *this.
21.4.3
basic_string iterator support
[string.iterators]
iterator begin() noexcept; const_iterator begin() const noexcept; const_iterator cbegin() const noexcept; 1
Returns: An iterator referring to the first character in the string. iterator end() noexcept; const_iterator end() const noexcept; const_iterator cend() const noexcept;
2
Returns: An iterator which is the past-the-end value. reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; const_reverse_iterator crbegin() const noexcept;
3
Returns: An iterator which is semantically equivalent to reverse_iterator(end()). reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; const_reverse_iterator crend() const noexcept;
4
Returns: An iterator which is semantically equivalent to reverse_iterator(begin()).
21.4.4
basic_string capacity
[string.capacity]
size_type size() const noexcept; 1
Returns: A count of the number of char-like objects currently in the string.
2
Complexity: constant time. size_type length() const noexcept;
3
Returns: size(). § 21.4.4
619
c ISO/IEC
N3376
size_type max_size() const noexcept; 4
Returns: The size of the largest possible string.
5
Complexity: constant time. void resize(size_type n, charT c);
6
Requires: n max_size().
8
Effects: Alters the length of the string designated by *this as follows: — If n size(), the function replaces the string designated by *this with a string of length n whose first size() elements are a copy of the original string designated by *this, and whose remaining elements are all initialized to c. void resize(size_type n);
9
Effects: resize(n,charT()). size_type capacity() const noexcept;
10
Returns: The size of the allocated storage in the string. void reserve(size_type res_arg=0);
11
The member function reserve() is a directive that informs a basic_string object of a planned change in size, so that it can manage the storage allocation accordingly.
12
Effects: After reserve(), capacity() is greater or equal to the argument of reserve. [ Note: Calling reserve() with a res_arg argument less than capacity() is in effect a non-binding shrink request. A call with res_arg max_size().234 void shrink_to_fit();
14
Remarks: shrink_to_fit is a non-binding request to reduce capacity() to size(). [ Note: The request is non-binding to allow latitude for implementation-specific optimizations. — end note ] void clear() noexcept;
15
Effects: Behaves as if the function calls: erase(begin(), end());
bool empty() const noexcept; 16
Returns: size() == 0. 234) reserve() uses allocator_traits::allocate() which may throw an appropriate exception.
§ 21.4.4
620
c ISO/IEC
21.4.5
basic_string element access
N3376
[string.access]
const_reference operator[](size_type pos) const; reference operator[](size_type pos); 1
Requires: pos = size().
7
Returns: operator[](pos). const charT& front() const; charT& front();
8
Requires: !empty()
9
Effects: Equivalent to operator[](0). const charT& back() const; charT& back();
10
Requires: !empty()
11
Effects: Equivalent to operator[](size() - 1).
21.4.6 21.4.6.1
basic_string modifiers basic_string::operator+=
[string.modifiers] [string::op+=]
basic_string& operator+=(const basic_string& str); 1
Effects: Calls append(str).
2
Returns: *this. basic_string& operator+=(const charT* s);
3
Effects: Calls append(s).
4
Returns: *this. basic_string& operator+=(charT c);
5
Effects: Calls push_back(c);
6
Returns: *this. § 21.4.6.1
621
c ISO/IEC
N3376
basic_string& operator+=(initializer_list il); 7
Effects: Calls append(il).
8
Returns: *this. 21.4.6.2
basic_string::append
[string::append]
basic_string& append(const basic_string& str); 1
Effects: Calls append(str.data(), str.size()).
2
Returns: *this. basic_string& append(const basic_string& str, size_type pos, size_type n);
3
Requires: pos str.size().
5
Effects: Determines the effective length rlen of the string to append as the smaller of n and str.size() - pos and calls append(str.data() + pos, rlen).
6
Returns: *this. basic_string& append(const charT* s, size_type n);
7
Requires: s points to an array of at least n elements of charT.
8
Throws: length_error if size() + n > max_size().
9
Effects: The function replaces the string controlled by *this with a string of length size() + n whose first size() elements are a copy of the original string controlled by *this and whose remaining elements are a copy of the initial n elements of s.
10
Returns: *this. basic_string& append(const charT* s);
11
Requires: s points to an array of at least traits::length(s) + 1 elements of charT.
12
Effects: Calls append(s, traits::length(s)).
13
Returns: *this. basic_string& append(size_type n, charT c);
14
Effects: Equivalent to append(basic_string(n, c)).
15
Returns: *this. template basic_string& append(InputIterator first, InputIterator last);
§ 21.4.6.2
622
c ISO/IEC
16
Requires: [first,last) is a valid range.
17
Effects: Equivalent to append(basic_string(first, last)).
18
Returns: *this.
N3376
basic_string& append(initializer_list il); 19
Effects: Calls append(il.begin(), il.size()).
20
Returns: *this. void push_back(charT c)
21
Effects: Equivalent to append(static_cast<size_type>(1), c). 21.4.6.3
basic_string::assign
[string::assign]
basic_string& assign(const basic_string& str); 1
Effects: Equivalent to assign(str, 0, npos).
2
Returns: *this. basic_string& assign(basic_string&& str) noexcept;
Effects: The function replaces the string controlled by *this with a string of length str.size() whose elements are a copy of the string controlled by str. [ Note: A valid implementation is swap(str). — end note ] 3
Returns: *this. basic_string& assign(const basic_string& str, size_type pos, size_type n);
4
Requires: pos str.size().
6
Effects: Determines the effective length rlen of the string to assign as the smaller of n and str.size() - pos and calls assign(str.data() + pos rlen).
7
Returns: *this. basic_string& assign(const charT* s, size_type n);
8
Requires: s points to an array of at least n elements of charT.
9
Throws: length_error if n > max_size().
10
Effects: Replaces the string controlled by *this with a string of length n whose elements are a copy of those pointed to by s.
11
Returns: *this. basic_string& assign(const charT* s);
§ 21.4.6.3
623
c ISO/IEC
N3376
12
Requires: s points to an array of at least traits::length(s) + 1 elements of charT.
13
Effects: Calls assign(s, traits::length(s)).
14
Returns: *this. basic_string& assign(initializer_list il);
15
Effects: Calls assign(il.begin(), il.size()).
16
*this. basic_string& assign(size_type n, charT c);
18 17
Effects: Equivalent to assign(basic_string(n, c)).
19
Returns: *this. template basic_string& assign(InputIterator first, InputIterator last);
20
Effects: Equivalent to assign(basic_string(first, last)).
21
Returns: *this. 21.4.6.4
basic_string::insert
[string::insert]
basic_string& insert(size_type pos1, const basic_string& str); 1
Requires: pos size().
3
Effects: Calls insert(pos, str.data(), str.size()).
4
Returns: *this. basic_string& insert(size_type pos1, const basic_string& str, size_type pos2, size_type n);
5
Requires: pos1 str.size().
7
Effects: Determines the effective length rlen of the string to insert as the smaller of n and str.size() - pos2 and calls insert(pos1, str.data() + pos2, rlen).
8
Returns: *this. basic_string& insert(size_type pos, const charT* s, size_type n);
§ 21.4.6.4
624
c ISO/IEC
9
N3376
Requires: s points to an array of at least n elements of charT and pos size() or length_error if size() + n > max_size().
11
Effects: Replaces the string controlled by *this with a string of length size() + n whose first pos elements are a copy of the initial elements of the original string controlled by *this and whose next n elements are a copy of the elements in s and whose remaining elements are a copy of the remaining elements of the original string controlled by *this.
12
Returns: *this. basic_string& insert(size_type pos, const charT* s);
13
Requires: pos = max_size() - n2 throws length_error. Otherwise, the function replaces the string controlled by *this with a string of length size() - xlen + n2 whose first pos1 elements are a copy of the initial elements of the original string controlled by *this, whose next n2 elements are a copy of the initial n2 elements of s, and whose remaining elements are a copy of the elements of the original string controlled by *this beginning at position pos + xlen.
12
Returns: *this. basic_string& replace(size_type pos, size_type n, const charT* s);
13
Requires: pos >(basic_istream& is, basic_string& str); 1
Effects: Behaves as a formatted input function (27.7.2.2.1). After constructing a sentry object, if the sentry converts to true, calls str.erase() and then extracts characters from is and appends them to str as if by calling str.append(1,c). If is.width() is greater than zero, the maximum number n of characters appended is is.width(); otherwise n is str.max_size(). Characters are extracted and appended until any of the following occurs: — n characters are stored; — end-of-file occurs on the input sequence; — isspace(c,is.getloc()) is true for the next available input character c.
2
After the last character (if any) is extracted, is.width(0) is called and the sentry object k is destroyed.
3
If the function extracts no characters, it calls is.setstate(ios::failbit), which may throw ios_base::failure (27.5.5.4).
4
Returns: is template basic_ostream& operator; hash; hash; hash<wstring>;
Requires: the template specializations shall meet the requirements of class template hash (20.8.12).
21.7 1
N3376
Null-terminated sequence utilities
[c.strings]
Tables 74, 75, 76, 77, 78, and 79 describe headers , , , , (character conversions), and <cuchar>, respectively. The contents of these headers shall be the same as the Standard C Library headers , <wctype.h>, <string.h>, <wchar.h>, and <stdlib.h> and the C Unicode TR header , respectively, with the following modifications: The headers shall not define the types char16_t, char32_t, and wchar_t (2.12). The function signature strchr(const char*, int) shall be replaced by the two declarations: const char* strchr(const char* s, int c); char* strchr( char* s, int c);
5
both of which shall have the same behavior as the original declaration. The function signature strpbrk(const char*, const char*) shall be replaced by the two declarations: const char* strpbrk(const char* s1, const char* s2); char* strpbrk( char* s1, const char* s2);
6
both of which shall have the same behavior as the original declaration. The function signature strrchr(const char*, int) shall be replaced by the two declarations: const char* strrchr(const char* s, int c); char* strrchr( char* s, int c);
7
both of which shall have the same behavior as the original declaration. The function signature strstr(const char*, const char*) shall be replaced by the two declarations: const char* strstr(const char* s1, const char* s2); char* strstr( char* s1, const char* s2);
8
both of which shall have the same behavior as the original declaration. The function signature memchr(const void*, int, size_t) shall be replaced by the two declarations: const void* memchr(const void* s, int c, size_t n); void* memchr( void* s, int c, size_t n);
§ 21.7
641
c ISO/IEC
9
N3376
both of which shall have the same behavior as the original declaration. The function signature wcschr(const wchar_t*, wchar_t) shall be replaced by the two declarations: const wchar_t* wcschr(const wchar_t* s, wchar_t c); wchar_t* wcschr( wchar_t* s, wchar_t c);
10
both of which shall have the same behavior as the original declaration. The function signature wcspbrk(const wchar_t*, const wchar_t*) shall be replaced by the two declarations: const wchar_t* wcspbrk(const wchar_t* s1, const wchar_t* s2); wchar_t* wcspbrk( wchar_t* s1, const wchar_t* s2);
11
both of which shall have the same behavior as the original declaration. The function signature wcsrchr(const wchar_t*, wchar_t) shall be replaced by the two declarations: const wchar_t* wcsrchr(const wchar_t* s, wchar_t c); wchar_t* wcsrchr( wchar_t* s, wchar_t c);
12
both of which shall have the same behavior as the original declaration. The function signature wcsstr(const wchar_t*, const wchar_t*) shall be replaced by the two declarations: const wchar_t* wcsstr(const wchar_t* s1, const wchar_t* s2); wchar_t* wcsstr( wchar_t* s1, const wchar_t* s2);
13
both of which shall have the same behavior as the original declaration. The function signature wmemchr(const wwchar_t*, int, size_t) shall be replaced by the two declarations: const wchar_t* wmemchr(const wchar_t* s, wchar_t c, size_t n); wchar_t* wmemchr( wchar_t* s, wchar_t c, size_t n);
14 15
both of which shall have the same behavior as the original declaration. The functions strerror and strtok are not required to avoid data races (17.6.5.9). Calling the functions listed in Table 73 with an mbstate_t* argument of NULL may introduce a data race (17.6.5.9) with other calls to these functions with an mbstate_t* argument of NULL. Table 73 — Potential mbstate_t data races mbrlen wcsrtomb
mbrtowc wctomb
mbsrtowc
mbtowc
wcrtomb
See also: ISO C 7.3, 7.10.7, 7.10.8, and 7.11. Amendment 1 4.4, 4.5, and 4.6. Table 74 — Header synopsis Type Functions: isalnum tolower toupper
§ 21.7
Name(s) isblank isalpha iscntrl
isdigit isgraph islower
isprint ispunct isspace
isupper isxdigit
642
c ISO/IEC
N3376
Table 75 — Header synopsis Type Macro: Types: Functions: iswalnum iswalpha iswblank iswcntrl
Name(s) WEOF wctrans_t
wctype_t
wint_t
iswctype iswdigit iswgraph iswlower
iswprint iswpunct iswspace iswupper
iswxdigit towctrans towlower towupper
wctrans wctype
Table 76 — Header synopsis Type Macro: Type: Functions: memchr memcmp memcpy memmove memset
Name(s) NULL size_t strcat strchr strcmp strcoll strcpy
strcspn strerror strlen strncat strncmp
strncpy strpbrk strrchr strspn strstr
strtok strxfrm
Table 77 — Header synopsis Type Macros: Types: Functions: btowc fgetwc fgetws fputwc fputws fwide fwprintf fwscanf getwchar getwc mbrlen mbrtowc
§ 21.7
NULL mbstate_t
WCHAR_MAX wint_t
mbsinit mbsrtowcs putwchar putwc swprintf swscanf ungetwc vfwprintf vfwscanf vswprintf vswscanf vwprintf
vwscanf wcrtomb wcscat wcschr wcscmp wcscoll wcscpy wcscspn wcsftime wcslen wcsncat wcsncmp
Name(s) WCHAR_MIN size_t wcsncpy wcspbrk wcsrchr wcsrtombs wcsspn wcsstr wcstod wcstof wcstok wcstold wcstoll wcstol
WEOF tm wcstoull wcstoul wcsxfrm wctob wmemchr wmemcmp wmemcpy wmemmove wmemset wprintf wscanf
643
c ISO/IEC
N3376
Table 78 — Header synopsis Type Macros: Functions: atof atoi atol atoll
Name(s) MB_CUR_MAX mblen mbtowc mbstowcs strtod
strtof strtol strtold strtoll
strtoul strtoull wctomb wcstombs
Table 79 — Header <cuchar> synopsis Type Macros: Functions:
§ 21.7
Name(s) __STDC_UTF_16__ __STDC_UTF_32__ mbrtoc16 c16rtomb mbrtoc32 c32rtomb
644
c ISO/IEC
22 22.1 1
2
N3376
Localization library
[localization]
General
[localization.general]
This Clause describes components that C++ programs may use to encapsulate (and therefore be more portable when confronting) cultural differences. The locale facility includes internationalization support for character classification and string collation, numeric, monetary, and date/time formatting and parsing, and message retrieval. The following subclauses describe components for locales themselves, the standard facets, and facilities from the ISO C library, as summarized in Table 80. Table 80 — Localization library summary
22.3 22.4 22.5 22.6
22.2
Subclause Locales Standard locale Categories Standard code conversion facets C library locales
Header(s)
Header synopsis
[locale.syn]
namespace std { // 22.3.1, locale: class locale; template const Facet& use_facet(const locale&); template bool has_facet(const locale&) noexcept; // 22.3.3, convenience interfaces: template bool isspace (charT c, const locale& loc); template bool isprint (charT c, const locale& loc); template bool iscntrl (charT c, const locale& loc); template bool isupper (charT c, const locale& loc); template bool islower (charT c, const locale& loc); template bool isalpha (charT c, const locale& loc); template bool isdigit (charT c, const locale& loc); template bool ispunct (charT c, const locale& loc); template bool isxdigit(charT c, const locale& loc); template bool isalnum (charT c, const locale& loc); template bool isgraph (charT c, const locale& loc); template charT toupper(charT c, const locale& loc); template charT tolower(charT c, const locale& loc); template , class Byte_alloc = std::allocator > class wstring_convert; template > class wbuffer_convert; // 22.4.1, ctype: class ctype_base;
§ 22.2
645
c ISO/IEC
N3376
template class ctype; template class ctype; // specialization template class ctype_byname; class codecvt_base; template class codecvt; template class codecvt_byname; // 22.4.2, numeric: template class num_put; numpunct; numpunct_byname;
// 22.4.4, collation: template class collate; template class collate_byname; // 22.4.5, date and time: class time_base; template > class money_get; class OutputIterator = ostreambuf_iterator > > class money_put; bool Intl = false> class moneypunct; bool Intl = false> class moneypunct_byname;
// 22.4.7, message retrieval: class messages_base; template class messages; template class messages_byname; } 1
The header defines classes and declares functions that encapsulate and manipulate the information peculiar to a locale.235
22.3 22.3.1
Locales Class locale
[locales] [locale]
namespace std { class locale { public: // types: class facet; class id; typedef int category; 235) In this subclause, the type name struct tm is an incomplete type that is defined in .
§ 22.3.1
646
c ISO/IEC
N3376
static const category // values assigned here are for exposition only none = 0, collate = 0x010, ctype = 0x020, monetary = 0x040, numeric = 0x080, time = 0x100, messages = 0x200, all = collate | ctype | monetary | numeric | time | messages; // construct/copy/destroy: locale() noexcept; locale(const locale& other) noexcept; explicit locale(const char* std_name); explicit locale(const string& std_name); locale(const locale& other, const char* std_name, category); locale(const locale& other, const string& std_name, category); template locale(const locale& other, Facet* f); locale(const locale& other, const locale& one, category); ~locale(); // not virtual const locale& operator=(const locale& other) noexcept; template locale combine(const locale& other) const; // locale operations: basic_string
name() const;
bool operator==(const locale& other) const; bool operator!=(const locale& other) const; template bool operator()(const basic_string& s1, const basic_string& s2) const; // global locale objects: static locale global(const locale&); static const locale& classic(); }; } 1
2 3
Class locale implements a type-safe polymorphic set of facets, indexed by facet type. In other words, a facet has a dual role: in one sense, it’s just a class interface; at the same time, it’s an index into a locale’s set of facets. Access to the facets of a locale is via two function templates, use_facet and has_facet. [ Example: An iostream operator&) is provided so that a locale may be used as a predicate argument to the standard collections, to collate strings. — Convenient global interfaces are provided for traditional ctype functions such as isdigit() and isspace(), so that given a locale object loc a C++ program can call isspace(c,loc). (This eases upgrading existing extractors (27.7.2.2).) — end note ]
6
7
8
9
Once a facet reference is obtained from a locale object by calling use_facet, that reference remains usable, and the results from member functions of it may be cached and re-used, as long as some locale object refers to that facet. In successive calls to a locale facet member function on a facet object installed in the same locale, the returned result shall be identical. A locale constructed from a name string (such as "POSIX"), or from parts of two named locales, has a name; all others do not. Named locales may be compared for equality; an unnamed locale is equal only to (copies of) itself. For an unnamed locale, locale::name() returns the string "*". Whether there is one global locale object for the entire program or one global locale object per thread is implementation-defined. Implementations should provide one global locale object per thread. If there is a single global locale object for the entire program, implementations are not required to avoid data races on it (17.6.5.9). 22.3.1.1 22.3.1.1.1
locale types Type locale::category
[locale.types] [locale.category]
typedef int category; 1
Valid category values include the locale member bitmask elements collate, ctype, monetary, numeric, time, and messages, each of which represents a single locale category. In addition, locale member bitmask constant none is defined as zero and represents no category. And locale member bitmask constant all is defined such that the expression (collate | ctype | monetary | numeric | time | messages | all) == all
2
3
4
5
is true, and represents the union of all categories. Further, the expression (X | Y), where X and Y each represent a single category, represents the union of the two categories. locale member functions expecting a category argument require one of the category values defined above, or the union of two or more such values. Such a category value identifies a set of locale categories. Each locale category, in turn, identifies a set of locale facets, including at least those shown in Table 81. For any locale loc either constructed, or returned by locale::classic(), and any facet Facet shown in Table 81, has_facet(loc) is true. Each locale member function which takes a locale::category argument operates on the corresponding set of facets. An implementation is required to provide those specializations for facet templates identified as members of a category, and for those shown in Table 82. The provided implementation of members of facets num_get and num_put calls use_facet (l) only for facet F of types numpunct and ctype, and for locale l the value obtained by calling member getloc() on the ios_base& argument to these functions. § 22.3.1.1.1
648
c ISO/IEC
N3376
Table 81 — Locale category facets Category collate ctype
monetary
numeric
time messages
Includes facets collate, collate<wchar_t> ctype, ctype<wchar_t> codecvt codecvt codecvt codecvt<wchar_t,char,mbstate_t> moneypunct, moneypunct<wchar_t> moneypunct, moneypunct<wchar_t,true> money_get, money_get<wchar_t> money_put, money_put<wchar_t> numpunct, numpunct<wchar_t> num_get, num_get<wchar_t> num_put, num_put<wchar_t> time_get, time_get<wchar_t> time_put, time_put<wchar_t> messages, messages<wchar_t>
Table 82 — Required specializations Category collate ctype
monetary
numeric time
messages
§ 22.3.1.1.1
Includes facets collate_byname, collate_byname<wchar_t> ctype_byname, ctype_byname<wchar_t> codecvt_byname codecvt_byname codecvt_byname codecvt_byname<wchar_t,char,mbstate_t> moneypunct_byname moneypunct_byname<wchar_t,International> money_get money_put numpunct_byname, numpunct_byname<wchar_t> num_get, num_put time_get time_get_byname time_get<wchar_t,InputIterator> time_get_byname<wchar_t,InputIterator> time_put time_put_byname time_put<wchar_t,OutputIterator> time_put_byname<wchar_t,OutputIterator> messages_byname, messages_byname<wchar_t>
649
c ISO/IEC
6
N3376
In declarations of facets, a template formal parameter with name InputIterator or OutputIterator indicates the set of all possible specializations on parameters that satisfy the requirements of an Input Iterator or an Output Iterator, respectively (24.2). A template formal parameter with name C represents the set of types containing char, wchar_t, and any other implementation-defined character types that satisfy the requirements for a character on which any of the iostream components can be instantiated. A template formal parameter with name International represents the set of all possible specializations on a bool parameter. 22.3.1.1.2 Class locale::facet [locale.facet] namespace std { class locale::facet { protected: explicit facet(size_t refs = 0); virtual ~facet(); facet(const facet&) = delete; void operator=(const facet&) = delete; }; }
1
2
3
4
Template parameters in this Clause which are required to be facets are those named Facet in declarations. A program that passes a type that is not a facet, or a type that refers to a volatile-qualified facet, as an (explicit or deduced) template parameter to a locale function expecting a facet, is ill-formed. A const-qualified facet is a valid template argument to any locale function that expects a Facet template parameter. The refs argument to the constructor is used for lifetime management. — For refs == 0, the implementation performs delete static_cast(f) (where f is a pointer to the facet) when the last locale object containing the facet is destroyed; for refs == 1, the implementation never destroys the facet. Constructors of all facets defined in this Clause take such an argument and pass it along to their facet base class constructor. All one-argument constructors defined in this Clause are explicit, preventing their participation in automatic conversions. For some standard facets a standard “. . ._byname” class, derived from it, implements the virtual function semantics equivalent to that facet of the locale constructed by locale(const char*) with the same name. Each such facet provides a constructor that takes a const char* argument, which names the locale, and a refs argument, which is passed to the base class constructor. Each such facet also provides a constructor that takes a string argument str and a refs argument, which has the same effect as calling the first constructor with the two arguments str.c_str() and refs. If there is no “. . ._byname” version of a facet, the base class implements named locale semantics itself by reference to other facets. 22.3.1.1.3
Class locale::id
[locale.id]
namespace std { class locale::id { public: id(); void operator=(const id&) = delete; id(const id&) = delete; }; } 1
2
The class locale::id provides identification of a locale facet interface, used as an index for lookup and to encapsulate initialization. [ Note: Because facets are used by iostreams, potentially while static constructors are running, their initialization cannot depend on programmed static initialization. One initialization strategy is for locale to
§ 22.3.1.1.3
650
c ISO/IEC
N3376
initialize each facet’s id member the first time an instance of the facet is installed into a locale. This depends only on static storage being zero before constructors run (3.6.2). — end note ] 22.3.1.2 locale constructors and destructor [locale.cons] locale() noexcept; 1
Default constructor: a snapshot of the current global locale.
2
Effects: Constructs a copy of the argument last passed to locale::global(locale&), if it has been called; else, the resulting facets have virtual function semantics identical to those of locale::classic(). [ Note: This constructor is commonly used as the default value for arguments of functions that take a const locale& argument. — end note ] locale(const locale& other) noexcept;
3
Effects: Constructs a locale which is a copy of other.
4
Effects: Creates a copy of other, replacing the current value.
5
Returns: *this explicit locale(const char* std_name);
6
Effects: Constructs a locale using standard C locale names, e.g., "POSIX". The resulting locale implements semantics defined to be associated with that name.
7
Throws: runtime_error if the argument is not valid, or is null.
8
Remarks: The set of valid string argument values is "C", "", and any implementation-defined values. explicit locale(const string& std_name);
9
Effects: The same as locale(std_name.c_str()). locale(const locale& other, const char* std_name, category);
10
Effects: Constructs a locale as a copy of other except for the facets identified by the category argument, which instead implement the same semantics as locale(std_name).
11
Throws: runtime_error if the argument is not valid, or is null.
12
Remarks: The locale has a name if and only if other has a name. locale(const locale& other, const string& std_name, category cat);
13
Effects: The same as locale(other, std_name.c_str(), cat). template locale(const locale& other, Facet* f);
14
Effects: Constructs a locale incorporating all facets from the first argument except that of type Facet, and installs the second argument as the remaining facet. If f is null, the resulting object is a copy of other.
15
Remarks: The resulting locale has no name. § 22.3.1.2
651
c ISO/IEC
N3376
locale(const locale& other, const locale& one, category cats); 16
Effects: Constructs a locale incorporating all facets from the first argument except those that implement cats, which are instead incorporated from the second argument.
17
Remarks: The resulting locale has a name if and only if the first two arguments have names. const locale& operator=(const locale& other) noexcept; ~locale();
18
A non-virtual destructor that throws no exceptions. 22.3.1.3
locale members
[locale.members]
template locale combine(const locale& other) const; 1
Effects: Constructs a locale incorporating all facets from *this except for that one facet of other that is identified by Facet.
2
Returns: The newly created locale.
3
Throws: runtime_error if has_facet(other) is false.
4
Remarks: The resulting locale has no name. basic_string name() const;
5
Returns: The name of *this, if it has one; otherwise, the string "*". If *this has a name, then locale(name().c_str()) is equivalent to *this. Details of the contents of the resulting string are otherwise implementation-defined. 22.3.1.4
locale operators
[locale.operators]
bool operator==(const locale& other) const; 1
Returns: true if both arguments are the same locale, or one is a copy of the other, or each has a name and the names are identical; false otherwise. bool operator!=(const locale& other) const;
2
Returns: The result of the expression: !(*this == other). template bool operator()(const basic_string& s1, const basic_string& s2) const;
3
Effects: Compares two strings according to the collate facet.
4
Remarks: This member operator template (and therefore locale itself) satisfies requirements for a comparator predicate template argument (Clause 25) applied to strings.
5
Returns: The result of the following expression: use_facet< collate >(*this).compare (s1.data(), s1.data()+s1.size(), s2.data(), s2.data()+s2.size()) < 0;
§ 22.3.1.4
652
c ISO/IEC
6
N3376
[ Example: A vector of strings v can be collated according to collation rules in locale loc simply by (25.4.1, 23.3.6): std::sort(v.begin(), v.end(), loc);
— end example ] 22.3.1.5
locale static members
[locale.statics]
static locale global(const locale& loc); 1
Sets the global locale to its argument.
2
Effects: Causes future calls to the constructor locale() to return a copy of the argument. If the argument has a name, does std::setlocale(LC_ALL, loc.name().c_str());
otherwise, the effect on the C locale, if any, is implementation-defined. No library function other than locale::global() shall affect the value returned by locale(). [ Note: See 22.6 for data race considerations when setlocale is invoked. — end note ] 3
Returns: The previous value of locale(). static const locale& classic();
4
The "C" locale.
5
Returns: A locale that implements the classic "C" locale semantics, equivalent to the value locale("C").
6
Remarks: This locale, its facets, and their member functions, do not change with time.
22.3.2
locale globals
[locale.global.templates]
template const Facet& use_facet(const locale& loc); 1
Requires: Facet is a facet class whose definition contains the public static member id as defined in 22.3.1.1.2.
2
Returns: A reference to the corresponding facet of loc, if present.
3
Throws: bad_cast if has_facet(loc) is false.
4
Remarks: The reference returned remains valid at least as long as any copy of loc exists. template bool has_facet(const locale& loc) noexcept;
5
Returns: True if the facet requested is present in loc; otherwise false.
22.3.3 22.3.3.1 template template template template template template template
§ 22.3.3.1
Convenience interfaces
[locale.convenience]
Character classification
bool bool bool bool bool bool bool
isspace isprint iscntrl isupper islower isalpha isdigit
[classification] (charT (charT (charT (charT (charT (charT (charT
c, c, c, c, c, c, c,
const const const const const const const
locale& locale& locale& locale& locale& locale& locale&
loc); loc); loc); loc); loc); loc); loc);
653
c ISO/IEC
template template template template template 1
N3376
bool bool bool bool bool
ispunct (charT isxdigit(charT isalnum (charT isgraph (charT isblank (charT
c, c, c, c, c,
const const const const const
locale& locale& locale& locale& locale&
loc); loc); loc); loc); loc);
Each of these functions isF returns the result of the expression: use_facet< ctype >(loc).is(ctype_base::F , c)
where F is the ctype_base::mask value corresponding to that function (22.4.1).237 22.3.3.2 Conversions 22.3.3.2.1
Character conversions
[conversions]
[conversions.character]
template charT toupper(charT c, const locale& loc); 1
Returns: use_facet(loc).toupper(c). template charT tolower(charT c, const locale& loc);
2
Returns: use_facet(loc).tolower(c). 22.3.3.2.2
1
string conversions
[conversions.string]
Class template wstring_convert performs conversions between a wide string and a byte string. It lets you specify a code conversion facet (like class template codecvt) to perform the conversions, without affecting any streams or locales. [ Example: Say, for example, you have a code conversion facet called codecvt_utf8 that you want to use to output to cout a UTF-8 multibyte sequence corresponding to a wide string, but you don’t want to alter the locale for cout. You can write something like: wstring_convert> myconv; std::string mbstring = myconv.to_bytes(L"Hello\n"); std::cout class wstring_convert { public: typedef std::basic_string byte_string; typedef std::basic_string<Elem, char_traits<Elem>, Wide_alloc> wide_string; typedef typename Codecvt::state_type state_type; typedef typename wide_string::traits_type::int_type int_type; wstring_convert(Codecvt *pcvt = new Codecvt); wstring_convert(Codecvt *pcvt, state_type state); wstring_convert(const byte_string& byte_err, const wide_string& wide_err = wide_string()); ~wstring_convert(); wide_string from_bytes(char byte); wide_string from_bytes(const char *ptr); wide_string from_bytes(const byte_string& str); 237) When used in a loop, it is faster to cache the ctype facet and use it directly, or use the vector form of ctype::is.
§ 22.3.3.2.2
654
c ISO/IEC
N3376
wide_string from_bytes(const char *first, const char *last); byte_string byte_string byte_string byte_string
to_bytes(Elem wchar); to_bytes(const Elem *wptr); to_bytes(const wide_string& wstr); to_bytes(const Elem *first, const Elem *last);
size_t converted() const; state_type state() const; private: byte_string byte_err_string; wide_string wide_err_string; Codecvt *cvtptr; state_type cvtstate; size_t cvtcount; };
// // // // //
exposition exposition exposition exposition exposition
only only only only only
} 3
4
The class template describes an object that controls conversions between wide string objects of class std::basic_string<Elem, char_traits<Elem>, Wide_alloc> and byte string objects of class std:: basic_string. The class template defines the types wide_string and byte_string as synonyms for these two types. Conversion between a sequence of Elem values (stored in a wide_string object) and multibyte sequences (stored in a byte_string object) is performed by an object of class Codecvt<Elem, char, std::mbstate_t>, which meets the requirements of the standard code-conversion facet std::codecvt<Elem, char, std::mbstate_t>. An object of this class template stores: — byte_err_string — a byte string to display on errors — wide_err_string — a wide string to display on errors — cvtptr — a pointer to the allocated conversion object (which is freed when the wstring_convert object is destroyed) — cvtstate — a conversion state object — cvtcount — a conversion count typedef std::basic_string byte_string;
5
The type shall be a synonym for std::basic_string size_t converted() const;
6
Returns: cvtcount. wide_string wide_string wide_string wide_string
from_bytes(char byte); from_bytes(const char *ptr); from_bytes(const byte_string& str); from_bytes(const char *first, const char *last);
7
Effects: The first member function shall convert the single-element sequence byte to a wide string. The second member function shall convert the null-terminated sequence beginning at ptr to a wide string. The third member function shall convert the sequence stored in str to a wide string. The fourth member function shall convert the sequence defined by the range [first,last) to a wide string.
8
In all cases: § 22.3.3.2.2
655
c ISO/IEC
N3376
— If the cvtstate object was not constructed with an explicit value, it shall be set to its default value (the initial conversion state) before the conversion begins. Otherwise it shall be left unchanged. — The number of input elements successfully converted shall be stored in cvtcount. 9
Returns: If no conversion error occurs, the member function shall return the converted wide string. Otherwise, if the object was constructed with a wide-error string, the member function shall return the wide-error string. Otherwise, the member function throws an object of class std::range_error. typedef typename wide_string::traits_type::int_type int_type;
The type shall be a synonym for wide_string::traits_type::int_type. state_type state() const; 10
returns cvtstate. typedef typename Codecvt::state_type state_type;
11
The type shall be a synonym for Codecvt::state_type. byte_string byte_string byte_string byte_string
to_bytes(Elem wchar); to_bytes(const Elem *wptr); to_bytes(const wide_string& wstr); to_bytes(const Elem *first, const Elem *last);
12
Effects: The first member function shall convert the single-element sequence wchar to a byte string. The second member function shall convert the null-terminated sequence beginning at wptr to a byte string. The third member function shall convert the sequence stored in wstr to a byte string. The fourth member function shall convert the sequence defined by the range [first,last) to a byte string.
13
In all cases: — If the cvtstate object was not constructed with an explicit value, it shall be set to its default value (the initial conversion state) before the conversion begins. Otherwise it shall be left unchanged. — The number of input elements successfully converted shall be stored in cvtcount.
14
Returns: If no conversion error occurs, the member function shall return the converted byte string. Otherwise, if the object was constructed with a byte-error string, the member function shall return the byte-error string. Otherwise, the member function shall throw an object of class std::range_error. typedef std::basic_string<Elem> wide_string;
15
The type shall be a synonym for std::basic_string<Elem>. wstring_convert(Codecvt *pcvt = new Codecvt); wstring_convert(Codecvt *pcvt, state_type state); wstring_convert(const byte_string& byte_err, const wide_string& wide_err = wide_string());
§ 22.3.3.2.2
656
c ISO/IEC
16
N3376
Effects: The first constructor shall store pcvt in cvtptr and default values in cvtstate, byte_err_string, and wide_err_string. The second constructor shall store pcvt in cvtptr, state in cvtstate, and default values in byte_err_string and wide_err_string; moreover the stored state shall be retained between calls to from_bytes and to_bytes. The third constructor shall store new Codecvt in cvtptr, state_type() in cvtstate, byte_err in byte_err_string, and wide_err in wide_err_string. ~wstring_convert();
17
Effects: The destructor shall delete cvtptr. 22.3.3.2.3
1
2
Buffer conversions
[conversions.buffer]
Class template wbuffer_convert looks like a wide stream buffer, but performs all its I/O through an underlying byte stream buffer that you specify when you construct it. Like class template wstring_convert, it lets you specify a code conversion facet to perform the conversions, without affecting any streams or locales. Class template wbuffer_convert synopsis namespace std { template > class wbuffer_convert : public std::basic_streambuf<Elem, Tr> { public: typedef typename Codecvt::state_type state_type; wbuffer_convert(std::streambuf *bytebuf = 0, Codecvt *pcvt = new Codecvt, state_type state = state_type()); std::streambuf *rdbuf() const; std::streambuf *rdbuf(std::streambuf *bytebuf); state_type state() const; private: std::streambuf *bufptr; Codecvt *cvtptr; state_type cvtstate; };
// exposition only // exposition only // exposition only
} 3
4
The class template describes a stream buffer that controls the transmission of elements of type Elem, whose character traits are described by the class Tr, to and from a byte stream buffer of type std::streambuf. Conversion between a sequence of Elem values and multibyte sequences is performed by an object of class Codecvt<Elem, char, std::mbstate_t>, which shall meet the requirements of the standard codeconversion facet std::codecvt<Elem, char, std::mbstate_t>. An object of this class template stores: — bufptr — a pointer to its underlying byte stream buffer — cvtptr — a pointer to the allocated conversion object (which is freed when the wbuffer_convert object is destroyed) — cvtstate — a conversion state object § 22.3.3.2.3
657
c ISO/IEC
N3376
state_type state() const; 5
Returns: cvtstate. std::streambuf *rdbuf() const;
6
Returns: bufptr. std::streambuf *rdbuf(std::streambuf *bytebuf);
7
Effects: stores bytebuf in bufptr.
8
Returns: The previous value of bufptr. typedef typename Codecvt::state_type state_type;
9
The type shall be a synonym for Codecvt::state_type. wbuffer_convert(std::streambuf *bytebuf = 0, Codecvt *pcvt = new Codecvt, state_type state = state_type());
10
Effects: The constructor constructs a stream buffer object, initializes bufptr to bytebuf, initializes cvtptr to pcvt, and initializes cvtstate to state. ~wbuffer_convert();
11
Effects: The destructor shall delete cvtptr.
22.4 1
2
3
Standard locale categories
[locale.categories]
Each of the standard categories includes a family of facets. Some of these implement formatting or parsing of a datum, for use by standard or users’ iostream operators >, as members put() and get(), respectively. Each such member function takes an ios_base& argument whose members flags(), precision(), and width(), specify the format of the corresponding datum (27.5.3). Those functions which need to use other facets call its member getloc() to retrieve the locale imbued there. Formatting facets use the character argument fill to fill out the specified width where necessary. The put() members make no provision for error reporting. (Any failures of the OutputIterator argument must be extracted from the returned iterator.) The get() members take an ios_base::iostate& argument whose value they ignore, but set to ios_base::failbit in case of a parse error. Within this clause it is unspecified whether one virtual function calls another virtual function.
22.4.1
The ctype category
[category.ctype]
namespace std { class ctype_base { public: typedef T mask; // numeric values are for exposition only. static const mask space = 1 (std::istream& s, Date& d); std::ostream& operator std::string Date::asString(const std::locale& l) { using namespace std; ostringstream s; s.imbue(l); s >(std::istream& s, Date& d) { using namespace std; istream::sentry cerberos(s); if (cerberos) { ios_base::iostate err = goodbit;
§ 22.4.8
697
c ISO/IEC
N3376
struct tm t; use_facet< time_get >(s.getloc()).get_date(s, 0, s, err, &t); if (!err) d = Date(t.tm_day, t.tm_mon + 1, t.tm_year + 1900); s.setstate(err); } return s; } 10
11
— end example ] A locale object may be extended with a new facet simply by constructing it with an instance of a class derived from locale::facet. The only member a C++ program must define is the static member id, which identifies your class interface as a new facet. [ Example: Classifying Japanese characters: // file: <jctype> #include namespace My { using namespace std; class JCtype : public locale::facet { public: static locale::id id; // required for use as a new locale facet bool is_kanji (wchar_t c) const; JCtype() { } protected: ~JCtype() { } }; } // file: filt.C #include #include #include "jctype" // above std::locale::id My::JCtype::id; // the static JCtype member declared above. int main() { using namespace std; typedef ctype<wchar_t> wctype; locale loc(locale(""), // the user’s preferred locale ... new My::JCtype); // and a new feature ... wchar_t c = use_facet<wctype>(loc).widen(’!’); if (!use_facet<My::JCtype>(loc).is_kanji(c)) cout <deque> <list> <map> <set> <stack>
[container.requirements] [container.requirements.general]
Containers are objects that store other objects. They control allocation and deallocation of these objects through constructors, destructors, insert and erase operations. All of the complexity requirements in this Clause are stated solely in terms of the number of operations on the contained objects. [ Example: the copy constructor of type vector has linear complexity, even though the complexity of copying each contained vector is itself linear. — end example ] For the components affected by this subclause that declare an allocator_type, objects stored in these components shall be constructed using the allocator_traits::construct function and destroyed using the allocator_traits::destroy function (20.6.8.2). These functions are called only for the container’s element type, not for internal types used by the container. [ Note: This means, for example, that a node-based container might need to construct nodes containing aligned buffers and call construct to place the element into the buffer. — end note ] In Tables 96 and 97, X denotes a container class containing objects of type T, a and b denote values of type X, u denotes an identifier, r denotes a non-const value of type X, and rv denotes a non-const rvalue of type X.
§ 23.2.1
702
c ISO/IEC
N3376
Table 96 — Container requirements Expression
Return type
X::value_type
T
X::reference X::const_reference X::iterator
lvalue of T const lvalue of T iterator type whose value type is T
X::const_iterator
constant iterator type whose value type is T signed integer type
X::difference_type
X::size_type
Operational semantics
unsigned integer type
X u(a) X u = a;
X u(rv) X u = rv
§ 23.2.1
X&
Complexity compile time
compile time compile time
X u; X() X(a)
a = rv
Assertion/note pre-/post-condition Requires: T is Erasable from X (see 23.2.1, below)
All existing elements of a are either move assigned to or destroyed
any iterator category that meets the forward iterator requirements. convertible to X::const_iterator. any iterator category that meets the forward iterator requirements. is identical to the difference type of X::iterator and X::const_iterator size_type can represent any non-negative value of difference_type post: u.empty() post: X().empty() Requires:T is CopyInsertable into X (see below). post: a == X(a). Requires:T is CopyInsertable into X (see below). post: u == a post: u shall be equal to the value that rv had before this construction a shall be equal to the value that rv had before this assignment
compile time
compile time
compile time
compile time
constant constant linear
linear
(Note B)
linear
703
c ISO/IEC
N3376
Table 96 — Container requirements (continued) Expression (&a)->∼X()
void
a.begin()
iterator; const_iterator for constant a iterator; const_iterator for constant a const_iterator const_iterator convertible to bool
a.end()
a.cbegin() a.cend() a == b
a.swap(b)
convertible to bool void
swap(a, b) r = a a.size()
void X& size_type
a.max_size()
size_type
a.empty()
convertible to bool
a != b
5
Return type
Operational semantics
Assertion/note pre-/post-condition note: the destructor is applied to every element of a; all the memory is deallocated.
Complexity linear
constant
constant
const_cast<X const&>(a).begin(); const_cast<X const&>(a).end(); Requires: T is == is an equivalence EqualityComparable relation. distance(a.begin(), a.end()) == distance(b.begin(), b.end()) && equal(a.begin(), a.end(), b.begin()) Equivalent to: !(a == b) exchanges the contents of a and b a.swap(b) post: r == a. distance(a.begin(), a.end()) distance(begin(), end()) for the largest possible container a.begin() == a.end()
constant constant linear
linear (Note A) (Note A) linear constant constant
constant
Notes: the algorithm equal() is defined in Clause 25. Those entries marked “(Note A)” or “(Note B)” have linear complexity for array and have constant complexity for all other standard containers. The member function size() returns the number of elements in the container. The number of elements is defined by the rules of constructors, inserts, and erases.
§ 23.2.1
704
c ISO/IEC
6
7
8
9
N3376
begin() returns an iterator referring to the first element in the container. end() returns an iterator which is the past-the-end value for the container. If the container is empty, then begin() == end(); Unless otherwise specified, all containers defined in this clause obtain memory using an allocator (see 17.6.3.5). Copy constructors for these container types obtain an allocator by calling allocator_traits::select_on_container_copy_construction on their first parameters. Move constructors obtain an allocator by move construction from the allocator belonging to the container being moved. Such move construction of the allocator shall not exit via an exception. All other constructors for these container types take an Allocator& argument (17.6.3.5), an allocator whose value type is the same as the container’s value type. [ Note: If an invocation of a constructor uses the default value of an optional allocator argument, then the Allocator type must support value initialization. — end note ] A copy of this allocator is used for any memory allocation performed, by these constructors and by all member functions, during the lifetime of each container object or until the allocator is replaced. The allocator may be replaced only via assignment or swap(). Allocator replacement is performed by copy assignment, move assignment, or swapping of the allocator only if allocator_traits::propagate_on_container_copy_assignment::value, allocator_traits::propagate_on_container_move_assignment::value, or allocator_traits::propagate_on_container_swap::value is true within the implementation of the corresponding container operation. The behavior of a call to a container’s swap function is undefined unless the objects being swapped have allocators that compare equal or allocator_traits::propagate_on_container_swap::value is true. In all container types defined in this Clause, the member get_allocator() returns a copy of the allocator used to construct the container or, if that allocator has been replaced, a copy of the most recent replacement. The expression a.swap(b), for containers a and b of a standard container type other than array, shall exchange the values of a and b without invoking any move, copy, or swap operations on the individual container elements. Any Compare, Pred, or Hash objects belonging to a and b shall be swappable and shall be exchanged by unqualified calls to non-member swap. If allocator_traits::propagate_on_container_swap::value is true, then the allocators of a and b shall also be exchanged using an unqualified call to non-member swap. Otherwise, they shall not be swapped, and the behavior is undefined unless a.get_allocator() == b.get_allocator(). Every iterator referring to an element in one container before the swap shall refer to the same element in the other container after the swap. It is unspecified whether an iterator with value a.end() before the swap will have value b.end() after the swap. If the iterator type of a container belongs to the bidirectional or random access iterator categories (24.2), the container is called reversible and satisfies the additional requirements in Table 97. Table 97 — Reversible container requirements Expression X::reverse_iterator X::const_reverse_iterator a.rbegin()
a.rend()
a.crbegin();
§ 23.2.1
Return type iterator type whose value type is T iterator type whose value type is const T reverse_iterator; const_reverse_iterator for constant a reverse_iterator; const_reverse_iterator for constant a const_reverse_iterator
Assertion/note pre-/post-condition reverse_iterator
Complexity compile time
reverse_iterator
compile time
reverse_iterator(end())
constant
reverse_iterator(begin())
constant
const_cast<X const&>(a).rbegin();
constant
705
c ISO/IEC
N3376
Table 97 — Reversible container requirements (continued) Expression a.crend();
10
Return type const_reverse_iterator
Assertion/note pre-/post-condition const_cast<X const&>(a).rend();
Complexity constant
Unless otherwise specified (see 23.2.4.1, 23.2.5.1, 23.3.3.4, and 23.3.6.5) all container types defined in this Clause meet the following additional requirements: — if an exception is thrown by an insert() or emplace() function while inserting a single element, that function has no effects. — if an exception is thrown by a push_back() or push_front() function, that function has no effects. — no erase(), clear(), pop_back() or pop_front() function throws an exception. — no copy constructor or assignment operator of a returned iterator throws an exception. — no swap() function throws an exception. — no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. — end note ]
11
12
Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. Table 98 lists operations that are provided for some types of containers but not others. Those containers for which the listed operations are provided shall implement the semantics described in Table 98 unless otherwise stated. Table 98 — Optional container operations Expression a < b
convertible to bool
a > b
convertible to bool convertible to bool convertible to bool
a = b
13
Return type
Operational semantics lexicographical_compare( a.begin(), a.end(), b.begin(), b.end()) b < a
Assertion/note pre-/post-condition pre: < is defined for values of T. < is a total ordering relationship.
Complexity linear
linear
!(a > b)
linear
!(a < b)
linear
Note: the algorithm lexicographical_compare() is defined in Clause 25. All of the containers defined in this Clause and in (21.4) except array meet the additional requirements of an allocator-aware container, as described in Table 99. Given a container type X having an allocator_type identical to A and a value_type identical to T § 23.2.1
706
c ISO/IEC
N3376
and given an lvalue m of type A, a pointer p of type T*, an expression v of type (possibly const) T, and an rvalue rv of type T, the following terms are defined. If X is not allocator-aware, the terms below are defined as if A were std::allocator — no allocator object needs to be created and user specializations of std::allocator are not instantiated: — T is DefaultInsertable into X means that the following expression is well-formed: allocator_traits::construct(m, p);
— An element of X is default-inserted if it is initialized by evaluation of the expression allocator_traits::construct(m, p);
where p is the address of the uninitialized storage for the element allocated within X. — T is CopyInsertable into X means that the following expression is well-formed: allocator_traits::construct(m, p, v);
— T is MoveInsertable into X means that the following expression is well-formed: allocator_traits::construct(m, p, rv);
— T is EmplaceConstructible into X from args , for zero or more arguments args, means that the following expression is well-formed: allocator_traits::construct(m, p, args);
— T is Erasable from X means that the following expression is well-formed: allocator_traits::destroy(m, p);
14
[ Note: A container calls allocator_traits::construct(m, p, args) to construct an element at p using args. The default construct in std::allocator will call ::new((void*)p) T(args), but specialized allocators may choose a different definition. — end note ] In Table 99, X denotes an allocator-aware container class with a value_type of T using allocator of type A, u denotes a variable, a and b denote non-const lvalues of type X, t denotes an lvalue or a const rvalue of type X, rv denotes a non-const rvalue of type X, m is a value of type A, and Q is an allocator type. Table 99 — Allocator-aware container requirements Expression
Return type
allocator_type
A
get_allocator() X() X u;
A
X(m) X u(m); § 23.2.1
Assertion/note pre-/post-condition Requires:allocator_type::value_type is the same as X::value_type.
Complexity compile time
constant Requires: A is DefaultConstructible. post: u.empty() returns true, u.get_allocator() == A() post: u.empty() returns true, u.get_allocator() == m
constant
constant
707
c ISO/IEC
N3376
Table 99 — Allocator-aware container requirements (continued) Expression
Return type
X(t, m) X u(t, m);
X(rv) X u(rv)
X(rv, m) X u(rv, m);
a = t
X&
a = rv
X&
a.swap(b)
void
23.2.2 1
2
Container data races
Assertion/note pre-/post-condition Requires: T is CopyInsertable into X. post: u == t, get_allocator() == m Requires: move construction of A shall not exit via an exception. post: u shall have the same elements as rv had before this construction; the value of get_allocator() shall be the same as the value of rv.get_allocator() before this construction. Requires: T is MoveInsertable into X. post: u shall have the same elements, or copies of the elements, that rv had before this construction, get_allocator() == m Requires: T is CopyInsertable into X and CopyAssignable. post: a == t Requires: If allocator_traits ::propagate_on_container_move_assignment::value is false, T is MoveInsertable into X and MoveAssignable. All existing elements of a are either move assigned to or destroyed. post: a shall be equal to the value that rv had before this assignment. exchanges the contents of a and b
Complexity linear
constant
constant if m == rv.get_allocator(), otherwise linear
linear
linear
constant
[container.requirements.dataraces]
For purposes of avoiding data races (17.6.5.9), implementations shall consider the following functions to be const: begin, end, rbegin, rend, front, back, data, find, lower_bound, upper_bound, equal_range, at and, except in associative or unordered associative containers, operator[]. Notwithstanding (17.6.5.9), implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting vector, are modified concurrently.
§ 23.2.2
708
c ISO/IEC
3
[ Note: For a vector x with a size greater than one, x[1] = 5 and *x.begin() = 10 can be executed concurrently without a data race, but x[0] = 5 and *x.begin() = 10 executed concurrently may result in a data race. As an exception to the general rule, for a vector y, y[0] = true may race with y[1] = true. — end note ]
23.2.3 1
2
3
4
N3376
Sequence containers
[sequence.reqmts]
A sequence container organizes a finite set of objects, all of the same type, into a strictly linear arrangement. The library provides four basic kinds of sequence containers: vector, forward_list, list, and deque. In addition, array is provided as a sequence container which provides limited sequence operations because it has a fixed number of elements. The library also provides container adaptors that make it easy to construct abstract data types, such as stacks or queues, out of the basic sequence container kinds (or out of other kinds of sequence containers that the user might define). The sequence containers offer the programmer different complexity trade-offs and should be used accordingly. vector or array is the type of sequence container that should be used by default. list or forward_list should be used when there are frequent insertions and deletions from the middle of the sequence. deque is the data structure of choice when most insertions and deletions take place at the beginning or at the end of the sequence. In Tables 100 and 101, X denotes a sequence container class, a denotes a value of X containing elements of type T, A denotes X::allocator_type if it exists and std::allocator if it doesn’t, i and j denote iterators satisfying input iterator requirements and refer to elements implicitly convertible to value_type, [i, j) denotes a valid range, il designates an object of type initializer_list, n denotes a value of X::size_type, p denotes a valid const iterator to a, q denotes a valid dereferenceable const iterator to a, [q1, q2) denotes a valid range of const iterators in a, t denotes an lvalue or a const rvalue of X::value_type, and rv denotes a non-const rvalue of X::value_type. Args denotes a template parameter pack; args denotes a function parameter pack with the pattern Args&&. The complexities of the expressions are sequence dependent. Table 100 — Sequence container requirements (in addition to container) Expression X(n, t) X a(n, t)
X(i, j) X a(i, j)
X(il);
§ 23.2.3
Return type
Assertion/note pre-/post-condition Requires:T shall be CopyInsertable into X. post: distance(begin(), end()) == n Constructs a sequence container with n copies of t Requires: T shall be EmplaceConstructible into X from *i. For vector, if the iterator does not meet the forward iterator requirements (24.2.5), T shall also be MoveInsertable into X. Each iterator in the range [i,j) shall be dereferenced exactly once. post: distance(begin(), end()) == distance(i, j) Constructs a sequence container equal to the range [i, j) Equivalent to X(il.begin(), il.end())
709
c ISO/IEC
N3376
Table 100 — Sequence container requirements (in addition to container) (continued) Expression
Return type
a = il;
X&
a.emplace(p, args);
iterator
a.insert(p,t)
iterator
a.insert(p,rv)
iterator
a.insert(p,n,t)
iterator
a.insert(p,i,j)
iterator
a.insert(p, il); a.erase(q)
iterator iterator
a.erase(q1,q2)
iterator
a.clear()
void
§ 23.2.3
Assertion/note pre-/post-condition Requires: T is CopyInsertable into X and CopyAssignable. Assigns the range [il.begin(),il.end()) into a. All existing elements of a are either assigned to or destroyed. Returns: *this. Requires: T is EmplaceConstructible into X from args. For vector and deque, T is also MoveInsertable into X and MoveAssignable. Effects: Inserts an object of type T constructed with std::forward(args)... before p. Requires:T shall be CopyInsertable into X. For vector and deque, T shall also be CopyAssignable. Effects: Inserts a copy of t before p. Requires: T shall be MoveInsertable into X. For vector and deque, T shall also be MoveAssignable. Effects: Inserts a copy of rv before p. Requires:T shall be CopyInsertable into X and CopyAssignable. Inserts n copies of t before p. Requires:T shall be EmplaceConstructible into X from *i. For vector, if the iterator does not meet the forward iterator requirements (24.2.5), T shall also be MoveInsertable into X and MoveAssignable. Each iterator in the range [i,j) shall be dereferenced exactly once. pre: i and j are not iterators into a. Inserts copies of elements in [i, j) before p a.insert(p, il.begin(), il.end()). Requires: For vector and deque, T shall be MoveAssignable. Effects: Erases the element pointed to by q Requires: For vector and deque, T shall be MoveAssignable. Effects: Erases the elements in the range [q1, q2). Destroys all elements in a. Invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator. post: a.empty() returns true 710
c ISO/IEC
N3376
Table 100 — Sequence container requirements (in addition to container) (continued) Expression
5 6 7 8
9
10
11 12
13
14
Return type
a.assign(i,j)
void
a.assign(il) a.assign(n,t)
void void
Assertion/note pre-/post-condition Requires: T shall be EmplaceConstructible into X from *i and assignable from *i. For vector, if the iterator does not meet the forward iterator requirements (24.2.5), T shall also be MoveInsertable into X. Each iterator in the range [i,j) shall be dereferenced exactly once. pre: i, j are not iterators into a. Replaces elements in a with a copy of [i, j). a.assign(il.begin(), il.end()). Requires:T shall be CopyInsertable into X and CopyAssignable. pre: t is not a reference into a. Replaces elements in a with n copies of t.
iterator and const_iterator types for sequence containers shall be at least of the forward iterator category. The iterator returned from a.insert(p, t) points to the copy of t inserted into a. The iterator returned from a.insert(p, rv) points to the copy of rv inserted into a. The iterator returned from a.insert(p, n, t) points to the copy of the first element inserted into a, or p if n == 0. The iterator returned from a.insert(p, i, j) points to the copy of the first element inserted into a, or p if i == j. The iterator returned from a.insert(p, i1) points to the copy of the first element inserted into a, or p if i1 is empty. The iterator returned from a.emplace(p, args) points to the new element constructed from args into a. The iterator returned from a.erase(q) points to the element immediately following q prior to the element being erased. If no such element exists, a.end() is returned. The iterator returned by a.erase(q1,q2) points to the element pointed to by q2 prior to any elements being erased. If no such element exists, a.end() is returned. For every sequence container defined in this Clause and in Clause 21: — If the constructor template X(InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type())
is called with a type InputIterator that does not qualify as an input iterator, then the constructor shall not participate in overload resolution. — If the member functions of the forms: template // such as insert() rt fx1(const_iterator p, InputIterator first, InputIterator last); template // such as append(), assign() rt fx2(InputIterator first, InputIterator last); template
§ 23.2.3
// such as replace()
711
c ISO/IEC
N3376
rt fx3(const_iterator i1, const_iterator i2, InputIterator first, InputIterator last);
are called with a type InputIterator that does not qualify as an input iterator, then these functions shall not participate in overload resolution. 15
16
The extent to which an implementation determines that a type cannot be an input iterator is unspecified, except that as a minimum integral types shall not qualify as input iterators. Table 101 lists operations that are provided for some types of sequence containers but not others. An implementation shall provide these operations for all container types shown in the “container” column, and shall implement them so as to take amortized constant time. Table 101 — Optional sequence container operations Expression a.front()
Return type reference; const_reference for constant a
a.back()
reference; const_reference for constant a
a.emplace_front(args)
void
a.emplace_back(args)
void
Operational semantics *a.begin()
Container basic_string, array, deque, forward_list, list, vector basic_{ auto tmp = a.end(); string, --tmp; array, deque, return *tmp; } list, vector Prepends an deque, object of type T constructed with forward_std::forward(args).... list, list Requires: T shall be EmplaceConstructible into X from args. deque, list, Appends an object of type T constructed with vector std::forward(args).... Requires: T shall be EmplaceConstructible into X from args. For vector, T shall also be MoveInsertable into X. Prepends a copy of t. Requires: T shall be CopyInsertable into X.
a.push_front(t)
void
a.push_front(rv)
void
Prepends a copy of rv. Requires: T shall be MoveInsertable into X.
a.push_back(t)
void
Appends a copy of t. Requires: T shall be CopyInsertable into X.
§ 23.2.3
deque, forward_list, list deque, forward_list, list basic_string, deque, list, vector 712
c ISO/IEC
N3376
Table 101 — Optional sequence container operations (continued) Expression a.push_back(rv)
17
2
3
4
5
6
void
Operational semantics Appends a copy of rv. Requires: T shall be MoveInsertable into X.
a.pop_front()
void
Destroys the first element. Requires: a.empty() shall be false.
a.pop_back()
void
Destroys the last element. Requires: a.empty() shall be false.
a[n]
reference; const_reference for constant a
*(a.begin() + n)
a.at(n)
reference; const_reference for constant a
*(a.begin() + n)
Container basic_string, deque, list, vector deque, forward_list, list basic_string, deque, list, vector basic_string, array, deque, vector basic_string, array, deque, vector
The member function at() provides bounds-checked access to container elements. at() throws out_of_range if n >= a.size().
23.2.4 1
Return type
Associative containers
[associative.reqmts]
Associative containers provide fast retrieval of data based on keys. The library provides four basic kinds of associative containers: set, multiset, map and multimap. Each associative container is parameterized on Key and an ordering relation Compare that induces a strict weak ordering (25.4) on elements of Key. In addition, map and multimap associate an arbitrary mapped type T with the Key. The object of type Compare is called the comparison object of a container. The phrase “equivalence of keys” means the equivalence relation imposed by the comparison and not the operator== on keys. That is, two keys k1 and k2 are considered to be equivalent if for the comparison object comp, comp(k1, k2) == false && comp(k2, k1) == false. For any two keys k1 and k2 in the same container, calling comp(k1, k2) shall always return the same value. An associative container supports unique keys if it may contain at most one element for each key. Otherwise, it supports equivalent keys. The set and map classes support unique keys; the multiset and multimap classes support equivalent keys. For multiset and multimap, insert, emplace, and erase preserve the relative ordering of equivalent elements. For set and multiset the value type is the same as the key type. For map and multimap it is equal to pair. iterator of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators. It is unspecified whether or not iterator and const_iterator are the same type. [ Note: iterator and const_iterator have identical semantics in this case, and iterator is convertible to const_iterator. Users can avoid violating the One Definition Rule by always using const_iterator in their function parameter lists. — end note ]
§ 23.2.4
713
c ISO/IEC
7
8
N3376
The associative containers meet all the requirements of Allocator-aware containers (23.2.1), except that for map and multimap, the requirements placed on value_type in Table 96 apply instead to key_type and mapped_type. [ Note: For example, in some cases key_type and mapped_type are required to be CopyAssignable even though the associated value_type, pair, is not CopyAssignable. — end note ] In Table 102, X denotes an associative container class, a denotes a value of X, a_uniq denotes a value of X when X supports unique keys, a_eq denotes a value of X when X supports multiple keys, u denotes an identifier, i and j satisfy input iterator requirements and refer to elements implicitly convertible to value_type, [i,j) denotes a valid range, p denotes a valid const iterator to a, q denotes a valid dereferenceable const iterator to a, [q1, q2) denotes a valid range of const iterators in a, il designates an object of type initializer_list, t denotes a value of X::value_type, k denotes a value of X::key_type and c denotes a value of type X::key_compare. A denotes the storage allocator used by X, if any, or std::allocator<X::value_type> otherwise, and m denotes an allocator of a type convertible to A. Table 102 — Associative container requirements (in addition to container) Expression X::key_type mapped_type (map and multimap only) X::value_type (set and multiset only) X::value_type (map and multimap only) X::key_compare X::value_compare
X(c) X a(c);
§ 23.2.4
Return type
Assertion/note pre-/post-condition
Complexity compile time compile time
Key T
Key
Requires: value_type is Erasable from X
compile time
pair
Requires: value_type is Erasable from X
compile time
Compare
defaults to less
compile time
a binary predicate type
is the same as key_compare for set and multiset; is an ordering relation on pairs induced by the first component (i.e., Key) for map and multimap. Requires: key_compare is CopyConstructible. Effects: Constructs an empty container. Uses a copy of c as a comparison object.
compile time
constant
714
c ISO/IEC
N3376
Table 102 — Associative container requirements (in addition to container) (continued) Expression
Return type
X() X a;
X(i,j,c) X a(i,j,c);
X(i,j) X a(i,j);
X(il); a = il
X&
a.key_comp()
X::key_compare
a.value_comp()
X::value_compare
§ 23.2.4
Assertion/note pre-/post-condition Requires: key_compare is DefaultConstructible. Effects: Constructs an empty container. Uses Compare() as a comparison object Requires: key_compare is CopyConstructible. value_type is EmplaceConstructible into X from *i. Effects: Constructs an empty container and inserts elements from the range [i, j) into it; uses c as a comparison object. Requires: key_compare is DefaultConstructible. value_type is EmplaceConstructible into X from *i. Effects: Same as above, but uses Compare() as a comparison object Same as X(il.begin(), il.end()). Requires: value_type is CopyInsertable into X and CopyAssignable. Effects: Assigns the range [il.begin(),il.end()) into a. All existing elements of a are either assigned to or destroyed. returns the comparison object out of which a was constructed. returns an object of value_compare constructed out of the comparison object
Complexity constant
N log N in general (N has the value distance(i, j)); linear if [i, j) is sorted with value_comp()
same as above
same as X(il.begin(), il.end()). N logN in general (where N has the value il.size() + a.size()); linear if [il.begin(),il.end()) is sorted with value_comp().
constant
constant
715
c ISO/IEC
N3376
Table 102 — Associative container requirements (in addition to container) (continued) Expression
Assertion/note Complexity pre-/post-condition a_uniq. pair EmplaceConstructible into X from args. Effects: Inserts a value_type object t constructed with std::forward(args)... if and only if there is no element in the container with key equivalent to the key of t. The bool component of the returned pair is true if and only if the insertion takes place, and the iterator component of the pair points to the element with key equivalent to the key of t. logarithmic a_eq. iterator Requires: value_type shall be emplace(args) EmplaceConstructible into X from args. Effects: Inserts a value_type object t constructed with std::forward(args)... and returns the iterator pointing to the newly inserted element. If a range containing elements equivalent to t exists in a_eq, t is inserted at the end of that range. a.emplace_iterator equivalent to a.emplace( logarithmic in general, but hint(p, std::forward(args)...).amortized constant if the args) Return value is an iterator element is inserted right pointing to the element with before p the key equivalent to the newly inserted element. The element is inserted as close as possible to the position just prior to p.
§ 23.2.4
Return type
716
c ISO/IEC
N3376
Table 102 — Associative container requirements (in addition to container) (continued) Expression
Assertion/note pre-/post-condition a_uniq. pair rvalue expression, value_type shall be MoveInsertable into X; otherwise, value_type shall be CopyInsertable into X. Effects: Inserts t if and only if there is no element in the container with key equivalent to the key of t. The bool component of the returned pair is true if and only if the insertion takes place, and the iterator component of the pair points to the element with key equivalent to the key of t. a_iterator Requires: If t is a non-const eq.insert(t) rvalue expression, value_type shall be MoveInsertable into X; otherwise, value_type shall be CopyInsertable into X. Effects: Inserts t and returns the iterator pointing to the newly inserted element. If a range containing elements equivalent to t exists in a_eq, t is inserted at the end of that range. a.insert( iterator Requires: If t is a non-const p, t) rvalue expression, value_type shall be MoveInsertable into X; otherwise, value_type shall be CopyInsertable into X. Effects: Inserts t if and only if there is no element with key equivalent to the key of t in containers with unique keys; always inserts t in containers with equivalent keys. always returns the iterator pointing to the element with key equivalent to the key of t. t is inserted as close as possible to the position just prior to p.
§ 23.2.4
Return type
Complexity logarithmic
logarithmic
logarithmic in general, but amortized constant if t is inserted right before p.
717
c ISO/IEC
N3376
Table 102 — Associative container requirements (in addition to container) (continued) Expression a.insert( i, j)
Return type void
a.insert(il) void
a.erase(k)
size_type
a.erase(q)
iterator
a.erase( q1, q2)
iterator
a.clear()
void
a.find(k)
iterator; const_iterator for constant a. size_type
a.count(k) a.lower_bound(k)
§ 23.2.4
iterator; const_iterator for constant a.
Assertion/note pre-/post-condition Requires: value_type shall be EmplaceConstructible into X from *i. pre: i, j are not iterators into a. inserts each element from the range [i,j) if and only if there is no element with key equivalent to the key of that element in containers with unique keys; always inserts that element in containers with equivalent keys. Equivalent to a.insert(il.begin(), il.end()). erases all elements in the container with key equivalent to k. returns the number of erased elements. erases the element pointed to by q. Returns an iterator pointing to the element immediately following q prior to the element being erased. If no such element exists, returns a.end(). erases all the elements in the range [q1,q2). Returns q2. a.erase(a.begin(),a.end()) post: a.empty() returns true returns an iterator pointing to an element with the key equivalent to k, or a.end() if such an element is not found returns the number of elements with key equivalent to k returns an iterator pointing to the first element with key not less than k, or a.end() if such an element is not found.
Complexity N log(a.size() + N ) (N has the value distance(i, j)
log(a.size()) + a.count(k)
amortized constant
log(a.size()) + N where N has the value distance(q1, q2). linear in a.size().
logarithmic
log(a.size()) + a.count(k) logarithmic
718
c ISO/IEC
N3376
Table 102 — Associative container requirements (in addition to container) (continued) Expression a.upper_bound(k)
a.equal_range(k)
9
10
Return type
Assertion/note pre-/post-condition iterator; returns an iterator pointing to const_the first element with key iterator for greater than k, or a.end() if constant a. such an element is not found. pair; pair(a.lower_bound(k), pair for constant a.
Complexity logarithmic
logarithmic
The insert and emplace members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements. The fundamental property of iterators of associative containers is that they iterate through the containers in the non-descending order of keys where non-descending is defined by the comparison that was used to construct them. For any two dereferenceable iterators i and j such that distance from i to j is positive, value_comp(*j, *i) == false
11
For associative containers with unique keys the stronger condition holds, value_comp(*i, *j) != false.
12
When an associative container is constructed by passing a comparison object the container shall not store a pointer or reference to the passed object, even if that object is passed by reference. When an associative container is copied, either through a copy constructor or an assignment operator, the target container shall then use the comparison object from the container being copied, as if that comparison object had been passed to the target container in its constructor. 23.2.4.1 Exception safety guarantees [associative.reqmts.except]
1
For associative containers, no clear() function throws an exception. erase(k) does not throw an exception unless that exception is thrown by the container’s Compare object (if any). For associative containers, if an exception is thrown by any operation from within an insert or emplace function inserting a single element, the insertion has no effect. For associative containers, no swap function throws an exception unless that exception is thrown by the swap of the container’s Compare object (if any).
2
3
23.2.5 1
2
3
Unordered associative containers
[unord.req]
Unordered associative containers provide an ability for fast retrieval of data based on keys. The worstcase complexity for most operations is linear, but the average case is much faster. The library provides four unordered associative containers: unordered_set, unordered_map, unordered_multiset, and unordered_multimap. Unordered associative containers conform to the requirements for Containers (23.2), except that the expressions a == b and a != b have different semantics than for the other container types. Each unordered associative container is parameterized by Key, by a function object type Hash that meets the Hash requirements (17.6.3.4) and acts as a hash function for argument values of type Key, and by a binary predicate Pred that induces an equivalence relation on values of type Key. Additionally, unordered_map and unordered_multimap associate an arbitrary mapped type T with the Key. § 23.2.5
719
c ISO/IEC
4
5
6
7
8
9
10
11
N3376
The container’s object of type Hash — denoted by hash — is called the hash function of the container. The container’s object of type Pred — denoted by pred — is called the key equality predicate of the container. Two values k1 and k2 of type Key are considered equivalent if the container’s key equality predicate returns true when passed those values. If k1 and k2 are equivalent, the container’s hash function shall return the same value for both. [ Note: Thus, when an unordered associative container is instantiated with a nondefault Pred parameter it usually needs a non-default Hash parameter as well. — end note ] For any two keys k1 and k2 in the same container, calling pred(k1, k2) shall always return the same value. For any key k in a container, calling hash(k) shall always return the same value. An unordered associative container supports unique keys if it may contain at most one element for each key. Otherwise, it supports equivalent keys. unordered_set and unordered_map support unique keys. unordered_multiset and unordered_multimap support equivalent keys. In containers that support equivalent keys, elements with equivalent keys are adjacent to each other in the iteration order of the container. Thus, although the absolute order of elements in an unordered container is not specified, its elements are grouped into equivalent-key groups such that all elements of each group have equivalent keys. Mutating operations on unordered containers shall preserve the relative order of elements within each equivalent-key group unless otherwise specified. For unordered_set and unordered_multiset the value type is the same as the key type. For unordered_map and unordered_multimap it is std::pair. For unordered containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators. It is unspecified whether or not iterator and const_iterator are the same type. [ Note: iterator and const_iterator have identical semantics in this case, and iterator is convertible to const_iterator. Users can avoid violating the One Definition Rule by always using const_iterator in their function parameter lists. — end note ] The elements of an unordered associative container are organized into buckets. Keys with the same hash code appear in the same bucket. The number of buckets is automatically increased as elements are added to an unordered associative container, so that the average number of elements per bucket is kept below a bound. Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. For unordered_multiset and unordered_multimap, rehashing preserves the relative ordering of equivalent elements. The unordered associative containers meet all the requirements of Allocator-aware containers (23.2.1), except that for unordered_map and unordered_multimap, the requirements placed on value_type in Table 96 apply instead to key_type and mapped_type. [ Note: For example, key_type and mapped_type are sometimes required to be CopyAssignable even though the associated value_type, pair, is not CopyAssignable. — end note ] In table 103: X is an unordered associative container class, a is an object of type X, b is a possibly const object of type X, a_uniq is an object of type X when X supports unique keys, a_eq is an object of type X when X supports equivalent keys, i and j are input iterators that refer to value_type, [i, j) is a valid range, p and q2 are valid const iterators to a, q and q1 are valid dereferenceable const iterators to a, [q1, q2) is a valid range in a, il designates an object of type initializer_list, t is a value of type X::value_type, k is a value of type key_type, hf is a possibly const value of type hasher, eq is a possibly const value of type key_equal, n is a value of type size_type, and z is a value of type float. Table 103 — Unordered associative container requirements (in addition to container) Expression X::key_type
§ 23.2.5
Return type Key
Assertion/note pre-/post-condition
Complexity compile time
720
c ISO/IEC
N3376
Table 103 — Unordered associative container requirements (in addition to container) (continued) Expression X::mapped_type (unordered_map and unordered_multimap only) X::value_type (unordered_set and unordered_multiset only) X::value_type (unordered_map and unordered_multimap only) X::hasher
X::key_equal
Pred
X::local_iterator
An iterator type whose category, value type, difference type, and pointer and reference types are the same as X::iterator’s. An iterator type whose category, value type, difference type, and pointer and reference types are the same as X::const_iterator’s. X
X::const_local_iterator
X(n, hf, eq) X a(n, hf, eq)
§ 23.2.5
Return type
Assertion/note pre-/post-condition
Complexity compile time
Key
Requires: value_type is Erasable from X
compile time
pair
Requires: value_type is Erasable from X
compile time
Hash
Hash shall be a unary function object type such that the expression hf(k) has type std::size_t. Pred shall be a binary predicate that takes two arguments of type Key. Pred is an equivalence relation. A local_iterator object may be used to iterate through a single bucket, but may not be used to iterate across buckets.
compile time
T
compile time
compile time
A const_local_iterator object may be used to iterate through a single bucket, but may not be used to iterate across buckets.
compile time
Requires: hasher and key_equal are CopyConstructible. Effects: Constructs an empty container with at least n buckets, using hf as the hash function and eq as the key equality predicate.
O(n)
721
c ISO/IEC
N3376
Table 103 — Unordered associative container requirements (in addition to container) (continued) Expression X(n, hf) X a(n, hf)
Return type X
X(n) X a(n)
X
X() X a
X
X(i, j, n, hf, eq) X a(i, j, n, hf, eq)
X
§ 23.2.5
Assertion/note pre-/post-condition Requires: hasher is CopyConstructible and key_equal is DefaultConstructible. Effects: Constructs an empty container with at least n buckets, using hf as the hash function and key_equal() as the key equality predicate. Requires: hasher and key_equal are DefaultConstructible. Effects: Constructs an empty container with at least n buckets, using hasher() as the hash function and key_equal() as the key equality predicate. Requires: hasher and key_equal are DefaultConstructible. Effects: Constructs an empty container with an unspecified number of buckets, using hasher() as the hash function and key_equal() as the key equality predicate. Requires: hasher and key_equal are CopyConstructible. value_type is EmplaceConstructible into X from *i. Effects: Constructs an empty container with at least n buckets, using hf as the hash function and eq as the key equality predicate, and inserts elements from [i, j) into it.
Complexity O(n)
O(n)
constant
Average case O(N ) (N is distance(i, j)), worst case O(N 2 )
722
c ISO/IEC
N3376
Table 103 — Unordered associative container requirements (in addition to container) (continued) Expression X(i, j, n, hf) X a(i, j, n, hf)
Return type X
X(i, j, n) X a(i, j, n)
X
X(i, j) X a(i, j)
X
X(il)
X
§ 23.2.5
Assertion/note pre-/post-condition Requires: hasher is CopyConstructible and key_equal is DefaultConstructible. value_type is EmplaceConstructible into X from *i. Effects: Constructs an empty container with at least n buckets, using hf as the hash function and key_equal() as the key equality predicate, and inserts elements from [i, j) into it. Requires: hasher and key_equal are DefaultConstructible. value_type is EmplaceConstructible into X from *i. Effects: Constructs an empty container with at least n buckets, using hasher() as the hash function and key_equal() as the key equality predicate, and inserts elements from [i, j) into it. Requires: hasher and key_equal are DefaultConstructible. value_type is EmplaceConstructible into X from *i. Effects: Constructs an empty container with an unspecified number of buckets, using hasher() as the hash function and key_equal() as the key equality predicate, and inserts elements from [i, j) into it. Same as X(il.begin(), il.end()).
Complexity Average case O(N ) (N is distance(i, j)), worst case O(N 2 )
Average case O(N ) (N is distance(i, j)), worst case O(N 2 )
Average case O(N ) (N is distance(i, j)), worst case O(N 2 )
Same as X(il.begin(), il.end()).
723
c ISO/IEC
N3376
Table 103 — Unordered associative container requirements (in addition to container) (continued) Expression
Return type
X(b) X a(b)
X
a = b
X&
a = il
X&
b.hash_function() b.key_eq()
hasher key_equal
a_uniq. emplace(args)
pair
a_eq.emplace(args)
iterator
§ 23.2.5
Assertion/note pre-/post-condition Copy constructor. In addition to the requirements of Table 96, copies the hash function, predicate, and maximum load factor. Copy assignment operator. In addition to the requirements of Table 96, copies the hash function, predicate, and maximum load factor. Requires: value_type is CopyInsertable into X and CopyAssignable. Effects: Assigns the range [il.begin(),il.end()) into a. All existing elements of a are either assigned to or destroyed. Returns b’s hash function. Returns b’s key equality predicate. Requires: value_type shall be EmplaceConstructible into X from args. Effects: Inserts a value_type object t constructed with std::forward(args)... if and only if there is no element in the container with key equivalent to the key of t. The bool component of the returned pair is true if and only if the insertion takes place, and the iterator component of the pair points to the element with key equivalent to the key of t. Requires: value_type shall be EmplaceConstructible into X from args. Effects: Inserts a value_type object t constructed with std::forward(args)... and returns the iterator pointing to the newly inserted element.
Complexity Average case linear in b.size(), worst case quadratic. Average case linear in b.size(), worst case quadratic. Same as a = X(il).
constant constant Average case O(1), worst case O(a_uniq. size()).
Average case O(1), worst case O(a_eq. size()).
724
c ISO/IEC
N3376
Table 103 — Unordered associative container requirements (in addition to container) (continued) Expression a.emplace_hint(p, args)
Return type iterator
a_uniq.insert(t)
pair
a_eq.insert(t)
iterator
§ 23.2.5
Assertion/note pre-/post-condition Requires: value_type shall be EmplaceConstructible into X from args. Effects: Equivalent to a.emplace( std::forward(args)...). Return value is an iterator pointing to the element with the key equivalent to the newly inserted element. The const_iterator p is a hint pointing to where the search should start. Implementations are permitted to ignore the hint. Requires: If t is a non-const rvalue expression, value_type shall be MoveInsertable into X; otherwise, value_type shall be CopyInsertable into X. Effects: Inserts t if and only if there is no element in the container with key equivalent to the key of t. The bool component of the returned pair indicates whether the insertion takes place, and the iterator component points to the element with key equivalent to the key of t. Requires: If t is a non-const rvalue expression, value_type shall be MoveInsertable into X; otherwise, value_type shall be CopyInsertable into X. Effects: Inserts t, and returns an iterator pointing to the newly inserted element.
Complexity Average case O(1), worst case O(a.size()).
Average case O(1), worst case O(a_uniq. size()).
Average case O(1), worst case O(a_eq. size()).
725
c ISO/IEC
N3376
Table 103 — Unordered associative container requirements (in addition to container) (continued) Expression a.insert(q, t)
Return type iterator
a.insert(i, j)
void
a.insert(il)
void
Same as a.insert(il.begin(), il.end()).
a.erase(k)
size_type
Erases all elements with key equivalent to k. Returns the number of elements erased.
a.erase(q)
iterator
a.erase(q1, q2)
iterator
a.clear()
void
b.find(k)
iterator; const_iterator for const b.
Erases the element pointed to by q. Return value is the iterator immediately following q prior to the erasure. Erases all elements in the range [q1, q2). Return value is the iterator immediately following the erased elements prior to the erasure. Erases all elements in the container. Post: a.empty() returns true Returns an iterator pointing to an element with key equivalent to k, or b.end() if no such element exists.
§ 23.2.5
Assertion/note pre-/post-condition Requires: If t is a non-const rvalue expression, value_type shall be MoveInsertable into X; otherwise, value_type shall be CopyInsertable into X. Effects: Equivalent to a.insert(t). Return value is an iterator pointing to the element with the key equivalent to that of t. The iterator q is a hint pointing to where the search should start. Implementations are permitted to ignore the hint. Requires: value_type shall be EmplaceConstructible into X from *i. Pre: i and j are not iterators in a. Equivalent to a.insert(t) for each element in [i,j).
Complexity Average case O(1), worst case O(a.size()).
Average case O(N ), where N is distance(i, j). Worst case O(N ∗ (a.size()) + N). Same as a.insert( il.begin(), il.end()). Average case O(a.count(k)). Worst case O(a.size()). Average case O(1), worst case O(a.size()). Average case linear in distance(q1, q2), worst case O(a.size()). Linear.
Average case O(1), worst case O(b.size()).
726
c ISO/IEC
N3376
Table 103 — Unordered associative container requirements (in addition to container) (continued) Expression b.count(k)
Return type size_type
Assertion/note pre-/post-condition Returns the number of elements with key equivalent to k.
b.equal_range(k)
pair; pair for const b. size_type
Returns a range containing all elements with keys equivalent to k. Returns make_pair(b.end(), b.end()) if no such elements exist. Returns the number of buckets that b contains. Returns an upper bound on the number of buckets that b might ever contain. Pre: b.bucket_count() > 0. Returns the index of the bucket in which elements with keys equivalent to k would be found, if any such element existed. Post: the return value shall be in the range [0, b.bucket_count()). Pre: n shall be in the range [0, b.bucket_count()). Returns the number of elements in the n th bucket. Pre: n shall be in the range [0, b.bucket_count()). b.begin(n) returns an iterator referring to the first element in the bucket. If the bucket is empty, then b.begin(n) == b.end(n). Pre: n shall be in the range [0, b.bucket_count()). b.end(n) returns an iterator which is the past-the-end value for the bucket. Pre: n shall be in the range [0, b.bucket_count()). Note: [b.cbegin(n), b.cend(n)) is a valid range containing all of the elements in the n th bucket. Pre: n shall be in the range [0, b.bucket_count()).
b.bucket_count() b.max_bucket_count()
size_type
b.bucket(k)
size_type
b.bucket_size(n)
size_type
b.begin(n)
local_iterator; const_local_iterator for const b.
b.end(n)
local_iterator; const_local_iterator for const b.
b.cbegin(n)
const_local_iterator
b.cend(n)
const_local_iterator
§ 23.2.5
Complexity Average case O(1), worst case O(b.size()). Average case O(b.count(k)). Worst case O(b.size()).
Constant Constant
Constant
O(b.bucket_size(n))
Constant
Constant
Constant
Constant
727
c ISO/IEC
N3376
Table 103 — Unordered associative container requirements (in addition to container) (continued)
12
13
Expression b.load_factor()
Return type float
b.max_load_factor()
float
a.max_load_factor(z)
void
a.rehash(n)
void
a.reserve(n)
void
Assertion/note pre-/post-condition Returns the average number of elements per bucket. Returns a positive number that the container attempts to keep the load factor less than or equal to. The container automatically increases the number of buckets as necessary to keep the load factor below this number. Pre: z shall be positive. May change the container’s maximum load load factor, using z as a hint. Post: a.bucket_count() > a.size() / a.max_load_factor() and a.bucket_count() >= n. Same as a.rehash(ceil(n / a.max_load_factor())).
Complexity Constant Constant
Constant
Average case linear in a.size(), worst case quadratic. Average case linear in a.size(), worst case quadratic.
Two unordered containers a and b compare equal if a.size() == b.size() and, for every equivalentkey group [Ea1,Ea2) obtained from a.equal_range(Ea1), there exists an equivalent-key group [Eb1,Eb2) obtained from b.equal_range(Ea1), such that distance(Ea1, Ea2) == distance(Eb1, Eb2) and is_permutation(Ea1, Ea2, Eb1) returns true. For unordered_set and unordered_map, the complexity of operator== (i.e., the number of calls to the == operator of the value_type, to the predicate returned by key_equal(), and to the hasher returned by hash_function()) is proportional to N in the average case and to N 2 in the worst case, where N is a.size().P For unordered_multiset and unordered_multimap, the complexity of operator== is proportional to Ei2 in the average case and to N 2 in the worst case, th where N is a.size(), and Ei is the size of the i equivalent-key group in a. However, if the respective elements of each corresponding pair of equivalent-key groups Eai and Ebi are arranged in the same order (as is commonly the case, e.g., if a and b are unmodified copies of the same container), then the average-case complexity for unordered_multiset and unordered_multimap becomes proportional to N (but worst-case complexity remains O(N 2 ), e.g., for a pathologically bad hash function). The behavior of a program that uses operator== or operator!= on unordered containers is undefined unless the Hash and Pred function objects respectively have the same behavior for both containers and the equality comparison operator for Key is a refinement262 of the partition into equivalent-key groups produced by Pred. The iterator types iterator and const_iterator of an unordered associative container are of at least the forward iterator category. For unordered associative containers where the key type and value type are the same, both iterator and const_iterator are const iterators. 262) Equality comparison is a refinement of partitioning if no two objects that compare equal fall into different partitions.
§ 23.2.5
728
c ISO/IEC
14
15
1
2
3
4
The insert and emplace members shall not affect the validity of references to container elements, but may invalidate all iterators to the container. The erase members shall invalidate only iterators and references to the erased elements. The insert and emplace members shall not affect the validity of iterators if (N+n) < z * B, where N is the number of elements in the container prior to the insert operation, n is the number of elements inserted, B is the container’s bucket count, and z is the container’s maximum load factor. 23.2.5.1 Exception safety guarantees [unord.req.except] For unordered associative containers, no clear() function throws an exception. erase(k) does not throw an exception unless that exception is thrown by the container’s Hash or Pred object (if any). For unordered associative containers, if an exception is thrown by any operation other than the container’s hash function from within an insert or emplace function inserting a single element, the insertion has no effect. For unordered associative containers, no swap function throws an exception unless that exception is thrown by the swap of the container’s Hash or Pred object (if any). For unordered associative containers, if an exception is thrown from within a rehash() function other than by the container’s hash function or comparison function, the rehash() function has no effect.
23.3 23.3.1 1
2
N3376
Sequence containers In general
[sequences] [sequences.general]
The headers <array>, <deque>, , <list>, and define template classes that meet the requirements for sequence containers. The headers and <stack> define container adaptors (23.6) that also meet the requirements for sequence containers. Header <array> synopsis #include namespace std { template struct array; template bool operator==(const array& x, const array& y); template bool operator!=(const array& x, const array& y); template bool operator(const array& x, const array& y); template bool operator=(const array& x, const array& y); template void swap(array& x, array& y) noexcept(noexcept(x.swap(y))); template class tuple_size; template <size_t I, class T> class tuple_element; template struct tuple_size<array >; template <size_t I, class T, size_t N> struct tuple_element; template <size_t I, class T, size_t N> T& get(array&) noexcept; template <size_t I, class T, size_t N> T&& get(array&&) noexcept;
§ 23.3.1
729
c ISO/IEC
N3376
template <size_t I, class T, size_t N> const T& get(const array&) noexcept; }
Header <deque> synopsis #include namespace std { template class deque; template bool operator==(const deque& x, const deque& y); template bool operator(const deque& x, const deque& y); template bool operator>=(const deque& x, const deque& y); template bool operator (const forward_list& x, const forward_list& template bool operator>=(const forward_list& x, const forward_list& template bool operator synopsis #include namespace std { template class list; template bool operator==(const list& x, const list& y); template bool operator< (const list& x, const list& y);
§ 23.3.1
730
c ISO/IEC
template bool operator!=(const list& x, const list& template bool operator> (const list& x, const list& template bool operator>=(const list& x, const list& template bool operator (const vector& x,const vector& template bool operator>=(const vector& x,const vector& template bool operator defines a class template for storing fixed-size sequences of objects. An array supports random access iterators. An instance of array stores N elements of type T, so that size() == N is an invariant. The elements of an array are stored contiguously, meaning that if a is an array then it obeys the identity &a[n] == &a[0] + n for all 0 ::value
§ 23.3.2.9
733
c ISO/IEC
1
Return type: integral constant expression.
2
Value: N
N3376
tuple_element::type 3
Requires: I < N. The program is ill-formed if I is out of bounds.
4
Value: The type T. template <size_t I, class T, size_t N> T& get(array& a) noexcept;
5
Requires: I < N. The program is ill-formed if I is out of bounds.
6
Returns: A reference to the Ith element of a, where indexing is zero-based. template <size_t I, class T, size_t N> T&& get(array&& a) noexcept;
7
Effects: Equivalent to return std::move(get(a)); template <size_t I, class T, size_t N> const T& get(const array& a) noexcept;
8
Requires: I < N. The program is ill-formed if I is out of bounds.
9
Returns: A const reference to the Ith element of a, where indexing is zero-based.
23.3.3 23.3.3.1 1
2
Class template deque Class template deque overview
[deque] [deque.overview]
A deque is a sequence container that, like a vector (23.3.6), supports random access iterators. In addition, it supports constant time insert and erase operations at the beginning or the end; insert and erase in the middle take linear time. That is, a deque is especially optimized for pushing and popping elements at the beginning and end. As with vectors, storage management is handled automatically. A deque satisfies all of the requirements of a container, of a reversible container (given in tables in 23.2), of a sequence container, including the optional sequence container requirements (23.2.3), and of an allocatoraware container (Table 99). Descriptions are provided here only for operations on deque that are not described in one of these tables or for operations where there is additional semantic information. namespace std { template class deque { public: // types: typedef value_type& reference; typedef const value_type& const_reference; typedef implementation-defined iterator; // See 23.2 typedef implementation-defined const_iterator; // See 23.2 typedef implementation-defined size_type; // See 23.2 typedef implementation-defined difference_type;// See 23.2 typedef T value_type; typedef Allocator allocator_type; typedef typename allocator_traits::pointer pointer; typedef typename allocator_traits::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator;
§ 23.3.3.1
734
c ISO/IEC
N3376
// 23.3.3.2, construct/copy/destroy: explicit deque(const Allocator& = Allocator()); explicit deque(size_type n); deque(size_type n, const T& value,const Allocator& = Allocator()); template deque(InputIterator first, InputIterator last,const Allocator& = Allocator()); deque(const deque& x); deque(deque&&); deque(const deque&, const Allocator&); deque(deque&&, const Allocator&); deque(initializer_list, const Allocator& = Allocator()); ~deque(); deque& operator=(const deque& x); deque& operator=(deque&& x); deque& operator=(initializer_list); template void assign(InputIterator first, InputIterator last); void assign(size_type n, const T& t); void assign(initializer_list); allocator_type get_allocator() const noexcept; // iterators: iterator const_iterator iterator const_iterator reverse_iterator const_reverse_iterator reverse_iterator const_reverse_iterator
begin() noexcept; begin() const noexcept; end() noexcept; end() const noexcept; rbegin() noexcept; rbegin() const noexcept; rend() noexcept; rend() const noexcept;
const_iterator const_iterator const_reverse_iterator const_reverse_iterator
cbegin() const noexcept; cend() const noexcept; crbegin() const noexcept; crend() const noexcept;
// 23.3.3.3, capacity: size_type size() const noexcept; size_type max_size() const noexcept; void resize(size_type sz); void resize(size_type sz, const T& c); void shrink_to_fit(); bool empty() const noexcept; // element access: reference operator[](size_type n); const_reference operator[](size_type n) const; reference at(size_type n); const_reference at(size_type n) const; reference front(); const_reference front() const; reference back(); const_reference back() const;
§ 23.3.3.1
735
c ISO/IEC
N3376
// 23.3.3.4, modifiers: template void emplace_front(Args&&... args); template void emplace_back(Args&&... args); template iterator emplace(const_iterator position, Args&&... args); void void void void
push_front(const T& x); push_front(T&& x); push_back(const T& x); push_back(T&& x);
iterator insert(const_iterator position, const T& x); iterator insert(const_iterator position, T&& x); iterator insert(const_iterator position, size_type n, const T& x); template iterator insert (const_iterator position, InputIterator first, InputIterator last); iterator insert(const_iterator position, initializer_list); void pop_front(); void pop_back(); iterator iterator void void
erase(const_iterator position); erase(const_iterator first, const_iterator last); swap(deque&); clear() noexcept;
}; template bool operator==(const deque& template bool operator< (const deque& template bool operator!=(const deque& template bool operator> (const deque& template bool operator>=(const deque& template bool operator=(const list& template bool operatorget_allocator() != x.get_allocator().
25
Complexity: At most size() + x.size() - 1 applications of comp if (&x != this); otherwise, no applications of comp are performed. If an exception is thrown other than by a comparison there are no effects. void reverse() noexcept;
26
Effects: Reverses the order of the elements in the list. Does not affect the validity of iterators and references.
27
Complexity: Linear time. void sort(); template void sort(Compare comp);
28
Requires: operator< (for the first version) or comp (for the second version) shall define a strict weak ordering (25.4).
29
Effects: Sorts the list according to the operator< or a Compare function object. Does not affect the validity of iterators and references.
30
Remarks: Stable.
31
Complexity: Approximately N log(N ) comparisons, where N == size(). 23.3.5.6
list specialized algorithms
[list.special]
template void swap(list& x, list& y); 1
Effects: x.swap(y);
23.3.6 23.3.6.1 1
2
Class template vector Class template vector overview
[vector] [vector.overview]
A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 (const vector& template bool operator>=(const vector& template
§ 23.3.6.1
x, const vector& y); x, const vector& y); x, const vector& y); x, const vector& y); x, const vector& y);
755
c ISO/IEC
N3376
bool operator max_size().265
6
Remarks: Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity(). void shrink_to_fit();
7
Requires: T shall be MoveInsertable into *this.
8
Complexity: Linear in the size of the sequence.
9
Remarks: shrink_to_fit is a non-binding request to reduce capacity() to size(). [ Note: The request is non-binding to allow latitude for implementation-specific optimizations. — end note ] If an exception is thrown other than by the move constructor of a non-CopyInsertable T there are no effects. void swap(vector& x);
10
Effects: Exchanges the contents and capacity() of *this with that of x.
11
Complexity: Constant time. void resize(size_type sz);
12
Effects: If sz defines the class templates set and multiset.
23.4.2
Header <map> synopsis
[associative.map.syn]
#include namespace std { template > class map; template bool operator==(const map& x, const map& y); template bool operator< (const map& x, const map& y); template bool operator!=(const map& x, const map& y); template bool operator> (const map& x, const map& y); template bool operator>=(const map& x, const map& y); template bool operator class multimap; template bool operator==(const multimap& x, const multimap& y); template bool operator< (const multimap& x, const multimap& y); template bool operator!=(const multimap& x, const multimap& y); template bool operator> (const multimap& x, const multimap& y); template bool operator>=(const multimap& x, const multimap& y); template bool operator synopsis
[associative.set.syn]
#include namespace std { template class set; template bool operator==(const set& x, const set& y); template bool operator< (const set& x, const set& y); template bool operator!=(const set& x, const set& y); template bool operator> (const set& x, const set& y); template bool operator>=(const set& x, const set& y); template bool operator (const multiset& const multiset& template bool operator>=(const multiset& const multiset& template bool operator class map { public: // types: typedef Key key_type; typedef T mapped_type; typedef pair value_type; typedef Compare key_compare; typedef Allocator allocator_type; typedef value_type& reference; typedef const value_type& const_reference;
§ 23.4.4.1
763
c ISO/IEC
typedef typedef typedef typedef typedef typedef typedef typedef
N3376
implementation-defined iterator; // see 23.2 implementation-defined const_iterator; // see 23.2 implementation-defined size_type; // see 23.2 implementation-defined difference_type;// see 23.2 typename allocator_traits::pointer pointer; typename allocator_traits::const_pointer const_pointer; std::reverse_iterator reverse_iterator; std::reverse_iterator const_reverse_iterator;
class value_compare { friend class map; protected: Compare comp; value_compare(Compare c) : comp(c) {} public: typedef bool result_type; typedef value_type first_argument_type; typedef value_type second_argument_type; bool operator()(const value_type& x, const value_type& y) const { return comp(x.first, y.first); } }; // 23.4.4.2, construct/copy/destroy: explicit map(const Compare& comp = Compare(), const Allocator& = Allocator()); template map(InputIterator first, InputIterator last, const Compare& comp = Compare(), const Allocator& = Allocator()); map(const map& x); map(map&& x); explicit map(const Allocator&); map(const map&, const Allocator&); map(map&&, const Allocator&); map(initializer_list, const Compare& = Compare(), const Allocator& = Allocator()); ~map(); map& operator=(const map& x); map& operator=(map&& x); map& operator=(initializer_list); allocator_type get_allocator() const noexcept; // iterators: iterator const_iterator iterator const_iterator
begin() noexcept; begin() const noexcept; end() noexcept; end() const noexcept;
reverse_iterator const_reverse_iterator reverse_iterator const_reverse_iterator
rbegin() noexcept; rbegin() const noexcept; rend() noexcept; rend() const noexcept;
§ 23.4.4.1
764
c ISO/IEC
N3376
const_iterator const_iterator const_reverse_iterator const_reverse_iterator
cbegin() const noexcept; cend() const noexcept; crbegin() const noexcept; crend() const noexcept;
// capacity: bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // 23.4.4.3, element access: T& operator[](const key_type& x); T& operator[](key_type&& x); T& at(const key_type& x); const T& at(const key_type& x) const; // 23.4.4.4, modifiers: template pair emplace(Args&&... args); template iterator emplace_hint(const_iterator position, Args&&... args); pair insert(const value_type& x); template pair insert(P&& x); iterator insert(const_iterator position, const value_type& x); template iterator insert(const_iterator position, P&&); template void insert(InputIterator first, InputIterator last); void insert(initializer_list); iterator erase(const_iterator position); size_type erase(const key_type& x); iterator erase(const_iterator first, const_iterator last); void swap(map&); void clear() noexcept; // observers: key_compare key_comp() const; value_compare value_comp() const; // 23.4.4.5, map iterator const_iterator size_type
operations: find(const key_type& x); find(const key_type& x) const; count(const key_type& x) const;
iterator const_iterator iterator const_iterator
lower_bound(const lower_bound(const upper_bound(const upper_bound(const
key_type& key_type& key_type& key_type&
x); x) const; x); x) const;
pair equal_range(const key_type& x); pair equal_range(const key_type& x) const; };
§ 23.4.4.1
765
c ISO/IEC
N3376
template bool operator==(const map& x, const map& y); template bool operator< (const map& x, const map& y); template bool operator!=(const map& x, const map& y); template bool operator> (const map& x, const map& y); template bool operator>=(const map& x, const map& y); template bool operator class multimap { public: // types: typedef Key key_type; typedef T mapped_type; typedef pair value_type; typedef Compare key_compare; typedef Allocator allocator_type; typedef value_type& reference; typedef const value_type& const_reference; typedef implementation-defined iterator; // see 23.2 typedef implementation-defined const_iterator; // see 23.2 typedef implementation-defined size_type; // see 23.2 typedef implementation-defined difference_type;// see 23.2 typedef typename allocator_traits::pointer pointer; typedef typename allocator_traits::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; class value_compare { friend class multimap; protected: Compare comp; value_compare(Compare c) : comp(c) { } public: typedef bool result_type; typedef value_type first_argument_type; typedef value_type second_argument_type; bool operator()(const value_type& x, const value_type& y) const { return comp(x.first, y.first);
§ 23.4.5.1
768
c ISO/IEC
N3376
} }; // construct/copy/destroy: explicit multimap(const Compare& comp = Compare(), const Allocator& = Allocator()); template multimap(InputIterator first, InputIterator last, const Compare& comp = Compare(), const Allocator& = Allocator()); multimap(const multimap& x); multimap(multimap&& x); explicit multimap(const Allocator&); multimap(const multimap&, const Allocator&); multimap(multimap&&, const Allocator&); multimap(initializer_list, const Compare& = Compare(), const Allocator& = Allocator()); ~multimap(); multimap& operator=(const multimap& x); multimap& operator=(multimap&& x); multimap& operator=(initializer_list); allocator_type get_allocator() const noexcept; // iterators: iterator const_iterator iterator const_iterator
begin() noexcept; begin() const noexcept; end() noexcept; end() const noexcept;
reverse_iterator const_reverse_iterator reverse_iterator const_reverse_iterator
rbegin() noexcept; rbegin() const noexcept; rend() noexcept; rend() const noexcept;
const_iterator const_iterator const_reverse_iterator const_reverse_iterator
cbegin() const noexcept; cend() const noexcept; crbegin() const noexcept; crend() const noexcept;
// capacity: bool size_type size_type
empty() const noexcept; size() const noexcept; max_size() const noexcept;
// modifiers: template iterator emplace(Args&&... args); template iterator emplace_hint(const_iterator position, Args&&... args); iterator insert(const value_type& x); template iterator insert(P&& x); iterator insert(const_iterator position, const value_type& x); template iterator insert(const_iterator position, P&& x); template
§ 23.4.5.1
769
c ISO/IEC
N3376
void insert(InputIterator first, InputIterator last); void insert(initializer_list); iterator erase(const_iterator position); size_type erase(const key_type& x); iterator erase(const_iterator first, const_iterator last); void swap(multimap&); void clear() noexcept; // observers: key_compare value_compare
key_comp() const; value_comp() const;
// map operations: iterator find(const key_type& x); const_iterator find(const key_type& x) const; size_type count(const key_type& x) const; iterator const_iterator iterator const_iterator
lower_bound(const lower_bound(const upper_bound(const upper_bound(const
key_type& key_type& key_type& key_type&
x); x) const; x); x) const;
pair equal_range(const key_type& x); pair equal_range(const key_type& x) const; }; template bool operator==(const multimap& x, const multimap& y); template bool operator< (const multimap& x, const multimap& y); template bool operator!=(const multimap& x, const multimap& y); template bool operator> (const multimap& x, const multimap& y); template bool operator>=(const multimap& x, const multimap& y); template bool operator (const set& x, const set& y); template bool operator>=(const set& x, const set& y); template bool operator (const multiset& const multiset& template bool operator>=(const multiset& const multiset& template bool operator class unordered_map; // 23.5.5, class template unordered_multimap: template > class unordered_multimap; template void swap(unordered_map& x, unordered_map& y); template void swap(unordered_multimap& x, unordered_multimap& y); template bool operator==(const unordered_map& a, const unordered_map& b); template bool operator!=(const unordered_map& a, const unordered_map& b); template bool operator==(const unordered_multimap& a,
§ 23.5.2
778
c ISO/IEC
const unordered_multimap& b);
Header synopsis
[unord.set.syn]
#include namespace std { // 23.5.6, class template unordered_set: template class unordered_set; // 23.5.7, class template unordered_multiset: template class unordered_multiset; template void swap(unordered_set& x, unordered_set& y); template void swap(unordered_multiset& x, unordered_multiset& y); template bool operator==(const unordered_set& a, const unordered_set& b); template bool operator!=(const unordered_set& a, const unordered_set& b); template bool operator==(const unordered_multiset& const unordered_multiset& template bool operator!=(const unordered_multiset& const unordered_multiset& } // namespace std
23.5.4 23.5.4.1 1
2
Class template unordered_map Class template unordered_map overview
a, b); a, b);
[unord.map] [unord.map.overview]
An unordered_map is an unordered associative container that supports unique keys (an unordered_map contains at most one of each key value) and that associates values of another type mapped_type with the keys. The unordered_map class supports forward iterators. An unordered_map satisfies all of the requirements of a container, of an unordered associative container, and of an allocator-aware container (Table 99). It provides the operations described in the preceding requirements § 23.5.4.1
779
c ISO/IEC
3
N3376
table for unique keys; that is, an unordered_map supports the a_uniq operations in that table, not the a_eq operations. For an unordered_map the key type is Key, the mapped type is T, and the value type is std::pair. This section only describes operations on unordered_map that are not described in one of the requirement tables, or for which there is additional semantic information. namespace std { template > class unordered_map { public: // types typedef Key key_type; typedef std::pair value_type; typedef T mapped_type; typedef Hash hasher; typedef Pred key_equal; typedef Allocator allocator_type; typedef typename allocator_traits::pointer pointer; typedef typename allocator_traits::const_pointer const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef implementation-defined size_type; typedef implementation-defined difference_type; typedef typedef typedef typedef
implementation-defined implementation-defined implementation-defined implementation-defined
iterator; const_iterator; local_iterator; const_local_iterator;
// construct/destroy/copy explicit unordered_map(size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); template unordered_map(InputIterator f, InputIterator l, size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); unordered_map(const unordered_map&); unordered_map(unordered_map&&); explicit unordered_map(const Allocator&); unordered_map(const unordered_map&, const Allocator&); unordered_map(unordered_map&&, const Allocator&); unordered_map(initializer_list, size_type = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type());
§ 23.5.4.1
780
c ISO/IEC
N3376
~unordered_map(); unordered_map& operator=(const unordered_map&); unordered_map& operator=(unordered_map&&); unordered_map& operator=(initializer_list); allocator_type get_allocator() const noexcept; // size and capacity bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // iterators iterator const_iterator iterator const_iterator const_iterator const_iterator
begin() noexcept; begin() const noexcept; end() noexcept; end() const noexcept; cbegin() const noexcept; cend() const noexcept;
// modifiers template pair emplace(Args&&... args); template iterator emplace_hint(const_iterator position, Args&&... args); pair insert(const value_type& obj); template pair insert(P&& obj); iterator insert(const_iterator hint, const value_type& obj); template iterator insert(const_iterator hint, P&& obj); template void insert(InputIterator first, InputIterator last); void insert(initializer_list); iterator erase(const_iterator position); size_type erase(const key_type& k); iterator erase(const_iterator first, const_iterator last); void clear() noexcept; void swap(unordered_map&); // observers hasher hash_function() const; key_equal key_eq() const; // lookup iterator find(const key_type& k); const_iterator find(const key_type& k) const; size_type count(const key_type& k) const; std::pair equal_range(const key_type& k); std::pair equal_range(const key_type& k) const; mapped_type& operator[](const key_type& k); mapped_type& operator[](key_type&& k); mapped_type& at(const key_type& k); const mapped_type& at(const key_type& k) const; // bucket interface size_type bucket_count() const noexcept; size_type max_bucket_count() const noexcept;
§ 23.5.4.1
781
c ISO/IEC
N3376
size_type bucket_size(size_type n) const; size_type bucket(const key_type& k) const; local_iterator begin(size_type n); const_local_iterator begin(size_type n) const; local_iterator end(size_type n); const_local_iterator end(size_type n) const; const_local_iterator cbegin(size_type n) const; const_local_iterator cend(size_type n) const; // hash policy float load_factor() const noexcept; float max_load_factor() const noexcept; void max_load_factor(float z); void rehash(size_type n); void reserve(size_type n); }; template void swap(unordered_map& x, unordered_map& y); template bool operator==(const unordered_map& a, const unordered_map& b); template bool operator!=(const unordered_map& a, const unordered_map& b); }
23.5.4.2
unordered_map constructors
[unord.map.cnstr]
explicit unordered_map(size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); 1
Effects: Constructs an empty unordered_map using the specified hash function, key equality function, and allocator, and using at least n buckets. If n is not provided, the number of buckets is implementation-defined. max_load_factor() returns 1.0.
2
Complexity: Constant. template unordered_map(InputIterator f, InputIterator l, size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type());
3
Effects: Constructs an empty unordered_map using the specified hash function, key equality function, and allocator, and using at least n buckets. If n is not provided, the number of buckets is implementation-defined. Then inserts elements from the range [f, l ). max_load_factor() returns 1.0.
4
Complexity: Average case linear, worst case quadratic.
§ 23.5.4.2
782
c ISO/IEC
23.5.4.3
unordered_map element access
N3376
[unord.map.elem]
mapped_type& operator[](const key_type& k); mapped_type& operator[](key_type&& k); 1
Requires: mapped_type shall be DefaultInsertable into *this. For the first operator, key_type shall be CopyInsertable into *this. For the second operator, key_type shall be MoveConstructible.
2
Effects: If the unordered_map does not already contain an element whose key is equivalent to k , the first operator inserts the value value_type(k, mapped_type()) and the second operator inserts the value value_type(std::move(k), mapped_type()).
3
Returns: A reference to x.second, where x is the (unique) element whose key is equivalent to k .
4
Complexity: Average case O(1), worst case O(size()). mapped_type& at(const key_type& k); const mapped_type& at(const key_type& k) const;
5
Returns: A reference to x.second, where x is the (unique) element whose key is equivalent to k.
6
Throws: An exception object of type out_of_range if no such element is present. 23.5.4.4
unordered_map modifiers
[unord.map.modifiers]
template pair insert(P&& obj); 1
Requires: value_type is constructible from std::forward
(obj).
2
Effects: Inserts obj converted to value_type if and only if there is no element in the container with key equivalent to the key of value_type(obj).
3
Returns: The bool component of the returned pair object indicates whether the insertion took place and the iterator component points to the element with key equivalent to the key of value_type(obj).
4
Complexity: Average case O(1), worst case O(size()).
5
Remarks: This signature shall not participate in overload resolution unless P is implicitly convertible to value_type. template iterator insert(const_iterator hint, P&& obj);
6
Requires: value_type is constructible from std::forward
(obj).
7
Effects: Inserts obj converted to value_type if and only if there is no element in the container with key equivalent to the key of value_type(obj). The iterator hint is a hint pointing to where the search should start.
8
Returns: An iterator that points to the element with key equivalent to the key of value_type(obj).
9
Complexity: Average case O(1), worst case O(size()).
10
Remarks: This signature shall not participate in overload resolution unless P is implicitly convertible to value_type. 23.5.4.5
unordered_map swap
[unord.map.swap]
template void swap(unordered_map& x, unordered_map& y); 1
Effects: x.swap(y). § 23.5.4.5
783
c ISO/IEC
23.5.5 23.5.5.1 1
2
3
N3376
Class template unordered_multimap Class template unordered_multimap overview
[unord.multimap] [unord.multimap.overview]
An unordered_multimap is an unordered associative container that supports equivalent keys (an instance of unordered_multimap may contain multiple copies of each key value) and that associates values of another type mapped_type with the keys. The unordered_multimap class supports forward iterators. An unordered_multimap satisfies all of the requirements of a container, of an unordered associative container, and of an allocator-aware container (Table 99). It provides the operations described in the preceding requirements table for equivalent keys; that is, an unordered_multimap supports the a_eq operations in that table, not the a_uniq operations. For an unordered_multimap the key type is Key, the mapped type is T, and the value type is std::pair. This section only describes operations on unordered_multimap that are not described in one of the requirement tables, or for which there is additional semantic information. namespace std { template > class unordered_multimap { public: // types typedef Key key_type; typedef std::pair value_type; typedef T mapped_type; typedef Hash hasher; typedef Pred key_equal; typedef Allocator allocator_type; typedef typename allocator_traits::pointer pointer; typedef typename allocator_traits::const_pointer const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef implementation-defined size_type; typedef implementation-defined difference_type; typedef typedef typedef typedef
implementation-defined implementation-defined implementation-defined implementation-defined
iterator; const_iterator; local_iterator; const_local_iterator;
// construct/destroy/copy explicit unordered_multimap(size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); template unordered_multimap(InputIterator f, InputIterator l, size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); unordered_multimap(const unordered_multimap&); unordered_multimap(unordered_multimap&&);
§ 23.5.5.1
784
c ISO/IEC
N3376
explicit unordered_multimap(const Allocator&); unordered_multimap(const unordered_multimap&, const Allocator&); unordered_multimap(unordered_multimap&&, const Allocator&); unordered_multimap(initializer_list, size_type = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); ~unordered_multimap(); unordered_multimap& operator=(const unordered_multimap&); unordered_multimap& operator=(unordered_multimap&&); unordered_multimap& operator=(initializer_list); allocator_type get_allocator() const noexcept; // size and capacity bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // iterators iterator const_iterator iterator const_iterator const_iterator const_iterator
begin() noexcept; begin() const noexcept; end() noexcept; end() const noexcept; cbegin() const noexcept; cend() const noexcept;
// modifiers template iterator emplace(Args&&... args); template iterator emplace_hint(const_iterator position, Args&&... args); iterator insert(const value_type& obj); template iterator insert(P&& obj); iterator insert(const_iterator hint, const value_type& obj); template iterator insert(const_iterator hint, P&& obj); template void insert(InputIterator first, InputIterator last); void insert(initializer_list); iterator erase(const_iterator position); size_type erase(const key_type& k); iterator erase(const_iterator first, const_iterator last); void clear() noexcept; void swap(unordered_multimap&); // observers hasher hash_function() const; key_equal key_eq() const; // lookup iterator find(const key_type& k); const_iterator find(const key_type& k) const; size_type count(const key_type& k) const; std::pair equal_range(const key_type& k); std::pair equal_range(const key_type& k) const;
§ 23.5.5.1
785
c ISO/IEC
N3376
// bucket interface size_type bucket_count() const noexcept; size_type max_bucket_count() const noexcept; size_type bucket_size(size_type n) const; size_type bucket(const key_type& k) const; local_iterator begin(size_type n); const_local_iterator begin(size_type n) const; local_iterator end(size_type n); const_local_iterator end(size_type n) const; const_local_iterator cbegin(size_type n) const; const_local_iterator cend(size_type n) const; // hash policy float load_factor() const noexcept; float max_load_factor() const noexcept; void max_load_factor(float z); void rehash(size_type n); void reserve(size_type n); }; template void swap(unordered_multimap& x, unordered_multimap& y); template &
a, b); a, b);
}
23.5.5.2
unordered_multimap constructors
[unord.multimap.cnstr]
explicit unordered_multimap(size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); 1
Effects: Constructs an empty unordered_multimap using the specified hash function, key equality function, and allocator, and using at least n buckets. If n is not provided, the number of buckets is implementation-defined. max_load_factor() returns 1.0.
2
Complexity: Constant. template unordered_multimap(InputIterator f, InputIterator l, size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type());
3
Effects: Constructs an empty unordered_multimap using the specified hash function, key equality function, and allocator, and using at least n buckets. If n is not provided, the number of buckets is implementation-defined. Then inserts elements from the range [f, l ). max_load_factor() returns 1.0. § 23.5.5.2
786
c ISO/IEC
4
N3376
Complexity: Average case linear, worst case quadratic. 23.5.5.3
unordered_multimap modifiers
[unord.multimap.modifiers]
template iterator insert(P&& obj); 1
Requires: value_type is constructible from std::forward
(obj).
2
Effects: Inserts obj converted to value_type.
3
Returns: An iterator that points to the element with key equivalent to the key of value_type(obj).
4
Complexity: Average case O(1), worst case O(size()).
5
Remarks: This signature shall not participate in overload resolution unless P is implicitly convertible to value_type. template iterator insert(const_iterator hint, P&& obj);
6
Requires: value_type is constructible from std::forward
(obj).
7
Effects: Inserts obj converted to value_type. The iterator hint is a hint pointing to where the search should start.
8
Returns: An iterator that points to the element with key equivalent to the key of value_type(obj).
9
Complexity: Average case O(1), worst case O(size()).
10
Remarks: This signature shall not participate in overload resolution unless P is implicitly convertible to value_type. 23.5.5.4
unordered_multimap swap
[unord.multimap.swap]
template void swap(unordered_multimap& x, unordered_multimap& y); 1
Effects: x.swap(y).
23.5.6 23.5.6.1 1
2
3
Class template unordered_set Class template unordered_set overview
[unord.set] [unord.set.overview]
An unordered_set is an unordered associative container that supports unique keys (an unordered_set contains at most one of each key value) and in which the elements’ keys are the elements themselves. The unordered_set class supports forward iterators. An unordered_set satisfies all of the requirements of a container, of an unordered associative container, and of an allocator-aware container (Table 99). It provides the operations described in the preceding requirements table for unique keys; that is, an unordered_set supports the a_uniq operations in that table, not the a_eq operations. For an unordered_set the key type and the value type are both Key. The iterator and const_iterator types are both const iterator types. It is unspecified whether they are the same type. This section only describes operations on unordered_set that are not described in one of the requirement tables, or for which there is additional semantic information. namespace std { template
787
c ISO/IEC
N3376
class unordered_set { public: // types typedef Key typedef Key typedef Hash typedef Pred typedef Allocator typedef typename allocator_traits::pointer typedef typename allocator_traits::const_pointer typedef value_type& typedef const value_type& typedef implementation-defined typedef implementation-defined typedef typedef typedef typedef
implementation-defined implementation-defined implementation-defined implementation-defined
key_type; value_type; hasher; key_equal; allocator_type; pointer; const_pointer; reference; const_reference; size_type; difference_type; iterator; const_iterator; local_iterator; const_local_iterator;
// construct/destroy/copy explicit unordered_set(size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); template unordered_set(InputIterator f, InputIterator l, size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); unordered_set(const unordered_set&); unordered_set(unordered_set&&); explicit unordered_set(const Allocator&); unordered_set(const unordered_set&, const Allocator&); unordered_set(unordered_set&&, const Allocator&); unordered_set(initializer_list, size_type = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); ~unordered_set(); unordered_set& operator=(const unordered_set&); unordered_set& operator=(unordered_set&&); unordered_set& operator=(initializer_list); allocator_type get_allocator() const noexcept; // size and capacity bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // iterators iterator
§ 23.5.6.1
begin() noexcept;
788
c ISO/IEC
const_iterator iterator const_iterator const_iterator const_iterator
N3376
begin() const noexcept; end() noexcept; end() const noexcept; cbegin() const noexcept; cend() const noexcept;
// modifiers template pair emplace(Args&&... args); template iterator emplace_hint(const_iterator position, Args&&... args); pair insert(const value_type& obj); pair insert(value_type&& obj); iterator insert(const_iterator hint, const value_type& obj); iterator insert(const_iterator hint, value_type&& obj); template void insert(InputIterator first, InputIterator last); void insert(initializer_list); iterator erase(const_iterator position); size_type erase(const key_type& k); iterator erase(const_iterator first, const_iterator last); void clear() noexcept; void swap(unordered_set&); // observers hasher hash_function() const; key_equal key_eq() const; // lookup iterator find(const key_type& k); const_iterator find(const key_type& k) const; size_type count(const key_type& k) const; std::pair equal_range(const key_type& k); std::pair equal_range(const key_type& k) const; // bucket interface size_type bucket_count() const noexcept; size_type max_bucket_count() const noexcept; size_type bucket_size(size_type n) const; size_type bucket(const key_type& k) const; local_iterator begin(size_type n); const_local_iterator begin(size_type n) const; local_iterator end(size_type n); const_local_iterator end(size_type n) const; const_local_iterator cbegin(size_type n) const; const_local_iterator cend(size_type n) const; // hash policy float load_factor() const noexcept; float max_load_factor() const noexcept; void max_load_factor(float z); void rehash(size_type n); void reserve(size_type n); }; template
§ 23.5.6.1
789
c ISO/IEC
N3376
void swap(unordered_set& x, unordered_set& y); template bool operator==(const unordered_set& a, const unordered_set& b); template bool operator!=(const unordered_set& a, const unordered_set& b); }
23.5.6.2
unordered_set constructors
[unord.set.cnstr]
explicit unordered_set(size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); 1
Effects: Constructs an empty unordered_set using the specified hash function, key equality function, and allocator, and using at least n buckets. If n is not provided, the number of buckets is implementation-defined. max_load_factor() returns 1.0.
2
Complexity: Constant. template unordered_set(InputIterator f, InputIterator l, size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type());
3
Effects: Constructs an empty unordered_set using the specified hash function, key equality function, and allocator, and using at least n buckets. If n is not provided, the number of buckets is implementation-defined. Then inserts elements from the range [f, l ). max_load_factor() returns 1.0.
4
Complexity: Average case linear, worst case quadratic. 23.5.6.3
unordered_set swap
[unord.set.swap]
template void swap(unordered_set& x, unordered_set& y); 1
Effects: x.swap(y).
23.5.7 23.5.7.1 1
2
Class template unordered_multiset Class template unordered_multiset overview
[unord.multiset] [unord.multiset.overview]
An unordered_multiset is an unordered associative container that supports equivalent keys (an instance of unordered_multiset may contain multiple copies of the same key value) and in which each element’s key is the element itself. The unordered_multiset class supports forward iterators. An unordered_multiset satisfies all of the requirements of a container, of an unordered associative container, and of an allocator-aware container (Table 99). It provides the operations described in the preceding requirements table for equivalent keys; that is, an unordered_multiset supports the a_eq operations in that table, not the a_uniq operations. For an unordered_multiset the key type and the value type § 23.5.7.1
790
c ISO/IEC
3
N3376
are both Key. The iterator and const_iterator types are both const iterator types. It is unspecified whether they are the same type. This section only describes operations on unordered_multiset that are not described in one of the requirement tables, or for which there is additional semantic information. namespace std { template class unordered_multiset { public: // types typedef Key typedef Key typedef Hash typedef Pred typedef Allocator typedef typename allocator_traits::pointer typedef typename allocator_traits::const_pointer typedef value_type& typedef const value_type& typedef implementation-defined typedef implementation-defined typedef typedef typedef typedef
implementation-defined implementation-defined implementation-defined implementation-defined
key_type; value_type; hasher; key_equal; allocator_type; pointer; const_pointer; reference; const_reference; size_type; difference_type; iterator; const_iterator; local_iterator; const_local_iterator;
// construct/destroy/copy explicit unordered_multiset(size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); template unordered_multiset(InputIterator f, InputIterator l, size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); unordered_multiset(const unordered_multiset&); unordered_multiset(unordered_multiset&&); explicit unordered_multiset(const Allocator&); unordered_multiset(const unordered_multiset&, const Allocator&); unordered_multiset(unordered_multiset&&, const Allocator&); unordered_multiset(initializer_list, size_type = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); ~unordered_multiset(); unordered_multiset& operator=(const unordered_multiset&); unordered_multiset operator=(unordered_multiset&&);
§ 23.5.7.1
791
c ISO/IEC
N3376
unordered_multiset& operator=(initializer_list); allocator_type get_allocator() const noexcept; // size and capacity bool empty() const noexcept; size_type size() const noexcept; size_type max_size() const noexcept; // iterators iterator const_iterator iterator const_iterator const_iterator const_iterator
begin() noexcept; begin() const noexcept; end() noexcept; end() const noexcept; cbegin() const noexcept; cend() const noexcept;
// modifiers template iterator emplace(Args&&... args); template iterator emplace_hint(const_iterator position, Args&&... args); iterator insert(const value_type& obj); iterator insert(value_type&& obj); iterator insert(const_iterator hint, const value_type& obj); iterator insert(const_iterator hint, value_type&& obj); template void insert(InputIterator first, InputIterator last); void insert(initializer_list); iterator erase(const_iterator position); size_type erase(const key_type& k); iterator erase(const_iterator first, const_iterator last); void clear() noexcept; void swap(unordered_multiset&); // observers hasher hash_function() const; key_equal key_eq() const; // lookup iterator find(const key_type& k); const_iterator find(const key_type& k) const; size_type count(const key_type& k) const; std::pair equal_range(const key_type& k); std::pair equal_range(const key_type& k) const; // bucket interface size_type bucket_count() const noexcept; size_type max_bucket_count() const noexcept; size_type bucket_size(size_type n) const; size_type bucket(const key_type& k) const; local_iterator begin(size_type n); const_local_iterator begin(size_type n) const; local_iterator end(size_type n); const_local_iterator end(size_type n) const; const_local_iterator cbegin(size_type n) const; const_local_iterator cend(size_type n) const;
§ 23.5.7.1
792
c ISO/IEC
N3376
// hash policy float load_factor() const noexcept; float max_load_factor() const noexcept; void max_load_factor(float z); void rehash(size_type n); void reserve(size_type n); }; template void swap(unordered_multiset& x, unordered_multiset& y); template bool operator==(const unordered_multiset& const unordered_multiset& template bool operator!=(const unordered_multiset& const unordered_multiset&
a, b); a, b);
}
23.5.7.2
unordered_multiset constructors
[unord.multiset.cnstr]
explicit unordered_multiset(size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()); 1
Effects: Constructs an empty unordered_multiset using the specified hash function, key equality function, and allocator, and using at least n buckets. If n is not provided, the number of buckets is implementation-defined. max_load_factor() returns 1.0.
2
Complexity: Constant. template unordered_multiset(InputIterator f, InputIterator l, size_type n = see below , const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type());
3
Effects: Constructs an empty unordered_multiset using the specified hash function, key equality function, and allocator, and using at least n buckets. If n is not provided, the number of buckets is implementation-defined. Then inserts elements from the range [f, l ). max_load_factor() returns 1.0.
4
Complexity: Average case linear, worst case quadratic. 23.5.7.3
unordered_multiset swap
[unord.multiset.swap]
template void swap(unordered_multiset& x, unordered_multiset& y); 1
Effects: x.swap(y);
§ 23.5.7.3
793
c ISO/IEC
23.6
Container adaptors
23.6.1 1
2
3
N3376
[container.adaptors]
In general
[container.adaptors.general]
The headers and <stack> define the container adaptors queue, priority_queue, and stack. These container adaptors meet the requirements for sequence containers. The container adaptors each take a Container template parameter, and each constructor takes a Container reference argument. This container is copied into the Container member of each adaptor. If the container takes an allocator, then a compatible allocator may be passed in to the adaptor’s constructor. Otherwise, normal copy or move construction is used for the container argument. For container adaptors, no swap function throws an exception unless that exception is thrown by the swap of the adaptor’s Container or Compare object (if any).
23.6.2
Header synopsis
[queue.syn]
#include namespace std { template class queue; template class priority_queue; template bool operator==(const queue& template bool operator< (const queue& template bool operator!=(const queue& template bool operator> (const queue& template bool operator>=(const queue& template bool operator (const queue& template bool operator>=(const queue& template bool operator=(const queue& x, const queue& y);
6
Returns: x.c >= y.c. 23.6.3.5
queue specialized algorithms
[queue.special]
template void swap(queue& x, queue& y) noexcept(noexcept(x.swap(y))); 1
Effects: x.swap(y).
23.6.4 1
Class template priority_queue
[priority.queue]
Any sequence container with random access iterator and supporting operations front(), push_back() and pop_back() can be used to instantiate priority_queue. In particular, vector (23.3.6) and deque (23.3.3) can be used. Instantiating priority_queue also involves supplying a function or function object for making priority comparisons; the library assumes that the function or function object defines a strict weak ordering (25.4). namespace std { template class priority_queue { public: typedef typename Container::value_type value_type; typedef typename Container::reference reference; typedef typename Container::const_reference const_reference; typedef typename Container::size_type size_type; typedef Container container_type; protected: Container c; Compare comp; public: priority_queue(const Compare& x, const Container&); explicit priority_queue(const Compare& x = Compare(), Container&& = Container()); template priority_queue(InputIterator first, InputIterator last, const Compare& x, const Container&); template priority_queue(InputIterator first, InputIterator last,
§ 23.6.4
797
c ISO/IEC
N3376
const Compare& x = Compare(), Container&& = Container()); template explicit priority_queue(const Alloc&); template priority_queue(const Compare&, const Alloc&); template priority_queue(const Compare&, const Container&, const Alloc&); template priority_queue(const Compare&, Container&&, const Alloc&); template priority_queue(const priority_queue&, const Alloc&); template priority_queue(priority_queue&&, const Alloc&); bool empty() const { return c.empty(); } size_type size() const { return c.size(); } const_reference top() const { return c.front(); } void push(const value_type& x); void push(value_type&& x); template void emplace(Args&&... args); void pop(); void swap(priority_queue& q) noexcept( noexcept(swap(c, q.c)) && noexcept(swap(comp, q.comp))) { using std::swap; swap(c, q.c); swap(comp, q.comp); } }; // no equality is provided template void swap(priority_queue& x, priority_queue& y) noexcept(noexcept(x.swap(y))); template struct uses_allocator<priority_queue, Alloc> : uses_allocator::type { }; }
23.6.4.1
priority_queue constructors
[priqueue.cons]
priority_queue(const Compare& x, const Container& y); explicit priority_queue(const Compare& x = Compare(), Container&& y = Container()); 1
Requires: x shall define a strict weak ordering (25.4).
2
Effects: Initializes comp with x and c with y (copy constructing or move constructing as appropriate); calls make_heap(c.begin(), c.end(), comp). template priority_queue(InputIterator first, InputIterator last, const Compare& x, const Container& y); template priority_queue(InputIterator first, InputIterator last, const Compare& x = Compare(), Container&& y = Container());
3
Requires: x shall define a strict weak ordering (25.4).
4
Effects: Initializes comp with x and c with y (copy constructing or move constructing as appropriate); calls c.insert(c.end(), first, last); and finally calls make_heap(c.begin(), c.end(), comp). § 23.6.4.1
798
c ISO/IEC
23.6.4.2 1
priority_queue constructors with allocators
N3376
[priqueue.cons.alloc]
If uses_allocator::value is false the constructors in this subclause shall not participate in overload resolution. template explicit priority_queue(const Alloc& a);
2
Effects: Initializes c with a and value-initializes comp. template priority_queue(const Compare& compare, const Alloc& a);
3
Effects: Initializes c with a and initializes comp with compare. template priority_queue(const Compare& compare, const Container& cont, const Alloc& a);
4
Effects: Initializes c with cont as the first argument and a as the second argument, and initializes comp with compare. template priority_queue(const Compare& compare, Container&& cont, const Alloc& a);
5
Effects: Initializes c with std::move(cont) as the first argument and a as the second argument, and initializes comp with compare. template priority_queue(const priority_queue& q, const Alloc& a);
6
Effects: Initializes c with q.c as the first argument and a as the second argument, and initializes comp with q.comp. template priority_queue(priority_queue&& q, const Alloc& a);
7
Effects: Initializes c with std::move(q.c) as the first argument and a as the second argument, and initializes comp with std::move(q.comp). 23.6.4.3
priority_queue members
[priqueue.members]
void push(const value_type& x); 1
Effects: c.push_back(x); push_heap(c.begin(), c.end(), comp);
void push(value_type&& x); 2
Effects: c.push_back(std::move(x)); push_heap(c.begin(), c.end(), comp);
§ 23.6.4.3
799
c ISO/IEC
N3376
template void emplace(Args&&... args) 3
Effects: c.emplace_back(std::forward(args)...); push_heap(c.begin(), c.end(), comp);
void pop(); 4
Effects: pop_heap(c.begin(), c.end(), comp); c.pop_back();
23.6.4.4
priority_queue specialized algorithms
[priqueue.special]
template void swap(priority_queue& x, priority_queue& y) noexcept(noexcept(x.swap(y))); 1
Effects: x.swap(y).
23.6.5 1
Class template stack
[stack]
Any sequence container supporting operations back(), push_back() and pop_back() can be used to instantiate stack. In particular, vector (23.3.6), list (23.3.5) and deque (23.3.3) can be used. 23.6.5.1 Header <stack> synopsis [stack.syn] #include namespace std { template class stack; template bool operator==(const stack& x,const stack& y); template bool operator< (const stack& x,const stack& y); template bool operator!=(const stack& x,const stack& y); template bool operator> (const stack& x,const stack& y); template bool operator>=(const stack& x,const stack& y); template bool operator& y);
template struct uses_allocator<stack, Alloc> : uses_allocator::type { }; }
23.6.5.3
stack constructors
[stack.cons]
explicit stack(const Container& cont); 1
Effects: Initializes c with cont. explicit stack(Container&& const = Container());
§ 23.6.5.3
801
c ISO/IEC
2
Effects: Initializes c with std::move(cont). 23.6.5.4
1
N3376
stack constructors with allocators
[stack.cons.alloc]
If uses_allocator::value is false the constructors in this subclause shall not participate in overload resolution. template explicit stack(const Alloc& a);
2
Effects: Initializes c with a. template stack(const container_type& cont, const Alloc& a);
3
Effects: Initializes c with cont as the first argument and a as the second argument. template stack(container_type&& cont, const Alloc& a);
4
Effects: Initializes c with std::move(cont) as the first argument and a as the second argument. template stack(const stack& s, const Alloc& a);
5
Effects: Initializes c with s.c as the first argument and a as the second argument. template stack(stack&& s, const Alloc& a);
6
Effects: Initializes c with std::move(s.c) as the first argument and a as the second argument. 23.6.5.5
stack operators
[stack.ops]
template bool operator==(const stack& x, const stack& y); 1
Returns: x.c == y.c. template bool operator!=(const stack& x, const stack& y);
2
Returns: x.c != y.c. template bool operator< (const stack& x, const stack& y);
3
Returns: x.c < y.c.
§ 23.6.5.5
802
c ISO/IEC
N3376
template bool operator y.c. template bool operator>=(const stack& x, const stack& y);
6
Returns: x.c >= y.c. 23.6.5.6
stack specialized algorithms
[stack.special]
template void swap(stack& x, stack& y) noexcept(noexcept(x.swap(y))); 1
Effects: x.swap(y).
§ 23.6.5.6
803
c ISO/IEC
24 24.1 1
2
N3376
Iterators library
[iterators]
General
[iterators.general]
This Clause describes components that C++ programs may use to perform iterations over containers (Clause 23), streams (27.7), and stream buffers (27.6). The following subclauses describe iterator requirements, and components for iterator primitives, predefined iterators, and stream iterators, as summarized in Table 104. Table 104 — Iterators library summary
24.2 24.4 24.5 24.6
24.2 24.2.1 1
2
Subclause Requirements Iterator primitives Predefined iterators Stream iterators
Header(s)
Iterator requirements
[iterator.requirements]
In general
[iterator.requirements.general]
Iterators are a generalization of pointers that allow a C++ program to work with different data structures (containers) in a uniform manner. To be able to construct template algorithms that work correctly and efficiently on different types of data structures, the library formalizes not just the interfaces but also the semantics and complexity assumptions of iterators. All input iterators i support the expression *i, resulting in a value of some object type T, called the value type of the iterator. All output iterators support the expression *i = o where o is a value of some type that is in the set of types that are writable to the particular iterator type of i. All iterators i for which the expression (*i).m is well-defined, support the expression i->m with the same semantics as (*i).m. For every iterator type X for which equality is defined, there is a corresponding signed integer type called the difference type of the iterator. Since iterators are an abstraction of pointers, their semantics is a generalization of most of the semantics of pointers in C++. This ensures that every function template that takes iterators works as well with regular pointers. This International Standard defines five categories of iterators, according to the operations defined on them: input iterators, output iterators, forward iterators, bidirectional iterators and random access iterators, as shown in Table 105. Table 105 — Relations among iterator categories Random Access
3
4
→ Bidirectional
→ Forward
→ Input → Output
Forward iterators satisfy all the requirements of input iterators and can be used whenever an input iterator is specified; Bidirectional iterators also satisfy all the requirements of forward iterators and can be used whenever a forward iterator is specified; Random access iterators also satisfy all the requirements of bidirectional iterators and can be used whenever a bidirectional iterator is specified. Iterators that further satisfy the requirements of output iterators are called mutable iterators. Nonmutable iterators are referred to as constant iterators. § 24.2.1
804
c ISO/IEC
5
6
7
8
9 10 11
Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding sequence. These values are called past-the-end values. Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable. Iterators can also have singular values that are not associated with any sequence. [ Example: After the declaration of an uninitialized pointer x (as with int* x;), x must always be assumed to have a singular value of a pointer. — end example ] Results of most expressions are undefined for singular values; the only exceptions are destroying an iterator that holds a singular value, the assignment of a non-singular value to an iterator that holds a singular value, and, for iterators that satisfy the DefaultConstructible requirements, using a value-initialized iterator as the source of a copy or move operation. [ Note: This guarantee is not offered for default initialization, although the distinction only matters for types with trivial default constructors such as pointers or aggregates holding pointers. — end note ] In these cases the singular value is overwritten the same way as any other value. Dereferenceable values are always non-singular. An iterator j is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == j. If j is reachable from i, they refer to elements of the same sequence. Most of the library’s algorithmic templates that operate on data structures have interfaces that use ranges. A range is a pair of iterators that designate the beginning and end of the computation. A range [i,i) is an empty range; in general, a range [i,j) refers to the elements in the data structure starting with the element pointed to by i and up to but not including the element pointed to by j. Range [i,j) is valid if and only if j is reachable from i. The result of the application of functions in the library to invalid ranges is undefined. All the categories of iterators require only those functions that are realizable for a given category in constant time (amortized). Therefore, requirement tables for the iterators do not have a complexity column. Destruction of an iterator may invalidate pointers and references previously obtained from that iterator. An invalid iterator is an iterator that may be singular.266 In the following sections, a and b denote values of type X or const X, difference_type and reference refer to the types iterator_traits<X>::difference_type and iterator_traits<X>::reference, respectively, n denotes a value of difference_type, u, tmp, and m denote identifiers, r denotes a value of X&, t denotes a value of value type T, o denotes a value of some type that is writable to the output iterator. [ Note: For an iterator type X there must be an instantiation of iterator_traits<X> (24.4.1). — end note ]
24.2.2 1
2
N3376
Iterator
[iterator.iterators]
The Iterator requirements form the basis of the iterator concept taxonomy; every iterator satisfies the Iterator requirements. This set of requirements specifies operations for dereferencing and incrementing an iterator. Most algorithms will require additional operations to read (24.2.3) or write (24.2.4) values, or to provide a richer set of iterator movements (24.2.5, 24.2.6, 24.2.7).) A type X satisfies the Iterator requirements if: — X satisfies the CopyConstructible, CopyAssignable, and Destructible requirements (17.6.3.1) and lvalues of type X are swappable (17.6.3.2), and — the expressions in Table 106 are valid and have the indicated semantics. Table 106 — Iterator requirements Expression *r ++r
Return type reference X&
Operational semantics
Assertion/note pre-/post-condition pre: r is dereferenceable.
266) This definition applies to pointers, since pointers are iterators. The effect of dereferencing an iterator that has been invalidated is undefined.
§ 24.2.2
805
c ISO/IEC
24.2.3 1
2
N3376
Input iterators
[input.iterators]
A class or pointer type X satisfies the requirements of an input iterator for the value type T if X satisfies the Iterator (24.2.2) and EqualityComparable (Table 17) requirements and the expressions in Table 107 are valid and have the indicated semantics. In Table 107, the term the domain of == is used in the ordinary mathematical sense to denote the set of values over which == is (required to be) defined. This set can change over time. Each algorithm places additional requirements on the domain of == for the iterator values it uses. These requirements can be inferred from the uses that algorithm makes of == and !=. [ Example: the call find(a,b,x) is defined only if the value of a has the property p defined as follows: b has property p and a value i has property p if (*i==x) or if (*i!=x and ++i has property p). — end example ] Table 107 — Input iterator requirements (in addition to Iterator) Expression
*a
contextually convertible to bool convertible to T
a->m ++r
X&
(void)r++ *r++
convertible to T
a != b
3
Operational semantics !(a == b)
(*a).m
Assertion/note pre-/post-condition pre: (a, b) is in the domain of ==. pre: a is dereferenceable. The expression (void)*a, *a is equivalent to *a. If a == b and (a,b) is in the domain of == then *a is equivalent to *b. pre: a is dereferenceable. pre: r is dereferenceable. post: r is dereferenceable or r is past-the-end. post: any copies of the previous value of r are no longer required either to be dereferenceable or to be in the domain of ==. equivalent to (void)++r
{ T tmp = *r; ++r; return tmp; }
[ Note: For input iterators, a == b does not imply ++a == ++b. (Equality does not guarantee the substitution property or referential transparency.) Algorithms on input iterators should never attempt to pass through the same iterator twice. They should be single pass algorithms. Value type T is not required to be a CopyAssignable type (Table 23). These algorithms can be used with istreams as the source of the input data through the istream_iterator class template. — end note ]
24.2.4 1
Return type
Output iterators
[output.iterators]
A class or pointer type X satisfies the requirements of an output iterator if X satisfies the Iterator requirements (24.2.2) and the expressions in Table 108 are valid and have the indicated semantics.
§ 24.2.4
806
c ISO/IEC
N3376
Table 108 — Output iterator requirements (in addition to Iterator) Expression
2
*r = o
result is not used
++r
X&
r++
convertible to const X&
*r++ = o
result is not used
Operational semantics
{ X tmp = r; ++r; return tmp; }
Assertion/note pre-/post-condition Remark: After this operation r is not required to be dereferenceable. post: r is incrementable. &r == &++r. Remark: After this operation r is not required to be dereferenceable. post: r is incrementable. Remark: After this operation r is not required to be dereferenceable. post: r is incrementable. Remark: After this operation r is not required to be dereferenceable. post: r is incrementable.
[ Note: The only valid use of an operator* is on the left side of the assignment statement. Assignment through the same value of the iterator happens only once. Algorithms on output iterators should never attempt to pass through the same iterator twice. They should be single pass algorithms. Equality and inequality might not be defined. Algorithms that take output iterators can be used with ostreams as the destination for placing data through the ostream_iterator class as well as with insert iterators and insert pointers. — end note ]
24.2.5 1
Return type
Forward iterators
[forward.iterators]
A class or pointer type X satisfies the requirements of a forward iterator if — X satisfies the requirements of an input iterator (24.2.3), — X satisfies the DefaultConstructible requirements (17.6.3.1), — if X is a mutable iterator, reference is a reference to T; if X is a const iterator, reference is a reference to const T, — the expressions in Table 109 are valid and have the indicated semantics, and — objects of type X offer the multi-pass guarantee, described below.
2 3
The domain of == for forward iterators is that of iterators over the same underlying sequence. Two dereferenceable iterators a and b of type X offer the multi-pass guarantee if: — a == b implies ++a == ++b and — X is a pointer type or the expression (void)++X(a), *a is equivalent to the expression *a.
4
[ Note: The requirement that a == b implies ++a == ++b (which is not true for input and output iterators) and the removal of the restrictions on the number of the assignments through a mutable iterator (which applies to output iterators) allows the use of multi-pass one-directional algorithms with forward iterators. — end note ]
§ 24.2.5
807
c ISO/IEC
N3376
Table 109 — Forward iterator requirements (in addition to input iterator) Expression
5 6
r++
convertible to const X&
*r++
reference
Operational semantics { X tmp = r; ++r; return tmp; }
Assertion/note pre-/post-condition
If a and b are equal, then either a and b are both dereferenceable or else neither is dereferenceable. If a and b are both dereferenceable, then a == b if and only if *a and *b are bound to the same object.
24.2.6 1
Return type
Bidirectional iterators
[bidirectional.iterators]
A class or pointer type X satisfies the requirements of a bidirectional iterator if, in addition to satisfying the requirements for forward iterators, the following expressions are valid as shown in Table 110. Table 110 — Bidirectional iterator requirements (in addition to forward iterator) Expression
2
--r
X&
r--
convertible to const X&
*r--
reference
Operational semantics
Assertion/note pre-/post-condition pre: there exists s such that r == ++s. post: r is dereferenceable. --(++r) == r. --r == --s implies r == s. &r == &--r.
{ X tmp = r; --r; return tmp; }
[ Note: Bidirectional iterators allow algorithms to move iterators backward as well as forward. — end note ]
24.2.7 1
Return type
Random access iterators
[random.access.iterators]
A class or pointer type X satisfies the requirements of a random access iterator if, in addition to satisfying the requirements for bidirectional iterators, the following expressions are valid as shown in Table 111.
§ 24.2.7
808
c ISO/IEC
N3376
Table 111 — Random access iterator requirements (in addition to bidirectional iterator) Expression
Return type
r += n
X&
a n r a
X
+ n + a -= n - n
X& X
b - a
difference_type
a[n]
convertible to reference contextually convertible to bool contextually convertible to bool contextually convertible to bool contextually convertible to bool.
a < b
a > b
a >= b
a = 0) while (m--) ++r; else while (m++) --r; return r; } { X tmp = a; return tmp += n; } return r += -n; { X tmp = a; return tmp -= n; } return n
Assertion/note pre-/post-condition
a + n == n + a.
pre: there exists a value n of type difference_type such that a + n == b. b == a + (b - a).
*(a + n) b - a > 0
< is a total ordering relation
b < a
> is a total ordering relation opposite to b)
Header synopsis
[iterator.synopsis]
namespace std { // 24.4, primitives: template struct iterator_traits; template struct iterator_traits; template struct iterator; struct struct struct struct
§ 24.3
input_iterator_tag { }; output_iterator_tag { }; forward_iterator_tag: public input_iterator_tag { }; bidirectional_iterator_tag: public forward_iterator_tag { };
809
c ISO/IEC
N3376
struct random_access_iterator_tag: public bidirectional_iterator_tag { }; // 24.4.4, iterator operations: template void advance(InputIterator& i, Distance n); template typename iterator_traits::difference_type distance(InputIterator first, InputIterator last); template ForwardIterator next(ForwardIterator x, typename std::iterator_traits::difference_type n = 1); template BidirectionalIterator prev(BidirectionalIterator x, typename std::iterator_traits::difference_type n = 1); // 24.5, predefined iterators: template class reverse_iterator; template bool operator==( const reverse_iterator& x, const reverse_iterator& y); template bool operator( const reverse_iterator& x, const reverse_iterator& y); template bool operator>=( const reverse_iterator& x, const reverse_iterator& y); template bool operatordecltype(y.base() - x.base()); template reverse_iterator operator+( typename reverse_iterator::difference_type n, const reverse_iterator& x); template class back_insert_iterator; template
§ 24.3
810
c ISO/IEC
N3376
back_insert_iterator back_inserter(Container& x); template class front_insert_iterator; template front_insert_iterator front_inserter(Container& x); template class insert_iterator; template insert_iterator inserter(Container& x, typename Container::iterator i); template class move_iterator; template bool operator==( const move_iterator& x, const move_iterator& template bool operator!=( const move_iterator& x, const move_iterator& template bool operator=( const move_iterator& x, const move_iterator&
y);
y);
y);
y);
y);
y);
template auto operator-( const move_iterator& x, const move_iterator& y) -> decltype(x.base() - y.base()); template move_iterator operator+( typename move_iterator::difference_type n, const move_iterator& x); template move_iterator make_move_iterator(Iterator i); // 24.6, stream iterators: template class istream_iterator; template bool operator==(const istream_iterator& x, const istream_iterator& y); template bool operator!=(const istream_iterator& x, const istream_iterator& y); template class ostream_iterator; template
§ 24.3
811
c ISO/IEC
N3376
class istreambuf_iterator; template bool operator==(const istreambuf_iterator& a, const istreambuf_iterator& b); template bool operator!=(const istreambuf_iterator& a, const istreambuf_iterator& b); template class ostreambuf_iterator; // 24.7, range access: template auto begin(C& c) -> decltype(c.begin()); template auto begin(const C& c) -> decltype(c.begin()); template auto end(C& c) -> decltype(c.end()); template auto end(const C& c) -> decltype(c.end()); template T* begin(T (&array)[N]); template T* end(T (&array)[N]); }
24.4 1
[iterator.primitives]
To simplify the task of defining iterators, the library provides several classes and functions:
24.4.1 1
Iterator primitives Iterator traits
[iterator.traits]
To implement algorithms only in terms of iterators, it is often necessary to determine the value and difference types that correspond to a particular iterator type. Accordingly, it is required that if Iterator is the type of an iterator, the types iterator_traits::difference_type iterator_traits::value_type iterator_traits::iterator_category
be defined as the iterator’s difference type, value type and iterator category, respectively. In addition, the types iterator_traits::reference iterator_traits::pointer
shall be defined as the iterator’s reference and pointer types, that is, for an iterator object a, the same type as the type of *a and a->, respectively. In the case of an output iterator, the types iterator_traits::difference_type iterator_traits::value_type iterator_traits::reference iterator_traits::pointer 2
may be defined as void. The template iterator_traits is defined as namespace std { template struct iterator_traits { typedef typename Iterator::difference_type difference_type; typedef typename Iterator::value_type value_type; typedef typename Iterator::pointer pointer; typedef typename Iterator::reference reference; typedef typename Iterator::iterator_category iterator_category; }; }
§ 24.4.1
812
c ISO/IEC
3
N3376
It is specialized for pointers as namespace std { template struct iterator_traits { typedef ptrdiff_t difference_type; typedef T value_type; typedef T* pointer; typedef T& reference; typedef random_access_iterator_tag iterator_category; }; }
and for pointers to const as namespace std { template struct iterator_traits { typedef ptrdiff_t difference_type; typedef T value_type; typedef const T* pointer; typedef const T& reference; typedef random_access_iterator_tag iterator_category; }; } 4
[ Note: If there is an additional pointer type _ _ far such that the difference of two _ _ far is of type long, an implementation may define template struct iterator_traits { typedef long difference_type; typedef T value_type; typedef T _ _ far* pointer; typedef T _ _ far& reference; typedef random_access_iterator_tag iterator_category; };
5
— end note ] [ Example: To implement a generic reverse function, a C++ program can do the following: template void reverse(BidirectionalIterator first, BidirectionalIterator last) { typename iterator_traits::difference_type n = distance(first, last); --n; while(n > 0) { typename iterator_traits::value_type tmp = *first; *first++ = *--last; *last = tmp; n -= 2; } }
— end example ]
24.4.2 1
Basic iterator
[iterator.basic]
The iterator template may be used as a base class to ease the definition of required types for new iterators. namespace std { template struct iterator { typedef T value_type; typedef Distance difference_type; typedef Pointer pointer; typedef Reference reference; typedef Category iterator_category; }; }
24.4.3 1
Standard iterator tags
[std.iterator.tags]
It is often desirable for a function template specialization to find out what is the most specific category of its iterator argument, so that the function can select the most efficient algorithm at compile time. To facilitate this, the library introduces category tag classes which are used as compile time tags for algorithm selection. They are: input_iterator_tag, output_iterator_tag, forward_iterator_tag, bidirectional_iterator_tag and random_access_iterator_tag. For every iterator of type Iterator, iterator_traits::iterator_category shall be defined to be the most specific category tag that describes the iterator’s behavior. namespace std { struct input_iterator_tag { }; struct output_iterator_tag { }; struct forward_iterator_tag: public input_iterator_tag { }; struct bidirectional_iterator_tag: public forward_iterator_tag { }; struct random_access_iterator_tag: public bidirectional_iterator_tag { }; }
2
[ Example: For a program-defined iterator BinaryTreeIterator, it could be included into the bidirectional iterator category by specializing the iterator_traits template: template struct iterator_traits { typedef std::ptrdiff_t difference_type; typedef T value_type; typedef T* pointer; typedef T& reference; typedef bidirectional_iterator_tag iterator_category; };
3
Typically, however, it would be easier to derive BinaryTreeIterator from iterator. — end example ] [ Example: If evolve() is well defined for bidirectional iterators, but can be implemented more efficiently for random access iterators, then the implementation is as follows: template inline void evolve(BidirectionalIterator first, BidirectionalIterator last) { evolve(first, last, typename iterator_traits::iterator_category()); } template void evolve(BidirectionalIterator first, BidirectionalIterator last, bidirectional_iterator_tag) { // more generic, but less efficient algorithm }
§ 24.4.3
814
c ISO/IEC
N3376
template void evolve(RandomAccessIterator first, RandomAccessIterator last, random_access_iterator_tag) { // more efficient, but less generic algorithm } 4
— end example ] [ Example: If a C++ program wants to define a bidirectional iterator for some data structure containing double and such that it works on a large memory model of the implementation, it can do so with: class MyIterator : public iterator { // code implementing ++, etc. };
5
Then there is no need to specialize the iterator_traits template. — end example ]
24.4.4 1
Iterator operations
[iterator.operations]
Since only random access iterators provide + and - operators, the library provides two function templates advance and distance. These function templates use + and - for random access iterators (and are, therefore, constant time for them); for input, forward and bidirectional iterators they use ++ to provide linear time implementations. template void advance(InputIterator& i, Distance n);
2
Requires: n shall be negative only for bidirectional and random access iterators.
3
Effects: Increments (or decrements for negative n) iterator reference i by n. template typename iterator_traits::difference_type distance(InputIterator first, InputIterator last);
4
Effects: If InputIterator meets the requirements of random access iterator, returns (last - first); otherwise, returns the number of increments needed to get from first to last.
5
Requires: If InputIterator meets the requirements of random access iterator, last shall be reachable from first or first shall be reachable from last; otherwise, last shall be reachable from first. template ForwardIterator next(ForwardIterator x, typename std::iterator_traits::difference_type n = 1);
6
Effects: Equivalent to advance(x, n); return x; template BidirectionalIterator prev(BidirectionalIterator x, typename std::iterator_traits::difference_type n = 1);
7
Effects: Equivalent to advance(x, -n); return x;
§ 24.4.4
815
c ISO/IEC
24.5
Iterator adaptors
24.5.1 1
N3376
Reverse iterators
[predef.iterators] [reverse.iterators]
Class template reverse_iterator is an iterator adaptor that iterates from the end of the sequence defined by its underlying iterator to the beginning of that sequence. The fundamental relation between a reverse iterator and its corresponding iterator i is established by the identity: &*(reverse_iterator(i)) == &*(i - 1). 24.5.1.1 Class template reverse_iterator [reverse.iterator] namespace std { template class reverse_iterator : public iterator { public: typedef Iterator iterator_type; typedef typename iterator_traits::difference_type difference_type; typedef typename iterator_traits::reference reference; typedef typename iterator_traits::pointer pointer; reverse_iterator(); explicit reverse_iterator(Iterator x); template reverse_iterator(const reverse_iterator& u); template reverse_iterator& operator=(const reverse_iterator& u); Iterator base() const; // explicit reference operator*() const; pointer operator->() const; reverse_iterator& reverse_iterator reverse_iterator& reverse_iterator
operator++(); operator++(int); operator--(); operator--(int);
reverse_iterator operator+ (difference_type n) const; reverse_iterator& operator+=(difference_type n); reverse_iterator operator- (difference_type n) const; reverse_iterator& operator-=(difference_type n); unspecified operator[](difference_type n) const; protected: Iterator current; private: Iterator deref_tmp; // exposition only }; template bool operator==( const reverse_iterator& x, const reverse_iterator& y); template bool operator( const reverse_iterator& x, const reverse_iterator& y); template bool operator>=( const reverse_iterator& x, const reverse_iterator& y); template bool operator decltype(y.current - x.current); template reverse_iterator operator+( typename reverse_iterator::difference_type n, const reverse_iterator& x); }
24.5.1.2 1 2
reverse_iterator requirements
[reverse.iter.requirements]
The template parameter Iterator shall meet all the requirements of a Bidirectional Iterator (24.2.6). Additionally, Iterator shall meet the requirements of a Random Access Iterator (24.2.7) if any of the members operator+ (24.5.1.3.8), operator- (24.5.1.3.10), operator+= (24.5.1.3.9), operator-= (24.5.1.3.11), operator [] (24.5.1.3.12), or the global operators operator< (24.5.1.3.14), operator> (24.5.1.3.16), operator = (24.5.1.3.17), operator- (24.5.1.3.19) or operator+ (24.5.1.3.20) are referenced in a way that requires instantiation (14.7.1). 24.5.1.3 reverse_iterator operations [reverse.iter.ops] 24.5.1.3.1
reverse_iterator constructor
[reverse.iter.cons]
reverse_iterator(); 1
Effects: Value initializes current. Iterator operations applied to the resulting iterator have defined behavior if and only if the corresponding operations are defined on a value-initialized iterator of type Iterator. explicit reverse_iterator(Iterator x);
2
Effects: Initializes current with x. template reverse_iterator(const reverse_iterator &u);
3
Effects: Initializes current with u.current.
§ 24.5.1.3.1
817
c ISO/IEC
24.5.1.3.2
N3376
reverse_iterator::operator=
[reverse.iter.op=]
template reverse_iterator& operator=(const reverse_iterator& u); 1
Effects: Assigns u.base() to current.
2
Returns: *this. 24.5.1.3.3
Conversion
Iterator base() const; 1
[reverse.iter.conv] // explicit
Returns: current. 24.5.1.3.4
operator*
[reverse.iter.op.star]
reference operator*() const; 1
Effects: deref_tmp = current; --deref_tmp; return *deref_tmp;
2
[ Note: This operation must use an auxiliary member variable rather than a temporary variable to avoid returning a reference that persists beyond the lifetime of its associated iterator. (See 24.2.) — end note ] 24.5.1.3.5
operator->
[reverse.iter.opref]
pointer operator->() const; 1
Returns: &(operator*()). 24.5.1.3.6
operator++
[reverse.iter.op++]
reverse_iterator& operator++(); 1
Effects: --current;
2
Returns: *this. reverse_iterator operator++(int);
3
Effects: reverse_iterator tmp = *this; --current; return tmp;
24.5.1.3.7
operator--
[reverse.iter.op--]
reverse_iterator& operator--(); 1
Effects: ++current
2
Returns: *this. reverse_iterator operator--(int);
§ 24.5.1.3.7
818
c ISO/IEC
3
N3376
Effects: reverse_iterator tmp = *this; ++current; return tmp;
24.5.1.3.8
operator+
[reverse.iter.op+]
reverse_iterator operator+(typename reverse_iterator::difference_type n) const; 1
Returns: reverse_iterator(current-n). 24.5.1.3.9
operator+=
[reverse.iter.op+=]
reverse_iterator& operator+=(typename reverse_iterator::difference_type n); 1
Effects: current -= n;
2
Returns: *this. 24.5.1.3.10
operator-
[reverse.iter.op-]
reverse_iterator operator-(typename reverse_iterator::difference_type n) const; 1
Returns: reverse_iterator(current+n). 24.5.1.3.11
operator-=
[reverse.iter.op-=]
reverse_iterator& operator-=(typename reverse_iterator::difference_type n); 1
Effects: current += n;
2
Returns: *this. 24.5.1.3.12
operator[]
[reverse.iter.opindex]
unspecified operator[]( typename reverse_iterator::difference_type n) const; 1
Returns: current[-n-1]. 24.5.1.3.13
operator==
[reverse.iter.op==]
template bool operator==( const reverse_iterator& x, const reverse_iterator& y); 1
Returns: x.current == y.current. 24.5.1.3.14
operator
]
template bool operator>( const reverse_iterator& x, const reverse_iterator& y); 1
Returns: x.current < y.current. 24.5.1.3.17
operator>=
[reverse.iter.op>=]
template bool operator>=( const reverse_iterator& x, const reverse_iterator& y); 1
Returns: x.current push_back(std::move(value));
4
Returns: *this. 24.5.2.2.3
back_insert_iterator::operator*
[back.insert.iter.op*]
back_insert_iterator& operator*(); 1
Returns: *this. 24.5.2.2.4
back_insert_iterator::operator++
[back.insert.iter.op++]
back_insert_iterator& operator++(); back_insert_iterator operator++(int); 1
Returns: *this. 24.5.2.2.5
back_inserter
[back.inserter]
template back_insert_iterator back_inserter(Container& x); 1
Returns: back_insert_iterator(x). 24.5.2.3
Class template front_insert_iterator
[front.insert.iterator]
namespace std { template class front_insert_iterator : public iterator { protected: Container* container; public: typedef Container container_type; explicit front_insert_iterator(Container& x); front_insert_iterator& operator=(const typename Container::value_type& value); front_insert_iterator& operator=(typename Container::value_type&& value); front_insert_iterator& operator*(); front_insert_iterator& operator++(); front_insert_iterator operator++(int); }; template front_insert_iterator front_inserter(Container& x); }
24.5.2.4 24.5.2.4.1
front_insert_iterator operations front_insert_iterator constructor
[front.insert.iter.ops] [front.insert.iter.cons]
explicit front_insert_iterator(Container& x); 1
Effects: Initializes container with &x.
§ 24.5.2.4.1
822
c ISO/IEC
24.5.2.4.2
N3376
front_insert_iterator::operator=
[front.insert.iter.op=]
front_insert_iterator& operator=(const typename Container::value_type& value); 1
Effects: container->push_front(value);
2
Returns: *this. front_insert_iterator& operator=(typename Container::value_type&& value);
3
Effects: container->push_front(std::move(value));
4
Returns: *this. 24.5.2.4.3
front_insert_iterator::operator*
[front.insert.iter.op*]
front_insert_iterator& operator*(); 1
Returns: *this. 24.5.2.4.4
front_insert_iterator::operator++
[front.insert.iter.op++]
front_insert_iterator& operator++(); front_insert_iterator operator++(int); 1
Returns: *this. 24.5.2.4.5
front_inserter
[front.inserter]
template front_insert_iterator front_inserter(Container& x); 1
Returns: front_insert_iterator(x). 24.5.2.5
Class template insert_iterator
[insert.iterator]
namespace std { template class insert_iterator : public iterator { protected: Container* container; typename Container::iterator iter; public: typedef Container container_type; insert_iterator(Container& x, typename Container::iterator i); insert_iterator& operator=(const typename Container::value_type& value); insert_iterator& operator=(typename Container::value_type&& value); insert_iterator& operator*(); insert_iterator& operator++(); insert_iterator& operator++(int); };
§ 24.5.2.5
823
c ISO/IEC
N3376
template insert_iterator inserter(Container& x, typename Container::iterator i); }
24.5.2.6
insert_iterator operations
24.5.2.6.1
insert_iterator constructor
[insert.iter.ops] [insert.iter.cons]
insert_iterator(Container& x, typename Container::iterator i); 1
Effects: Initializes container with &x and iter with i. 24.5.2.6.2
insert_iterator::operator=
[insert.iter.op=]
insert_iterator& operator=(const typename Container::value_type& value); 1
Effects: iter = container->insert(iter, value); ++iter;
2
Returns: *this. insert_iterator& operator=(typename Container::value_type&& value);
3
Effects: iter = container->insert(iter, std::move(value)); ++iter;
4
Returns: *this. 24.5.2.6.3
insert_iterator::operator*
[insert.iter.op*]
insert_iterator& operator*(); 1
Returns: *this. 24.5.2.6.4
insert_iterator::operator++
[insert.iter.op++]
insert_iterator& operator++(); insert_iterator& operator++(int); 1
Returns: *this. 24.5.2.6.5
[inserter]
inserter
template insert_iterator inserter(Container& x, typename Container::iterator i); 1
Returns: insert_iterator(x, i).
24.5.3 1
2
Move iterators
[move.iterators]
Class template move_iterator is an iterator adaptor with the same behavior as the underlying iterator except that its dereference operator implicitly converts the value returned by the underlying iterator’s dereference operator to an rvalue reference. Some generic algorithms can be called with move iterators to replace copying with moving. [ Example: § 24.5.3
824
c ISO/IEC
N3376
list<string> s; // populate the list s vector<string> v1(s.begin(), s.end()); // copies strings into v1 vector<string> v2(make_move_iterator(s.begin()), make_move_iterator(s.end())); // moves strings into v2
— end example ] 24.5.3.1 Class template move_iterator
[move.iterator]
namespace std { template class move_iterator { public: typedef Iterator typedef typename iterator_traits::difference_type typedef Iterator typedef typename iterator_traits::value_type typedef typename iterator_traits::iterator_category typedef value_type&&
iterator_type; difference_type; pointer; value_type; iterator_category; reference;
move_iterator(); explicit move_iterator(Iterator i); template move_iterator(const move_iterator& u); template move_iterator& operator=(const move_iterator& u); iterator_type base() const; reference operator*() const; pointer operator->() const; move_iterator& operator++(); move_iterator operator++(int); move_iterator& operator--(); move_iterator operator--(int); move_iterator operator+(difference_type n) const; move_iterator& operator+=(difference_type n); move_iterator operator-(difference_type n) const; move_iterator& operator-=(difference_type n); unspecified operator[](difference_type n) const; private: Iterator current; };
// exposition only
template bool operator==( const move_iterator& x, const template bool operator!=( const move_iterator& x, const template bool operator=( const move_iterator& x, const move_iterator& y); template auto operator-( const move_iterator& x, const move_iterator& y) -> decltype(x.base() - y.base()); template move_iterator operator+( typename move_iterator::difference_type n, const move_iterator& x); template move_iterator make_move_iterator(Iterator i); }
24.5.3.2 1
move_iterator requirements
[move.iter.requirements]
The template parameter Iterator shall meet the requirements for an Input Iterator (24.2.3). Additionally, if any of the bidirectional or random access traversal functions are instantiated, the template parameter shall meet the requirements for a Bidirectional Iterator (24.2.6) or a Random Access Iterator (24.2.7), respectively. 24.5.3.3 move_iterator operations [move.iter.ops] 24.5.3.3.1
move_iterator constructors
[move.iter.op.const]
move_iterator(); 1
Effects: Constructs a move_iterator, value initializing current. Iterator operations applied to the resulting iterator have defined behavior if and only if the corresponding operations are defined on a value-initialized iterator of type Iterator. explicit move_iterator(Iterator i);
2
Effects: Constructs a move_iterator, initializing current with i. template move_iterator(const move_iterator& u);
3
Effects: Constructs a move_iterator, initializing current with u.base().
4
Requires: U shall be convertible to Iterator. 24.5.3.3.2
move_iterator::operator=
[move.iter.op=]
template move_iterator& operator=(const move_iterator& u); 1
Effects: Assigns u.base() to current.
2
Requires: U shall be convertible to Iterator. 24.5.3.3.3
move_iterator conversion
[move.iter.op.conv]
Iterator base() const; 1
Returns: current.
§ 24.5.3.3.3
826
c ISO/IEC
24.5.3.3.4
N3376
move_iterator::operator*
[move.iter.op.star]
reference operator*() const; 1
Returns: std::move(*current). 24.5.3.3.5
move_iterator::operator->
[move.iter.op.ref]
pointer operator->() const; 1
Returns: current. 24.5.3.3.6
move_iterator::operator++
[move.iter.op.incr]
move_iterator& operator++(); 1
Effects: ++current.
2
Returns: *this. move_iterator operator++(int);
3
Effects: move_iterator tmp = *this; ++current; return tmp;
24.5.3.3.7
move_iterator::operator--
[move.iter.op.decr]
move_iterator& operator--(); 1
Effects: --current.
2
Returns: *this. move_iterator operator--(int);
3
Effects: move_iterator tmp = *this; --current; return tmp;
24.5.3.3.8
move_iterator::operator+
[move.iter.op.+]
move_iterator operator+(difference_type n) const; 1
Returns: move_iterator(current + n). 24.5.3.3.9
move_iterator::operator+=
[move.iter.op.+=]
move_iterator& operator+=(difference_type n); 1
Effects: current += n.
2
Returns: *this. 24.5.3.3.10
move_iterator::operator-
[move.iter.op.-]
move_iterator operator-(difference_type n) const; 1
Returns: move_iterator(current - n). § 24.5.3.3.10
827
c ISO/IEC
24.5.3.3.11
N3376
move_iterator::operator-=
[move.iter.op.-=]
move_iterator& operator-=(difference_type n); 1
Effects: current -= n.
2
Returns: *this.
1
24.5.3.3.12
move_iterator::operator[]
unspecified
operator[](difference_type n) const;
[move.iter.op.index]
Returns: std::move(current[n]). 24.5.3.3.13
move_iterator comparisons
[move.iter.op.comp]
template bool operator==(const move_iterator& x, const move_iterator& y); 1
Returns: x.base() == y.base(). template bool operator!=(const move_iterator& x, const move_iterator& y);
2
Returns: !(x == y). template bool operator=(const move_iterator& x, const move_iterator& y);
6
Returns: !(x < y). 24.5.3.3.14
move_iterator non-member functions
[move.iter.nonmember]
template auto operator-( const move_iterator& x, const move_iterator& y) -> decltype(x.base() - y.base()); 1
Returns: x.base() - y.base().
§ 24.5.3.3.14
828
c ISO/IEC
N3376
template move_iterator operator+( typename move_iterator::difference_type n, const move_iterator& x); 2
Returns: x + n. template move_iterator make_move_iterator(Iterator i);
3
Returns: move_iterator(i).
24.6 1
Stream iterators
[stream.iterators]
To make it possible for algorithmic templates to work directly with input/output streams, appropriate iterator-like class templates are provided. [ Example: partial_sum_copy(istream_iterator<double, char>(cin), istream_iterator<double, char>(), ostream_iterator<double, char>(cout, "\n"));
reads a file containing floating point numbers from cin, and prints the partial sums onto cout. — end example ]
24.6.1 1
2
Class template istream_iterator
[istream.iterator]
The class template istream_iterator is an input iterator (24.2.3) that reads (using operator>>) successive elements from the input stream for which it was constructed. After it is constructed, and every time ++ is used, the iterator reads and stores a value of T. If the iterator fails to read and store a value of T (fail() on the stream returns true), the iterator becomes equal to the end-of-stream iterator value. The constructor with no arguments istream_iterator() always constructs an end-of-stream input iterator object, which is the only legitimate iterator to be used for the end condition. The result of operator* on an end-of-stream iterator is not defined. For any other iterator value a const T& is returned. The result of operator-> on an end-of-stream iterator is not defined. For any other iterator value a const T* is returned. The behavior of a program that applies operator++() to an end-of-stream iterator is undefined. It is impossible to store things into istream iterators. Two end-of-stream iterators are always equal. An end-of-stream iterator is not equal to a non-end-of-stream iterator. Two non-end-of-stream iterators are equal when they are constructed from the same stream. namespace std { template class istream_iterator: public iterator { public: typedef charT char_type; typedef traits traits_type; typedef basic_istream istream_type; see below istream_iterator(); istream_iterator(istream_type& s); istream_iterator(const istream_iterator& x) = default; ~istream_iterator() = default; const T& operator*() const; const T* operator->() const; istream_iterator& operator++();
§ 24.6.1
829
c ISO/IEC
N3376
istream_iterator operator++(int); private: basic_istream* in_stream; // exposition only T value; // exposition only }; template bool operator==(const istream_iterator& x, const istream_iterator& y); template bool operator!=(const istream_iterator& x, const istream_iterator& y); }
24.6.1.1
istream_iterator constructors and destructor
[istream.iterator.cons]
see below istream_iterator(); 1
Effects: Constructs the end-of-stream iterator. If T is a literal type, then this constructor shall be a constexpr constructor.
2
Postcondition: in_stream == 0. istream_iterator(istream_type& s);
3
Effects: Initializes in_stream with &s. value may be initialized during construction or the first time it is referenced.
4
Postcondition: in_stream == &s. istream_iterator(const istream_iterator& x) = default;
5
Effects: Constructs a copy of x. If T is a literal type, then this constructor shall be a trivial copy constructor.
6
Postcondition: in_stream == x.in_stream. ~istream_iterator() = default;
7
Effects: The iterator is destroyed. If T is a literal type, then this destructor shall be a trivial destructor. 24.6.1.2
istream_iterator operations
[istream.iterator.ops]
const T& operator*() const; 1
Returns: value. const T* operator->() const;
2
Returns: &(operator*()). istream_iterator& operator++();
3
Requires: in_stream != 0.
4
Effects: *in_stream » value.
5
Returns: *this. § 24.6.1.2
830
c ISO/IEC
N3376
istream_iterator operator++(int); 6
Requires: in_stream != 0.
7
Effects: istream_iterator tmp = *this; *in_stream >> value; return (tmp);
template bool operator==(const istream_iterator &x, const istream_iterator &y); 8
Returns: x.in_stream == y.in_stream. template bool operator!=(const istream_iterator &x, const istream_iterator &y);
9
Returns: !(x == y)
24.6.2 1
Class template ostream_iterator
[ostream.iterator]
ostream_iterator writes (using operatorsbumpc().
2
Returns: *this. proxy istreambuf_iterator::operator++(int);
3
Returns: proxy(sbuf_->sbumpc(), sbuf_). 24.6.3.5
istreambuf_iterator::equal
[istreambuf.iterator::equal]
bool equal(const istreambuf_iterator& b) const; 1
Returns: true if and only if both iterators are at end-of-stream, or neither is at end-of-stream, regardless of what streambuf object they use. 24.6.3.6
operator==
[istreambuf.iterator::op==]
template bool operator==(const istreambuf_iterator& a, const istreambuf_iterator& b); 1
Returns: a.equal(b). 24.6.3.7
operator!=
[istreambuf.iterator::op!=]
template bool operator!=(const istreambuf_iterator& a, const istreambuf_iterator& b); 1
Returns: !a.equal(b). § 24.6.3.7
834
c ISO/IEC
24.6.4
N3376
Class template ostreambuf_iterator
[ostreambuf.iterator]
namespace std { template class ostreambuf_iterator : public iterator { public: typedef charT char_type; typedef traits traits_type; typedef basic_streambuf streambuf_type; typedef basic_ostream ostream_type; public: ostreambuf_iterator(ostream_type& s) noexcept; ostreambuf_iterator(streambuf_type* s) noexcept; ostreambuf_iterator& operator=(charT c); ostreambuf_iterator& operator*(); ostreambuf_iterator& operator++(); ostreambuf_iterator& operator++(int); bool failed() const noexcept; private: streambuf_type* sbuf_; };
// exposition only
} 1
The class template ostreambuf_iterator writes successive characters onto the output stream from which it was constructed. It is not possible to get a character value out of the output iterator. 24.6.4.1 ostreambuf_iterator constructors [ostreambuf.iter.cons] ostreambuf_iterator(ostream_type& s) noexcept;
1
Requires: s.rdbuf() shall not null pointer.
2
Effects: :sbuf_(s.rdbuf()) {}. ostreambuf_iterator(streambuf_type* s) noexcept;
3
Requires: s shall not be a null pointer.
4
Effects: : 24.6.4.2
sbuf_(s) {}.
ostreambuf_iterator operations
[ostreambuf.iter.ops]
ostreambuf_iterator& operator=(charT c); 1
Effects: If failed() yields false, calls sbuf_->sputc(c); otherwise has no effect.
2
Returns: *this. ostreambuf_iterator& operator*();
3
Returns: *this.
§ 24.6.4.2
835
c ISO/IEC
N3376
ostreambuf_iterator& operator++(); ostreambuf_iterator& operator++(int); 4
Returns: *this. bool failed() const noexcept;
5
Returns: true if in any prior use of member operator=, the call to sbuf_->sputc() returned traits::eof(); or false otherwise.
24.7 1
range access
[iterator.range]
In addition to being available via inclusion of the header, the function templates in 24.7 are available when any of the following headers are included: <array>, <deque>, , <list>, <map>, , <set>, <string>, , , and . template auto begin(C& c) -> decltype(c.begin()); template auto begin(const C& c) -> decltype(c.begin());
2
Returns: c.begin(). template auto end(C& c) -> decltype(c.end()); template auto end(const C& c) -> decltype(c.end());
3
Returns: c.end(). template T* begin(T (&array)[N]);
4
Returns: array. template T* end(T (&array)[N]);
5
Returns: array + N.
§ 24.7
836
c ISO/IEC
25 25.1 1
2
N3376
Algorithms library
[algorithms]
General
[algorithms.general]
This Clause describes components that C++ programs may use to perform algorithmic operations on containers (Clause 23) and other sequences. The following subclauses describe components for non-modifying sequence operation, modifying sequence operations, sorting and related operations, and algorithms from the ISO C library, as summarized in Table 112. Table 112 — Algorithms library summary
25.2 25.3 25.4 25.5
Subclause Non-modifying sequence operations Mutating sequence operations Sorting and related operations C library algorithms
Header(s)
Header synopsis #include namespace std { // 25.2, non-modifying sequence operations: template bool all_of(InputIterator first, InputIterator last, Predicate pred); template bool any_of(InputIterator first, InputIterator last, Predicate pred); template bool none_of(InputIterator first, InputIterator last, Predicate pred); template Function for_each(InputIterator first, InputIterator last, Function f); template InputIterator find(InputIterator first, InputIterator last, const T& value); template InputIterator find_if(InputIterator first, InputIterator last, Predicate pred); template InputIterator find_if_not(InputIterator first, InputIterator last, Predicate pred); template ForwardIterator1 find_end(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); template ForwardIterator1
§ 25.1
837
c ISO/IEC
N3376
find_end(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred); template InputIterator find_first_of(InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2); template InputIterator find_first_of(InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2, BinaryPredicate pred); template ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last); template ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last, BinaryPredicate pred); template typename iterator_traits::difference_type count(InputIterator first, InputIterator last, const T& value); template typename iterator_traits::difference_type count_if(InputIterator first, InputIterator last, Predicate pred); template pair mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2); template pair mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate pred); template bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2); template bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate pred); template bool is_permutation(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2); template bool is_permutation(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, BinaryPredicate pred);
§ 25.1
838
c ISO/IEC
N3376
template ForwardIterator1 search( ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); template ForwardIterator1 search( ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred); template ForwardIterator search_n(ForwardIterator first, ForwardIterator last, Size count, const T& value); template ForwardIterator1 search_n(ForwardIterator first, ForwardIterator last, Size count, const T& value, BinaryPredicate pred); // 25.3, modifying sequence operations: // 25.3.1, copy: template OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result); template OutputIterator copy_n(InputIterator first, Size n, OutputIterator result); template OutputIterator copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate pred); template BidirectionalIterator2 copy_backward( BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result); // 25.3.2, move: template OutputIterator move(InputIterator first, InputIterator last, OutputIterator result); template BidirectionalIterator2 move_backward( BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result); // 25.3.3, swap: template ForwardIterator2 swap_ranges(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2); template void iter_swap(ForwardIterator1 a, ForwardIterator2 b); template OutputIterator transform(InputIterator first, InputIterator last, OutputIterator result, UnaryOperation op);
§ 25.1
839
c ISO/IEC
N3376
template OutputIterator transform(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryOperation binary_op); template void replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value); template void replace_if(ForwardIterator first, ForwardIterator last, Predicate pred, const T& new_value); template OutputIterator replace_copy(InputIterator first, InputIterator last, OutputIterator result, const T& old_value, const T& new_value); template OutputIterator replace_copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate pred, const T& new_value); template void fill(ForwardIterator first, ForwardIterator last, const T& value); template OutputIterator fill_n(OutputIterator first, Size n, const T& value); template void generate(ForwardIterator first, ForwardIterator last, Generator gen); template OutputIterator generate_n(OutputIterator first, Size n, Generator gen); template ForwardIterator remove(ForwardIterator first, ForwardIterator last, const T& value); template ForwardIterator remove_if(ForwardIterator first, ForwardIterator last, Predicate pred); template OutputIterator remove_copy(InputIterator first, InputIterator last, OutputIterator result, const T& value); template OutputIterator remove_copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate pred); template ForwardIterator unique(ForwardIterator first, ForwardIterator last); template ForwardIterator unique(ForwardIterator first, ForwardIterator last, BinaryPredicate pred); template OutputIterator unique_copy(InputIterator first, InputIterator last, OutputIterator result); template OutputIterator unique_copy(InputIterator first, InputIterator last,
§ 25.1
840
c ISO/IEC
N3376
OutputIterator result, BinaryPredicate pred); template void reverse(BidirectionalIterator first, BidirectionalIterator last); template OutputIterator reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result); template ForwardIterator rotate(ForwardIterator first, ForwardIterator middle, ForwardIterator last); template OutputIterator rotate_copy( ForwardIterator first, ForwardIterator middle, ForwardIterator last, OutputIterator result); template void random_shuffle(RandomAccessIterator first, RandomAccessIterator last); template void random_shuffle(RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator&& rand); template void shuffle(RandomAccessIterator first, RandomAccessIterator last, UniformRandomNumberGenerator&& rand); // 25.3.13, partitions: template bool is_partitioned(InputIterator first, InputIterator last, Predicate pred); template ForwardIterator partition(ForwardIterator first, ForwardIterator last, Predicate pred); template BidirectionalIterator stable_partition(BidirectionalIterator first, BidirectionalIterator last, Predicate pred); template pair partition_copy(InputIterator first, InputIterator last, OutputIterator1 out_true, OutputIterator2 out_false, Predicate pred); template ForwardIterator partition_point(ForwardIterator first, ForwardIterator last, Predicate pred); // 25.4, sorting and related operations: // 25.4.1, sorting: template
§ 25.1
841
c ISO/IEC
N3376
void sort(RandomAccessIterator first, RandomAccessIterator last); template void sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp); template void stable_sort(RandomAccessIterator first, RandomAccessIterator last); template void stable_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp); template void partial_sort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last); template void partial_sort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last, Compare comp); template RandomAccessIterator partial_sort_copy( InputIterator first, InputIterator last, RandomAccessIterator result_first, RandomAccessIterator result_last); template RandomAccessIterator partial_sort_copy( InputIterator first, InputIterator last, RandomAccessIterator result_first, RandomAccessIterator result_last, Compare comp); template bool is_sorted(ForwardIterator first, ForwardIterator last); template bool is_sorted(ForwardIterator first, ForwardIterator last, Compare comp); template ForwardIterator is_sorted_until(ForwardIterator first, ForwardIterator last); template ForwardIterator is_sorted_until(ForwardIterator first, ForwardIterator last, Compare comp); template void nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last); template void nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, Compare comp); // 25.4.3, binary search: template ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& value); template ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& value, Compare comp);
§ 25.1
842
c ISO/IEC
N3376
template ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last, const T& value); template ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last, const T& value, Compare comp); template pair equal_range(ForwardIterator first, ForwardIterator last, const T& value); template pair equal_range(ForwardIterator first, ForwardIterator last, const T& value, Compare comp); template bool binary_search(ForwardIterator first, ForwardIterator last, const T& value); template bool binary_search(ForwardIterator first, ForwardIterator last, const T& value, Compare comp); // 25.4.4, merge: template OutputIterator merge(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); template OutputIterator merge(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp); template void inplace_merge(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last); template void inplace_merge(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp); // 25.4.5, set operations: template bool includes(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2); template bool includes( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, Compare comp); template OutputIterator set_union(InputIterator1 first1, InputIterator1 last1,
§ 25.1
843
c ISO/IEC
N3376
InputIterator2 first2, InputIterator2 last2, OutputIterator result); template OutputIterator set_union(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp); template OutputIterator set_intersection( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); template OutputIterator set_intersection( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp); template OutputIterator set_difference( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); template OutputIterator set_difference( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp); template OutputIterator set_symmetric_difference( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); template OutputIterator set_symmetric_difference( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp); // 25.4.6, heap operations: template void push_heap(RandomAccessIterator first, RandomAccessIterator last); template void push_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp); template void pop_heap(RandomAccessIterator first, RandomAccessIterator last); template void pop_heap(RandomAccessIterator first, RandomAccessIterator last,
§ 25.1
844
c ISO/IEC
N3376
Compare comp); template void make_heap(RandomAccessIterator first, RandomAccessIterator last); template void make_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp); template void sort_heap(RandomAccessIterator first, RandomAccessIterator last); template void sort_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp); template bool is_heap(RandomAccessIterator first, RandomAccessIterator last); template bool is_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp); template RandomAccessIterator is_heap_until(RandomAccessIterator first, RandomAccessIterator last); template RandomAccessIterator is_heap_until(RandomAccessIterator first, RandomAccessIterator last, Compare comp); // 25.4.7, minimum and maximum: template const T& min(const T& a, const T& b); template const T& min(const T& a, const T& b, Compare comp); template T min(initializer_list t); template T min(initializer_list t, Compare comp); template const T& max(const T& a, const T& b); template const T& max(const T& a, const T& b, Compare comp); template T max(initializer_list t); template T max(initializer_list t, Compare comp); template pair minmax(const T& a, const T& b); template pair minmax(const T& a, const T& b, Compare comp); template pair minmax(initializer_list t); template pair minmax(initializer_list t, Compare comp); template ForwardIterator min_element(ForwardIterator first, ForwardIterator last); template ForwardIterator min_element(ForwardIterator first, ForwardIterator last, Compare comp); template
§ 25.1
845
c ISO/IEC
N3376
ForwardIterator max_element(ForwardIterator first, ForwardIterator last); template ForwardIterator max_element(ForwardIterator first, ForwardIterator last, Compare comp); template pair minmax_element(ForwardIterator first, ForwardIterator last); template pair minmax_element(ForwardIterator first, ForwardIterator last, Compare comp); template bool lexicographical_compare( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2); template bool lexicographical_compare( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, Compare comp); // 25.4.9, permutations: template bool next_permutation(BidirectionalIterator first, BidirectionalIterator last); template bool next_permutation(BidirectionalIterator first, BidirectionalIterator last, Compare comp); template bool prev_permutation(BidirectionalIterator first, BidirectionalIterator last); template bool prev_permutation(BidirectionalIterator first, BidirectionalIterator last, Compare comp); } 3
4
5
6
All of the algorithms are separated from the particular implementations of data structures and are parameterized by iterator types. Because of this, they can work with program-defined data structures, as long as these data structures have iterator types satisfying the assumptions on the algorithms. For purposes of determining the existence of data races, algorithms shall not modify objects referenced through an iterator argument unless the specification requires such modification. Throughout this Clause, the names of template parameters are used to express type requirements. If an algorithm’s template parameter is InputIterator, InputIterator1, or InputIterator2, the actual template argument shall satisfy the requirements of an input iterator (24.2.3). If an algorithm’s template parameter is OutputIterator, OutputIterator1, or OutputIterator2, the actual template argument shall satisfy the requirements of an output iterator (24.2.4). If an algorithm’s template parameter is ForwardIterator, ForwardIterator1, or ForwardIterator2, the actual template argument shall satisfy the requirements of a forward iterator (24.2.5). If an algorithm’s template parameter is BidirectionalIterator, BidirectionalIterator1, or BidirectionalIterator2, the actual template argument shall satisfy the requirements of a bidirectional iterator (24.2.6). If an algorithm’s template parameter is RandomAccessIterator, RandomAccessIterator1, or RandomAccessIterator2, the actual template argument shall satisfy the requirements of a random-access iterator (24.2.7). If an algorithm’s Effects section says that a value pointed to by any iterator passed as an argument is modified, then that algorithm has an additional type requirement: The type of that argument shall satisfy § 25.1
846
c ISO/IEC
7
8
9
10
11
12
N3376
the requirements of a mutable iterator (24.2). [ Note: This requirement does not affect arguments that are declared as OutputIterator, OutputIterator1, or OutputIterator2, because output iterators must always be mutable. — end note ] Both in-place and copying versions are provided for certain algorithms.267 When such a version is provided for algorithm it is called algorithm_copy. Algorithms that take predicates end with the suffix _if (which follows the suffix _copy). The Predicate parameter is used whenever an algorithm expects a function object (20.8) that, when applied to the result of dereferencing the corresponding iterator, returns a value testable as true. In other words, if an algorithm takes Predicate pred as its argument and first as its iterator argument, it should work correctly in the construct pred(*first) contextually converted to bool (Clause 4). The function object pred shall not apply any non-constant function through the dereferenced iterator. The BinaryPredicate parameter is used whenever an algorithm expects a function object that when applied to the result of dereferencing two corresponding iterators or to dereferencing an iterator and type T when T is part of the signature returns a value testable as true. In other words, if an algorithm takes BinaryPredicate binary_pred as its argument and first1 and first2 as its iterator arguments, it should work correctly in the construct binary_pred(*first1, *first2) contextually converted to bool (Clause 4). BinaryPredicate always takes the first iterator’s value_type as its first argument, that is, in those cases when T value is part of the signature, it should work correctly in the construct binary_pred(*first1, value) contextually converted to bool (Clause 4). binary_pred shall not apply any non-constant function through the dereferenced iterators. [ Note: Unless otherwise specified, algorithms that take function objects as arguments are permitted to copy those function objects freely. Programmers for whom object identity is important should consider using a wrapper class that points to a noncopied implementation object such as reference_wrapper (20.8.3), or some equivalent solution. — end note ] When the description of an algorithm gives an expression such as *first == value for a condition, the expression shall evaluate to either true or false in boolean contexts. In the description of the algorithms operators + and - are used for some of the iterator categories for which they do not have to be defined. In these cases the semantics of a+n is the same as that of X tmp = a; advance(tmp, n); return tmp;
and that of b-a is the same as of return distance(a, b);
25.2
Non-modifying sequence operations
25.2.1
All of
[alg.nonmodifying] [alg.all_of]
template bool all_of(InputIterator first, InputIterator last, Predicate pred); 1
Returns: true if [first,last) is empty or if pred(*i) is true for every iterator i in the range [first,last), and false otherwise.
2
Complexity: At most last - first applications of the predicate.
25.2.2
Any of
[alg.any_of]
267) The decision whether to include a copying version was usually based on complexity considerations. When the cost of doing the operation dominates the cost of copy, the copying version is not included. For example, sort_copy is not included because the cost of sorting is much more significant, and users might as well do copy followed by sort.
§ 25.2.2
847
c ISO/IEC
N3376
template bool any_of(InputIterator first, InputIterator last, Predicate pred); 1
Returns: false if [first,last) is empty or if there is no iterator i in the range [first,last) such that pred(*i) is true, and true otherwise.
2
Complexity: At most last - first applications of the predicate.
25.2.3
None of
[alg.none_of]
template bool none_of(InputIterator first, InputIterator last, Predicate pred); 1
Returns: true if [first,last) is empty or if pred(*i) is false for every iterator i in the range [first,last), and false otherwise.
2
Complexity: At most last - first applications of the predicate.
25.2.4
For each
[alg.foreach]
template Function for_each(InputIterator first, InputIterator last, Function f); 1
Requires: Function shall meet the requirements of MoveConstructible (Table 20). [ Note: Function need not meet the requirements of CopyConstructible (Table 21). — end note ]
2
Effects: Applies f to the result of dereferencing every iterator in the range [first,last), starting from first and proceeding to last - 1. [ Note: If the type of first satisfies the requirements of a mutable iterator, f may apply nonconstant functions through the dereferenced iterator. — end note ]
3
Returns: std::move(f).
4
Complexity: Applies f exactly last - first times.
5
Remarks: If f returns a result, the result is ignored.
25.2.5
Find
[alg.find]
template InputIterator find(InputIterator first, InputIterator last, const T& value); template InputIterator find_if(InputIterator first, InputIterator last, Predicate pred); template InputIterator find_if_not(InputIterator first, InputIterator last, Predicate pred); 1
Returns: The first iterator i in the range [first,last) for which the following corresponding conditions hold: *i == value, pred(*i) != false, pred(*i) == false. Returns last if no such iterator is found.
2
Complexity: At most last - first applications of the corresponding predicate.
25.2.6
Find end
[alg.find.end]
template ForwardIterator1 find_end(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2);
§ 25.2.6
848
c ISO/IEC
N3376
template ForwardIterator1 find_end(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred); 1
Effects: Finds a subsequence of equal values in a sequence.
2
Returns: The last iterator i in the range [first1,last1 - (last2 - first2)) such that for any nonnegative integer n < (last2 - first2), the following corresponding conditions hold: *(i + n) == *(first2 + n), pred(*(i + n), *(first2 + n)) != false. Returns last1 if [first2,last2) is empty or if no such iterator is found.
3
Complexity: At most (last2 - first2) * (last1 - first1 - (last2 - first2) + 1) applications of the corresponding predicate.
25.2.7
Find first
[alg.find.first.of]
template InputIterator find_first_of(InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2); template InputIterator find_first_of(InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2, BinaryPredicate pred); 1
Effects: Finds an element that matches one of a set of values.
2
Returns: The first iterator i in the range [first1,last1) such that for some iterator j in the range [first2,last2) the following conditions hold: *i == *j, pred(*i,*j) != false. Returns last1 if [first2,last2) is empty or if no such iterator is found.
3
Complexity: At most (last1-first1) * (last2-first2) applications of the corresponding predicate.
25.2.8
Adjacent find
[alg.adjacent.find]
template ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last); template ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last, BinaryPredicate pred); 1
Returns: The first iterator i such that both i and i + 1 are in the range [first,last) for which the following corresponding conditions hold: *i == *(i + 1), pred(*i, *(i + 1)) != false. Returns last if no such iterator is found.
2
Complexity: For a nonempty range, exactly min((i - first) + 1, (last - first) - 1) applications of the corresponding predicate, where i is adjacent_find’s return value.
25.2.9
§ 25.2.9
Count
[alg.count]
849
c ISO/IEC
N3376
template typename iterator_traits::difference_type count(InputIterator first, InputIterator last, const T& value); template typename iterator_traits::difference_type count_if(InputIterator first, InputIterator last, Predicate pred); 1
Effects: Returns the number of iterators i in the range [first,last) for which the following corresponding conditions hold: *i == value, pred(*i) != false.
2
Complexity: Exactly last - first applications of the corresponding predicate.
25.2.10
Mismatch
[mismatch]
template pair mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2); template pair mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate pred); 1
Returns: A pair of iterators i and j such that j == first2 + (i - first1) and i is the first iterator in the range [first1,last1) for which the following corresponding conditions hold: !(*i == *(first2 + (i - first1))) pred(*i, *(first2 + (i - first1))) == false
Returns the pair last1 and first2 + (last1 - first1) if such an iterator i is not found. 2
Complexity: At most last1 - first1 applications of the corresponding predicate.
25.2.11
Equal
[alg.equal]
template bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2); template bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate pred); 1
Returns: true if for every iterator i in the range [first1,last1) the following corresponding conditions hold: *i == *(first2 + (i - first1)), pred(*i, *(first2 + (i - first1))) != false. Otherwise, returns false.
2
Complexity: At most last1 - first1 applications of the corresponding predicate.
25.2.12
Is permutation
template bool is_permutation(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, BinaryPredicate pred); 1
Requires:: ForwardIterator1 and ForwardIterator2 shall have the same value type. The comparison function shall be an equivalence relation.
2
Returns: true if there exists a permutation of the elements in the range [first2,first2 + (last1 - first1)), beginning with ForwardIterator2 begin, such that equal(first1, last1, begin) returns true or equal(first1, last1, begin, pred) returns true; otherwise, returns false.
3
Complexity: Exactly distance(first1, last1) applications of the corresponding predicate if equal( first1, last1, first2) would return true or equal(first1, last1, first2, pred) would return true; otherwise, at worst O(N 2 ), where N has the value distance(first1, last1).
25.2.13
Search
[alg.search]
template ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); template ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred); 1
Effects: Finds a subsequence of equal values in a sequence.
2
Returns: The first iterator i in the range [first1,last1 - (last2-first2)) such that for any nonnegative integer n less than last2 - first2 the following corresponding conditions hold: *(i + n) == *(first2 + n), pred(*(i + n), *(first2 + n)) != false. Returns first1 if [first2,last2) is empty, otherwise returns last1 if no such iterator is found.
3
Complexity: At most (last1 - first1) * (last2 - first2) applications of the corresponding predicate. template ForwardIterator search_n(ForwardIterator first, ForwardIterator last, Size count, const T& value); template ForwardIterator search_n(ForwardIterator first, ForwardIterator last, Size count, const T& value, BinaryPredicate pred);
4
Requires: The type Size shall be convertible to integral type (4.7, 12.3).
5
Effects: Finds a subsequence of equal values in a sequence.
6
Returns: The first iterator i in the range [first,last-count) such that for any non-negative integer n less than count the following corresponding conditions hold: *(i + n) == value, pred(*(i + n),value) != false. Returns last if no such iterator is found.
7
Complexity: At most last - first applications of the corresponding predicate. § 25.2.13
851
c ISO/IEC
25.3
Mutating sequence operations
25.3.1
N3376
[alg.modifying.operations]
Copy
[alg.copy]
template OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result); 1
Effects: Copies elements in the range [first,last) into the range [result,result + (last first)) starting from first and proceeding to last. For each non-negative integer n < (last first), performs *(result + n) = *(first + n).
2
Returns: result + (last - first).
3
Requires: result shall not be in the range [first,last).
4
Complexity: Exactly last - first assignments. template OutputIterator copy_n(InputIterator first, Size n, OutputIterator result);
5
Effects: For each non-negative integer i < n, performs *(result + i) = *(first + i).
6
Returns: result + n.
7
Complexity: Exactly n assignments. template OutputIterator copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate pred);
8
Requires: The ranges [first,last) and [result,result + (last - first)) shall not overlap.
9
Effects: Copies all of the elements referred to by the iterator i in the range [first,last) for which pred(*i) is true.
10
Returns: The end of the resulting range.
11
Complexity: Exactly last - first applications of the corresponding predicate.
12
Remarks: Stable. template BidirectionalIterator2 copy_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result);
13
Effects: Copies elements in the range [first,last) into the range [result - (last-first),result ) starting from last - 1 and proceeding to first.268 For each positive integer n 0.
5
Returns: The smallest value in the initializer_list.
6
Remarks: Returns a copy of the leftmost argument when several arguments are equivalent to the smallest. template const T& max(const T& a, const T& b); template const T& max(const T& a, const T& b, Compare comp);
7
Requires: Type T is LessThanComparable (Table 18).
8
Returns: The larger value.
9
Remarks: Returns the first argument when the arguments are equivalent. template T max(initializer_list t); template T max(initializer_list t, Compare comp);
10
Requires: T is LessThanComparable and CopyConstructible and t.size() > 0.
11
Returns: The largest value in the initializer_list.
12
Remarks: Returns a copy of the leftmost argument when several arguments are equivalent to the largest.
§ 25.4.7
870
c ISO/IEC
N3376
template pair minmax(const T& a, const T& b); template pair minmax(const T& a, const T& b, Compare comp); 13
Requires: Type T shall be LessThanComparable (Table 18).
14
Returns: pair(b, a) if b is smaller than a, and pair(a, b) otherwise.
15
Remarks: Returns pair(a, b) when the arguments are equivalent.
16
Complexity: Exactly one comparison. template pair minmax(initializer_list t); template pair minmax(initializer_list t, Compare comp);
17
Requires: T is LessThanComparable and CopyConstructible and t.size() > 0.
18
Returns: pair(x, y), where x has the smallest and y has the largest value in the initializer list.
19
Remarks: x is a copy of the leftmost argument when several arguments are equivalent to the smallest. y is a copy of the rightmost argument when several arguments are equivalent to the largest.
20
Complexity: At most (3/2) * t.size() applications of the corresponding predicate. template ForwardIterator min_element(ForwardIterator first, ForwardIterator last); template ForwardIterator min_element(ForwardIterator first, ForwardIterator last, Compare comp);
21
Returns: The first iterator i in the range [first,last) such that for any iterator j in the range [first,last) the following corresponding conditions hold: !(*j < *i) or comp(*j, *i) == false. Returns last if first == last.
22
Complexity: Exactly max((last - first) - 1, 0) applications of the corresponding comparisons. template ForwardIterator max_element(ForwardIterator first, ForwardIterator last); template ForwardIterator max_element(ForwardIterator first, ForwardIterator last, Compare comp);
23
Returns: The first iterator i in the range [first,last) such that for any iterator j in the range [first,last) the following corresponding conditions hold: !(*i < *j) or comp(*i, *j) == false. Returns last if first == last.
24
Complexity: Exactly max((last - first) - 1, 0) applications of the corresponding comparisons.
§ 25.4.7
871
c ISO/IEC
N3376
template pair minmax_element(ForwardIterator first, ForwardIterator last); template pair minmax_element(ForwardIterator first, ForwardIterator last, Compare comp); 25
Returns: make_pair(first, first) if [first,last) is empty, otherwise make_pair(m, M), where m is the first iterator in [first,last) such that no iterator in the range refers to a smaller element, and where M is the last iterator in [first,last) such that no iterator in the range refers to a larger element.
26
Complexity: At most max(b 23 (N − 1)c, 0) applications of the corresponding predicate, where N is distance(first, last).
25.4.8
Lexicographical comparison
[alg.lex.comparison]
template bool lexicographical_compare(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2); template bool lexicographical_compare(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, Compare comp); 1
Returns: true if the sequence of elements defined by the range [first1,last1) is lexicographically less than the sequence of elements defined by the range [first2,last2) and false otherwise.
2
Complexity: At most 2*min((last1 - first1), (last2 - first2)) applications of the corresponding comparison.
3
Remarks: If two sequences have the same number of elements and their corresponding elements are equivalent, then neither sequence is lexicographically less than the other. If one sequence is a prefix of the other, then the shorter sequence is lexicographically less than the longer sequence. Otherwise, the lexicographical comparison of the sequences yields the same result as the comparison of the first corresponding pair of elements that are not equivalent. for ( ; first1 != last1 && first2 != last2 ; ++first1, ++first2) { if (*first1 < *first2) return true; if (*first2 < *first1) return false; } return first1 == last1 && first2 != last2;
4
Remarks: An empty sequence is lexicographically less than any non-empty sequence, but not less than any empty sequence.
25.4.9
Permutation generators
[alg.permutation.generators]
template bool next_permutation(BidirectionalIterator first, BidirectionalIterator last); template bool next_permutation(BidirectionalIterator first, BidirectionalIterator last, Compare comp);
§ 25.4.9
872
c ISO/IEC
N3376
1
Effects: Takes a sequence defined by the range [first,last) and transforms it into the next permutation. The next permutation is found by assuming that the set of all permutations is lexicographically sorted with respect to operator< or comp. If such a permutation exists, it returns true. Otherwise, it transforms the sequence into the smallest permutation, that is, the ascendingly sorted one, and returns false.
2
Requires: BidirectionalIterator shall satisfy the requirements of ValueSwappable (17.6.3.2).
3
Complexity: At most (last - first)/2 swaps. template bool prev_permutation(BidirectionalIterator first, BidirectionalIterator last); template bool prev_permutation(BidirectionalIterator first, BidirectionalIterator last, Compare comp);
4
Effects: Takes a sequence defined by the range [first,last) and transforms it into the previous permutation. The previous permutation is found by assuming that the set of all permutations is lexicographically sorted with respect to operator< or comp.
5
Returns: true if such a permutation exists. Otherwise, it transforms the sequence into the largest permutation, that is, the descendingly sorted one, and returns false.
6
Requires: BidirectionalIterator shall satisfy the requirements of ValueSwappable (17.6.3.2).
7
Complexity: At most (last - first)/2 swaps.
25.5 1
C library algorithms
[alg.c.library]
Table 113 describes some of the contents of the header . Table 113 — Header synopsis Type Type: Functions:
2 3
Name(s) size_t bsearch qsort
The contents are the same as the Standard C library header <stdlib.h> with the following exceptions: The function signature: bsearch(const void *, const void *, size_t, size_t, int (*)(const void *, const void *));
is replaced by the two declarations: extern "C" void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); extern "C++" void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); 4
both of which have the same behavior as the original declaration. The function signature: § 25.5
873
c ISO/IEC
N3376
qsort(void *, size_t, size_t, int (*)(const void *, const void *));
is replaced by the two declarations: extern "C" void qsort(void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*)); extern "C++" void qsort(void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*));
both of which have the same behavior as the original declaration. The behavior is undefined unless the objects in the array pointed to by base are of trivial type. [ Note: Because the function argument compar() may throw an exception, bsearch() and qsort() are allowed to propagate the exception (17.6.5.12). — end note ] See also: ISO C 7.10.5.
§ 25.5
874
c ISO/IEC
26 26.1 1 2
N3376
Numerics library
[numerics]
General
[numerics.general]
This Clause describes components that C++ programs may use to perform seminumerical operations. The following subclauses describe components for complex number types, random number generation, numeric (n-at-a-time) arrays, generalized numeric algorithms, and facilities included from the ISO C library, as summarized in Table 114. Table 114 — Numerics library summary
26.2 26.3 26.4 26.5 26.6 26.7 26.8
26.2 1
Subclause Requirements Floating-Point Environment Complex Numbers Random number generation Numeric arrays Generalized numeric operations C library
Numeric type requirements
Header(s)
[numeric.requirements]
The complex and valarray components are parameterized by the type of information they contain and manipulate. A C++ program shall instantiate these components only with a type T that satisfies the following requirements:271 — T is not an abstract class (it has no pure virtual member functions); — T is not a reference type; — T is not cv-qualified; — If T is a class, it has a public default constructor; — If T is a class, it has a public copy constructor with the signature T::T(const T&) — If T is a class, it has a public destructor; — If T is a class, it has a public assignment operator whose signature is either T& T::operator=(const T&) or T& T::operator=(T) — If T is a class, its assignment operator, copy and default constructors, and destructor shall correspond to each other in the following sense: Initialization of raw storage using the default constructor, followed by assignment, is semantically equivalent to initialization of raw storage using the copy constructor. 271) In other words, value types. These include arithmetic types, pointers, the library class complex, and instantiations of valarray for value types.
§ 26.2
875
c ISO/IEC
N3376
Destruction of an object, followed by initialization of its raw storage using the copy constructor, is semantically equivalent to assignment to the original object. [ Note: This rule states that there shall not be any subtle differences in the semantics of initialization versus assignment. This gives an implementation considerable flexibility in how arrays are initialized. [ Example: An implementation is allowed to initialize a valarray by allocating storage using the new operator (which implies a call to the default constructor for each element) and then assigning each element its value. Or the implementation can allocate raw storage and use the copy constructor to initialize each element. — end example ] If the distinction between initialization and assignment is important for a class, or if it fails to satisfy any of the other conditions listed above, the programmer should use vector (23.3.6) instead of valarray for that class; — end note ] — If T is a class, it does not overload unary operator&. 2 3
4
If any operation on T throws an exception the effects are undefined. In addition, many member and related functions of valarray can be successfully instantiated and will exhibit well-defined behavior if and only if T satisfies additional requirements specified for each such member or related function. [ Example: It is valid to instantiate valarray, but operator>() will not be successfully instantiated for valarray operands, since complex does not have any ordering operators. — end example ]
26.3 26.3.1
The floating-point environment Header synopsis
[cfenv] [cfenv.syn]
namespace std { // types typedef object type fenv_t; typedef integer type fexcept_t; // functions int feclearexcept(int except); int fegetexceptflag(fexcept_t *pflag, int except); int feraiseexcept(int except); int fesetexceptflag(const fexcept_t *pflag, int except); int fetestexcept(int except); int fegetround(void); int fesetround(int mode); int int int int
fegetenv(fenv_t *penv); feholdexcept(fenv_t *penv); fesetenv(const fenv_t *penv); feupdateenv(const fenv_t *penv);
} 1
The header also defines the macros: FE_ALL_EXCEPT FE_DIVBYZERO FE_INEXACT FE_INVALID FE_OVERFLOW
§ 26.3.1
876
c ISO/IEC
N3376
FE_UNDERFLOW FE_DOWNWARD FE_TONEAREST FE_TOWARDZERO FE_UPWARD FE_DFL_ENV 2 3
4
The header defines all functions, types, and macros the same as Clause 7.6 of the C standard. The floating-point environment has thread storage duration (3.7.2). The initial state for a thread’s floatingpoint environment is the state of the floating-point environment of the thread that constructs the corresponding std::thread object (30.3.1) at the time it constructed the object. [ Note: That is, the child thread gets the floating-point state of the parent thread at the time of the child’s creation. — end note ] A separate floating-point environment shall be maintained for each thread. Each function accesses the environment corresponding to its calling thread.
26.4 1
2
3
4
Complex numbers
[complex.numbers]
The header defines a class template, and numerous functions for representing and manipulating complex numbers. The effect of instantiating the template complex for any type other than float, double, or long double is unspecified. The specializations complex, complex<double>, and complex are literal types (3.9). If the result of a function is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. If z is an lvalue expression of type cv std::complex then: — the expression reinterpret_cast(z) shall be well-formed, — reinterpret_cast(z)[0] shall designate the real part of z, and — reinterpret_cast(z)[1] shall designate the imaginary part of z. Moreover, if a is an expression of type cv std::complex* and the expression a[i] is well-defined for an integer expression i, then: — reinterpret_cast(a)[2*i] shall designate the real part of a[i], and — reinterpret_cast(a)[2*i + 1] shall designate the imaginary part of a[i].
26.4.1
Header synopsis
[complex.syn]
namespace std { template class complex; template class complex; template class complex<double>; template class complex; // 26.4.6, operators: template complex operator+(const complex&, const complex&); template complex operator+(const complex&, const T&); template complex operator+(const T&, const complex&); template complex operator-( const complex&, const complex&);
§ 26.4.1
877
c ISO/IEC
N3376
template complex operator-(const complex&, const T&); template complex operator-(const T&, const complex&); template complex operator*( const complex&, const complex&); template complex operator*(const complex&, const T&); template complex operator*(const T&, const complex&); template complex operator/( const complex&, const complex&); template complex operator/(const complex&, const T&); template complex operator/(const T&, const complex&); template complex operator+(const complex&); template complex operator-(const complex&); template bool operator==( const complex&, const complex&); template bool operator==(const complex&, const T&); template bool operator==(const T&, const complex&); template bool operator!=(const complex&, const complex&); template bool operator!=(const complex&, const T&); template bool operator!=(const T&, const complex&); template basic_istream& operator>>(basic_istream&, complex&); template basic_ostream& operator&); complex<X>&); complex<X>&); complex<X>&); complex<X>&);
}; } 1
The class complex describes an object that can store the Cartesian components, real() and imag(), of a complex number.
26.4.3
complex specializations
[complex.special]
namespace std { template class complex { public: typedef float value_type;
§ 26.4.3
879
c ISO/IEC
N3376
constexpr complex(float re = 0.0f, float im = 0.0f); explicit constexpr complex(const complex<double>&); explicit constexpr complex(const complex&); constexpr float real(); void real(float); constexpr float imag(); void imag(float); complex& complex& complex& complex& complex&
operator= (float); operator+=(float); operator-=(float); operator*=(float); operator/=(float);
complex& operator=(const complex&); template complex& operator= (const template complex& operator+=(const template complex& operator-=(const template complex& operator*=(const template complex& operator/=(const
complex<X>&); complex<X>&); complex<X>&); complex<X>&); complex<X>&);
}; template class complex<double> { public: typedef double value_type; constexpr complex(double re = 0.0, double im = 0.0); constexpr complex(const complex&); explicit constexpr complex(const complex&); constexpr double real(); void real(double); constexpr double imag(); void imag(double); complex<double>& complex<double>& complex<double>& complex<double>& complex<double>&
operator= (double); operator+=(double); operator-=(double); operator*=(double); operator/=(double);
complex<double>& operator=(const complex<double>&); template complex<double>& operator= (const template complex<double>& operator+=(const template complex<double>& operator-=(const template complex<double>& operator*=(const template complex<double>& operator/=(const
complex<X>&); complex<X>&); complex<X>&); complex<X>&); complex<X>&);
}; template class complex { public: typedef long double value_type;
§ 26.4.3
880
c ISO/IEC
N3376
constexpr complex(long double re = 0.0L, long double im = 0.0L); constexpr complex(const complex&); constexpr complex(const complex<double>&); constexpr long void real(long constexpr long void imag(long complex&
template
operator=(const operator= (long operator+=(long operator-=(long operator*=(long operator/=(long
complex&
operator= (const operator+=(const operator-=(const operator*=(const operator/=(const
complex<X>&); complex<X>&); complex<X>&); complex<X>&); complex<X>&);
}; }
26.4.4
complex member functions
[complex.members]
template complex(const T& re = T(), const T& im = T()); 1
Effects: Constructs an object of class complex.
2
Postcondition: real() == re && imag() == im. T real() const;
Returns: The value of the real component. void real(T val);
Effects: Assigns val to the real component. T imag() const;
Returns: The value of the imaginary component. void imag(T val);
Effects: Assigns val to the imaginary component.
26.4.5
complex member operators
[complex.member.ops]
complex& operator+=(const T& rhs); 1
Effects: Adds the scalar value rhs to the real part of the complex value *this and stores the result in the real part of *this, leaving the imaginary part unchanged.
2
Returns: *this. § 26.4.5
881
c ISO/IEC
N3376
complex& operator-=(const T& rhs); 3
Effects: Subtracts the scalar value rhs from the real part of the complex value *this and stores the result in the real part of *this, leaving the imaginary part unchanged.
4
Returns: *this. complex& operator*=(const T& rhs);
5
Effects: Multiplies the scalar value rhs by the complex value *this and stores the result in *this.
6
Returns: *this. complex& operator/=(const T& rhs);
7
Effects: Divides the scalar value rhs into the complex value *this and stores the result in *this.
8
Returns: *this. complex& operator+=(const complex& rhs);
9 10
Effects: Adds the complex value rhs to the complex value *this and stores the sum in *this. Returns: *this. complex& operator-=(const complex& rhs);
11
Effects: Subtracts the complex value rhs from the complex value *this and stores the difference in *this.
12
Returns: *this. complex& operator*=(const complex& rhs);
13
Effects: Multiplies the complex value rhs by the complex value *this and stores the product in *this. Returns: *this. complex& operator/=(const complex& rhs);
14
Effects: Divides the complex value rhs into the complex value *this and stores the quotient in *this.
15
Returns: *this.
26.4.6
complex non-member operations
[complex.ops]
template complex operator+(const complex& lhs); 1
Remarks: unary operator.
2
Returns: complex(lhs). template complex operator+(const complex& lhs, const complex& rhs); template complex operator+(const complex& lhs, const T& rhs); template complex operator+(const T& lhs, const complex& rhs);
§ 26.4.6
882
c ISO/IEC
3
N3376
Returns: complex(lhs) += rhs. template complex operator-(const complex& lhs);
4
Remarks: unary operator.
5
Returns: complex(-lhs.real(),-lhs.imag()). template complex operator-(const complex& lhs, const complex& rhs); template complex operator-(const complex& lhs, const T& rhs); template complex operator-(const T& lhs, const complex& rhs);
6
Returns: complex(lhs) -= rhs. template complex operator*(const complex& lhs, const complex& rhs); template complex operator*(const complex& lhs, const T& rhs); template complex operator*(const T& lhs, const complex& rhs);
7
Returns: complex(lhs) *= rhs. template complex operator/(const complex& lhs, const complex& rhs); template complex operator/(const complex& lhs, const T& rhs); template complex operator/(const T& lhs, const complex& rhs);
8
Returns: complex(lhs) /= rhs. template bool operator==(const complex& lhs, const complex& rhs); template bool operator==(const complex& lhs, const T& rhs); template bool operator==(const T& lhs, const complex& rhs);
9 10
Returns: lhs.real() == rhs.real() && lhs.imag() == rhs.imag(). Remarks: The imaginary part is assumed to be T(), or 0.0, for the T arguments. template bool operator!=(const complex& lhs, const complex& rhs); template bool operator!=(const complex& lhs, const T& rhs); template bool operator!=(const T& lhs, const complex& rhs);
11
Returns: rhs.real() != lhs.real() || rhs.imag() != lhs.imag(). template basic_istream& operator>>(basic_istream& is, complex& x);
§ 26.4.6
883
c ISO/IEC
N3376
12
Effects: Extracts a complex number x of the form: u, (u), or (u,v), where u is the real part and v is the imaginary part (27.7.2.2).
13
Requires: The input values shall be convertible to T. If bad input is encountered, calls is.setstate(ios_base::failbit) (which may throw ios::failure (27.5.5.4)).
14
Returns: is.
15
Remarks: This extraction is performed as a series of simpler extractions. Therefore, the skipping of whitespace is specified to be the same for each of the simpler extractions. template basic_ostream& operator len(lv, 2), str(dv, 2); // v0[gslice(3, len, str)] returns // valarray("dfhkmo", 6)
— end example ] gslice_array operator[](const gslice& gslicearr); 5
Returns: An object that holds references to elements of the controlled sequence selected by gslicearr. [ Example: valarray v0("abcdefghijklmnop", 16); valarray v1("ABCDE", 5); const size_t lv[] = { 2, 3 }; const size_t dv[] = { 7, 2 }; const valarray<size_t> len(lv, 2), str(dv, 2); v0[gslice(3, len, str)] = v1; // v0 == valarray("abcAeBgCijDlEnFp", 16)
— end example ] valarray operator[](const valarray& boolarr) const; 6
Returns: An object of class valarray containing those elements of the controlled sequence designated by boolarr. [ Example: const valarray v0("abcdefghijklmnop", 16); const bool vb[] = { false, false, true, true, false, true }; // v0[valarray(vb, 6)] returns // valarray("cdf", 3)
— end example ] § 26.6.2.5
939
c ISO/IEC
N3376
mask_array operator[](const valarray& boolarr); 7
Returns: An object that holds references to elements of the controlled sequence selected by boolarr. [ Example: valarray v0("abcdefghijklmnop", 16); valarray v1("ABC", 3); const bool vb[] = { false, false, true, true, false, true }; v0[valarray(vb, 6)] = v1; // v0 == valarray("abABeCghijklmnop", 16)
— end example ] valarray operator[](const valarray<size_t>& indarr) const; 8
Returns: An object of class valarray containing those elements of the controlled sequence designated by indarr. [ Example: const valarray v0("abcdefghijklmnop", 16); const size_t vi[] = { 7, 5, 2, 3, 8 }; // v0[valarray<size_t>(vi, 5)] returns // valarray("hfcdi", 5)
— end example ] indirect_array operator[](const valarray<size_t>& indarr); 9
Returns: An object that holds references to elements of the controlled sequence selected by indarr. [ Example: valarray v0("abcdefghijklmnop", 16); valarray v1("ABCDE", 5); const size_t vi[] = { 7, 5, 2, 3, 8 }; v0[valarray<size_t>(vi, 5)] = v1; // v0 == valarray("abCDeBgAEjklmnop", 16)
— end example ] 26.6.2.6
valarray unary operators
[valarray.unary]
valarray operator+() const; valarray operator-() const; valarray operator~() const; valarray operator!() const; 1
Each of these operators may only be instantiated for a type T to which the indicated operator can be applied and for which the indicated operator returns a value which is of type T (bool for operator!) or which may be unambiguously implicitly converted to type T (bool for operator!).
2
Each of these operators returns an array whose length is equal to the length of the array. Each element of the returned array is initialized with the result of applying the indicated operator to the corresponding element of the array.
§ 26.6.2.6
940
c ISO/IEC
26.6.2.7
N3376
valarray computed assignment
valarray& valarray& valarray& valarray& valarray& valarray& valarray& valarray& valarray& valarray&
operator*= (const operator/= (const operator%= (const operator+= (const operator-= (const operator^= (const operator&= (const operator|= (const operator=(const
[valarray.cassign]
valarray&); valarray&); valarray&); valarray&); valarray&); valarray&); valarray&); valarray&); valarray&); valarray&);
1
Each of these operators may only be instantiated for a type T to which the indicated operator can be applied. Each of these operators performs the indicated operation on each of its elements and the corresponding element of the argument array.
2
The array is then returned by reference.
3
If the array and the argument array do not have the same length, the behavior is undefined. The appearance of an array on the left-hand side of a computed assignment does not invalidate references or pointers.
4
If the value of an element in the left-hand side of a valarray computed assignment operator depends on the value of another element in that left hand side, the resulting behavior is undefined. valarray& valarray& valarray& valarray& valarray& valarray& valarray& valarray& valarray& valarray&
operator*= (const operator/= (const operator%= (const operator+= (const operator-= (const operator^= (const operator&= (const operator|= (const operator=(const
T&); T&); T&); T&); T&); T&); T&); T&); T&); T&);
5
Each of these operators may only be instantiated for a type T to which the indicated operator can be applied.
6
Each of these operators applies the indicated operation to each element of the array and the non-array argument.
7
The array is then returned by reference.
8
The appearance of an array on the left-hand side of a computed assignment does not invalidate references or pointers to the elements of the array. 26.6.2.8
valarray member functions
[valarray.members]
void swap(valarray& v) noexcept; 1
Effects: *this obtains the value of v. v obtains the value of *this.
2
Complexity: Constant. size_t size() const;
§ 26.6.2.8
941
c ISO/IEC
3
Returns: The number of elements in the array.
4
Complexity: constant time.
N3376
T sum() const;
This function may only be instantiated for a type T to which operator+= can be applied. This function returns the sum of all the elements of the array. 5
If the array has length 0, the behavior is undefined. If the array has length 1, sum() returns the value of element 0. Otherwise, the returned value is calculated by applying operator+= to a copy of an element of the array and all other elements of the array in an unspecified order. T min() const;
6
This function returns the minimum value contained in *this. The value returned for an array of length 0 is undefined. For an array of length 1, the value of element 0 is returned. For all other array lengths, the determination is made using operator (const valarray&, const valarray&); template valarray operator= (const valarray&, const valarray&); template valarray operator&& (const valarray&, const valarray&); template valarray operator|| (const valarray&, const valarray&); 1
Each of these operators may only be instantiated for a type T to which the indicated operator can be applied and for which the indicated operator returns a value which is of type bool or which can be unambiguously implicitly converted to type bool.
2
Each of these operators returns a bool array whose length is equal to the length of the array arguments. Each element of the returned array is initialized with the result of applying the indicated operator to the corresponding elements of the argument arrays.
3
If the two array arguments do not have the same length, the behavior is undefined. template
valarray valarray valarray valarray valarray valarray valarray valarray valarray valarray valarray valarray valarray valarray valarray valarray
operator==(const operator==(const operator!=(const operator!=(const operator< (const operator< (const operator> (const operator> (const operator=(const operator&&(const operator&&(const operator||(const operator||(const
valarray&, const T&); T&, const valarray&); valarray&, const T&); T&, const valarray&); valarray&, const T&); T&, const valarray&); valarray&, const T&); T&, const valarray&); valarray&, const T&); T&, const valarray&); valarray&, const T&); T&, const valarray&); valarray&, const T&); T&, const valarray&); valarray&, const T&); T&, const valarray&);
Each of these operators may only be instantiated for a type T to which the indicated operator can be applied and for which the indicated operator returns a value which is of type bool or which can be unambiguously implicitly converted to type bool. § 26.6.3.2
944
c ISO/IEC
5
N3376
Each of these operators returns a bool array whose length is equal to the length of the array argument. Each element of the returned array is initialized with the result of applying the indicated operator to the corresponding element of the array and the non-array argument. 26.6.3.3
valarray transcendentals
[valarray.transcend]
template valarray abs (const valarray&); template valarray acos (const valarray&); template valarray asin (const valarray&); template valarray atan (const valarray&); template valarray atan2 (const valarray&, const valarray&); template valarray atan2(const valarray&, const T&); template valarray atan2(const T&, const valarray&); template valarray cos (const valarray&); template valarray cosh (const valarray&); template valarray exp (const valarray&); template valarray log (const valarray&); template valarray log10(const valarray&); template valarray pow (const valarray&, const valarray&); template valarray pow (const valarray&, const T&); template valarray pow (const T&, const valarray&); template valarray sin (const valarray&); template valarray sinh (const valarray&); template valarray sqrt (const valarray&); template valarray tan (const valarray&); template valarray tanh (const valarray&); 1
Each of these functions may only be instantiated for a type T to which a unique function with the indicated name can be applied (unqualified). This function shall return a value which is of type T or which can be unambiguously implicitly converted to type T. 26.6.3.4
valarray specialized algorithms
[valarray.special]
template void swap(valarray& x, valarray& y) noexcept; 1
Effects: x.swap(y).
26.6.4 26.6.4.1
Class slice Class slice overview
[class.slice] [class.slice.overview]
namespace std { class slice { public: slice(); slice(size_t, size_t, size_t); size_t start() const; size_t size() const; size_t stride() const; }; }
§ 26.6.4.1
945
c ISO/IEC
1
N3376
The slice class represents a BLAS-like slice from an array. Such a slice is specified by a starting index, a length, and a stride.286 26.6.4.2 slice constructors [cons.slice] slice(); slice(size_t start, size_t length, size_t stride); slice(const slice&);
1
The default constructor is equivalent to slice(0, 0, 0). A default constructor is provided only to permit the declaration of arrays of slices. The constructor with arguments for a slice takes a start, length, and stride parameter.
2
[ Example: slice(3, 8, 2) constructs a slice which selects elements 3, 5, 7, ... 17 from an array. — end example ] 26.6.4.3
slice access functions
[slice.access]
size_t start() const; size_t size() const; size_t stride() const; 1
Returns: The start, length, or stride specified by a slice object.
2
Complexity: constant time.
26.6.5
Class template slice_array
26.6.5.1
[template.slice.array]
Class template slice_array overview
[template.slice.array.overview]
namespace std { template class slice_array { public: typedef T value_type; void void void void void void void void void void void
operator= (const operator*= (const operator/= (const operator%= (const operator+= (const operator-= (const operator^= (const operator&= (const operator|= (const operator=(const
valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&)
const; const; const; const; const; const; const; const; const; const; const;
slice_array(const slice_array&); ~slice_array(); const slice_array& operator=(const slice_array&) const; void operator=(const T&) const; slice_array() = delete;
// as implied by declaring copy constructor above
}; } 286) BLAS stands for Basic Linear Algebra Subprograms. C++ programs may instantiate this class. See, for example, Dongarra, Du Croz, Duff, and Hammerling: A set of Level 3 Basic Linear Algebra Subprograms; Technical Report MCS-P1-0888, Argonne National Laboratory (USA), Mathematics and Computer Science Division, August, 1988.
§ 26.6.5.1
946
c ISO/IEC
1
N3376
The slice_array template is a helper template used by the slice subscript operator slice_array valarray::operator[](slice);
2
It has reference semantics to a subset of an array specified by a slice object. [ Example: The expression a[slice(1, 5, 3)] = b; has the effect of assigning the elements of b to a slice of the elements in a. For the slice shown, the elements selected from a are 1, 4, ..., 13. — end example ] 26.6.5.2 slice_array assignment [slice.arr.assign] void operator=(const valarray&) const; const slice_array& operator=(const slice_array&) const;
1
These assignment operators have reference semantics, assigning the values of the argument array elements to selected elements of the valarray object to which the slice_array object refers. 26.6.5.3 void void void void void void void void void void
1
slice_array computed assignment
operator*= (const operator/= (const operator%= (const operator+= (const operator-= (const operator^= (const operator&= (const operator|= (const operator=(const
valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&)
[slice.arr.comp.assign]
const; const; const; const; const; const; const; const; const; const;
These computed assignments have reference semantics, applying the indicated operation to the elements of the argument array and selected elements of the valarray object to which the slice_array object refers. 26.6.5.4
slice_array fill function
[slice.arr.fill]
void operator=(const T&) const; 1
This function has reference semantics, assigning the value of its argument to the elements of the valarray object to which the slice_array object refers.
26.6.6 26.6.6.1
The gslice class The gslice class overview
[class.gslice] [class.gslice.overview]
namespace std { class gslice { public: gslice(); gslice(size_t s, const valarray<size_t>& l, const valarray<size_t>& d); size_t start() const; valarray<size_t> size() const; valarray<size_t> stride() const; }; } 1
This class represents a generalized slice out of an array. A gslice is defined by a starting offset (s), a set of lengths (lj ), and a set of strides (dj ). The number of lengths shall equal the number of strides.
§ 26.6.6.1
947
c ISO/IEC
2
N3376
A gslice represents a mapping from a set of indices (ij ), equal in number to the number of strides, to a single index k. It is useful for building multidimensional array classes using the valarray template, which is one-dimensional. The set of one-dimensional index values specified by a gslice are X k =s+ ij dj j
3
where the multidimensional indices ij range in value from 0 to lij − 1. [ Example: The gslice specification start = 3 length = {2, 4, 3} stride = {19, 4, 1}
yields the sequence of one-dimensional indices k = 3 + (0, 1) × 19 + (0, 1, 2, 3) × 4 + (0, 1, 2) × 1 which are ordered as shown in the following table: (i0 , i1 , i2 , k) = (0, 0, 0, 3), (0, 0, 1, 4), (0, 0, 2, 5), (0, 1, 0, 7), (0, 1, 1, 8), (0, 1, 2, 9), (0, 2, 0, 11), (0, 2, 1, 12), (0, 2, 2, 13), (0, 3, 0, 15), (0, 3, 1, 16), (0, 3, 2, 17), (1, 0, 0, 22), (1, 0, 1, 23), ... (1, 3, 2, 36)
4 5
That is, the highest-ordered index turns fastest. — end example ] It is possible to have degenerate generalized slices in which an address is repeated. [ Example: If the stride parameters in the previous example are changed to {1, 1, 1}, the first few elements of the resulting sequence of indices will be (0, (0, (0, (0, (0, (0, ...
6
0, 0, 0, 1, 1, 1,
0, 1, 2, 0, 1, 2,
3), 4), 5), 4), 5), 6),
— end example ] If a degenerate slice is used as the argument to the non-const version of operator[](const gslice&), the resulting behavior is undefined. § 26.6.6.1
948
c ISO/IEC
26.6.6.2
N3376
gslice constructors
[gslice.cons]
gslice(); gslice(size_t start, const valarray<size_t>& lengths, const valarray<size_t>& strides); gslice(const gslice&); 1
The default constructor is equivalent to gslice(0, valarray<size_t>(), valarray<size_t>()). The constructor with arguments builds a gslice based on a specification of start, lengths, and strides, as explained in the previous section. 26.6.6.3
gslice access functions
[gslice.access]
size_t start() const; valarray<size_t> size() const; valarray<size_t> stride() const; 1
Returns: The representation of the start, lengths, or strides specified for the gslice.
2
Complexity: start() is constant time. size() and stride() are linear in the number of strides.
26.6.7
Class template gslice_array
26.6.7.1
[template.gslice.array]
Class template gslice_array overview
[template.gslice.array.overview]
namespace std { template class gslice_array { public: typedef T value_type; void void void void void void void void void void void
operator= (const operator*= (const operator/= (const operator%= (const operator+= (const operator-= (const operator^= (const operator&= (const operator|= (const operator=(const
valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&)
const; const; const; const; const; const; const; const; const; const; const;
gslice_array(const gslice_array&); ~gslice_array(); const gslice_array& operator=(const gslice_array&) const; void operator=(const T&) const; gslice_array() = delete;
// as implied by declaring copy constructor above
}; } 1
This template is a helper template used by the slice subscript operator gslice_array valarray::operator[](const gslice&);
2
It has reference semantics to a subset of an array specified by a gslice object.
3
Thus, the expression a[gslice(1, length, stride)] = b has the effect of assigning the elements of b to a generalized slice of the elements in a.
§ 26.6.7.1
949
c ISO/IEC
26.6.7.2
N3376
gslice_array assignment
[gslice.array.assign]
void operator=(const valarray&) const; const gslice_array& operator=(const gslice_array&) const; 1
These assignment operators have reference semantics, assigning the values of the argument array elements to selected elements of the valarray object to which the gslice_array refers. 26.6.7.3 void void void void void void void void void void
1
[gslice.array.comp.assign]
gslice_array
operator*= (const operator/= (const operator%= (const operator+= (const operator-= (const operator^= (const operator&= (const operator|= (const operator=(const
valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&)
const; const; const; const; const; const; const; const; const; const;
These computed assignments have reference semantics, applying the indicated operation to the elements of the argument array and selected elements of the valarray object to which the gslice_array object refers. 26.6.7.4
gslice_array fill function
[gslice.array.fill]
void operator=(const T&) const; 1
This function has reference semantics, assigning the value of its argument to the elements of the valarray object to which the gslice_array object refers.
26.6.8
Class template mask_array
26.6.8.1
[template.mask.array]
Class template mask_array overview
[template.mask.array.overview]
namespace std { template class mask_array { public: typedef T value_type; void void void void void void void void void void void
operator= (const operator*= (const operator/= (const operator%= (const operator+= (const operator-= (const operator^= (const operator&= (const operator|= (const operator=(const
valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&)
const; const; const; const; const; const; const; const; const; const; const;
mask_array(const mask_array&); ~mask_array(); const mask_array& operator=(const mask_array&) const; void operator=(const T&) const;
§ 26.6.8.1
950
c ISO/IEC
N3376
// as implied by declaring copy constructor above
mask_array() = delete; }; } 1
This template is a helper template used by the mask subscript operator: mask_array valarray::operator[](const valarray&).
2
It has reference semantics to a subset of an array specified by a boolean mask. Thus, the expression a[mask] = b; has the effect of assigning the elements of b to the masked elements in a (those for which the corresponding element in mask is true.) 26.6.8.2
mask_array assignment
[mask.array.assign]
void operator=(const valarray&) const; const mask_array& operator=(const mask_array&) const; 1
These assignment operators have reference semantics, assigning the values of the argument array elements to selected elements of the valarray object to which it refers. 26.6.8.3 void void void void void void void void void void
1
mask_array computed assignment
operator*= (const operator/= (const operator%= (const operator+= (const operator-= (const operator^= (const operator&= (const operator|= (const operator=(const
valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&)
[mask.array.comp.assign]
const; const; const; const; const; const; const; const; const; const;
These computed assignments have reference semantics, applying the indicated operation to the elements of the argument array and selected elements of the valarray object to which the mask object refers. 26.6.8.4
mask_array fill function
[mask.array.fill]
void operator=(const T&) const; 1
This function has reference semantics, assigning the value of its argument to the elements of the valarray object to which the mask_array object refers.
26.6.9
Class template indirect_array
26.6.9.1
Class template indirect_array overview
[template.indirect.array] [template.indirect.array.overview]
namespace std { template class indirect_array { public: typedef T value_type; void void void void void void void
§ 26.6.9.1
operator= operator*= operator/= operator%= operator+= operator-= operator^=
(const (const (const (const (const (const (const
valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&)
const; const; const; const; const; const; const;
951
c ISO/IEC
void void void void
N3376
operator&= (const operator|= (const operator=(const
valarray&) valarray&) valarray&) valarray&)
const; const; const; const;
indirect_array(const indirect_array&); ~indirect_array(); const indirect_array& operator=(const indirect_array&) const; void operator=(const T&) const; // as implied by declaring copy constructor above
indirect_array() = delete; }; } 1
This template is a helper template used by the indirect subscript operator indirect_array valarray::operator[](const valarray<size_t>&).
2
It has reference semantics to a subset of an array specified by an indirect_array. Thus the expression a[indirect] = b; has the effect of assigning the elements of b to the elements in a whose indices appear in indirect. 26.6.9.2
indirect_array assignment
[indirect.array.assign]
void operator=(const valarray&) const; const indirect_array& operator=(const indirect_array&) const; 1
These assignment operators have reference semantics, assigning the values of the argument array elements to selected elements of the valarray object to which it refers.
2
If the indirect_array specifies an element in the valarray object to which it refers more than once, the behavior is undefined.
3
[ Example: int addr[] = {2, 3, 1, 4, 4}; valarray<size_t> indirect(addr, 5); valarray<double> a(0., 10), b(1., 5); a[indirect] = b;
results in undefined behavior since element 4 is specified twice in the indirection. — end example ] 26.6.9.3 void void void void void void void void void void
indirect_array computed assignment
operator*= (const operator/= (const operator%= (const operator+= (const operator-= (const operator^= (const operator&= (const operator|= (const operator=(const
valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&)
[indirect.array.comp.assign]
const; const; const; const; const; const; const; const; const; const;
1
These computed assignments have reference semantics, applying the indicated operation to the elements of the argument array and selected elements of the valarray object to which the indirect_array object refers.
2
If the indirect_array specifies an element in the valarray object to which it refers more than once, the behavior is undefined. § 26.6.9.3
952
c ISO/IEC
26.6.9.4
N3376
indirect_array fill function
[indirect.array.fill]
void operator=(const T&) const; 1
This function has reference semantics, assigning the value of its argument to the elements of the valarray object to which the indirect_array object refers.
26.6.10 1
valarray range access
[valarray.range]
In the begin and end function templates that follow, unspecified 1 is a type that meets the requirements of a mutable random access iterator (24.2.7) whose value_type is the template parameter T and whose reference type is T&. unspecified 2 is a type that meets the requirements of a constant random access iterator (24.2.7) whose value_type is the template parameter T and whose reference type is const T&. template unspecified 1 begin(valarray& v); template unspecified 2 begin(const valarray& v);
2
Returns: An iterator referencing the first value in the numeric array. template unspecified 1 end(valarray& v); template unspecified 2 end(const valarray& v);
3
Returns: An iterator referencing one past the last value in the numeric array.
26.7 26.7.1
Generalized numeric operations Header synopsis
[numeric.ops] [numeric.ops.overview]
namespace std { template T accumulate(InputIterator first, InputIterator last, T init); template T accumulate(InputIterator first, InputIterator last, T init, BinaryOperation binary_op); template T inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init); template T inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2); template OutputIterator partial_sum(InputIterator first, InputIterator last, OutputIterator result); template OutputIterator partial_sum(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op); template
§ 26.7.1
953
c ISO/IEC
N3376
OutputIterator adjacent_difference(InputIterator first, InputIterator last, OutputIterator result); template OutputIterator adjacent_difference(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op); template void iota(ForwardIterator first, ForwardIterator last, T value); } 1
The requirements on the types of algorithms’ arguments that are described in the introduction to Clause 25 also apply to the following algorithms.
26.7.2
Accumulate
[accumulate]
template T accumulate(InputIterator first, InputIterator last, T init); template T accumulate(InputIterator first, InputIterator last, T init, BinaryOperation binary_op); 1
Effects: Computes its result by initializing the accumulator acc with the initial value init and then modifies it with acc = acc + *i or acc = binary_op(acc, *i) for every iterator i in the range [first,last) in order.287
2
Requires: T shall meet the requirements of CopyConstructible (Table 21) and CopyAssignable (Table 23) types. In the range [first,last], binary_op shall neither modify elements nor invalidate iterators or subranges.288
26.7.3
Inner product
[inner.product]
template T inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init); template T inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2); 1
Effects: Computes its result by initializing the accumulator acc with the initial value init and then modifying it with acc = acc + (*i1) * (*i2) or acc = binary_op1(acc, binary_op2(*i1, *i2)) for every iterator i1 in the range [first1,last1) and iterator i2 in the range [first2,first2 + (last1 - first1)) in order.
2
Requires: T shall meet the requirements of CopyConstructible (Table 21) and CopyAssignable (Table 23) types. In the ranges [first1,last1] and [first2,first2 + (last1 - first1)] binary_op1 and binary_op2 shall neither modify elements nor invalidate iterators or subranges.289 287) accumulate is similar to the APL reduction operator and Common Lisp reduce function, but it avoids the difficulty of defining the result of reduction on an empty sequence by always requiring an initial value. 288) The use of fully closed ranges is intentional 289) The use of fully closed ranges is intentional
§ 26.7.3
954
c ISO/IEC
26.7.4
N3376
Partial sum
[partial.sum]
template OutputIterator partial_sum( InputIterator first, InputIterator last, OutputIterator result); template OutputIterator partial_sum( InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op); 1
Effects: For a non-empty range, the function creates an accumulator acc whose type is InputIterator’s value type, initializes it with *first, and assigns the result to *result. For every iterator i in [first + 1,last) in order, acc is then modified by acc = acc + *i or acc = binary_op(acc, *i) and the result is assigned to *(result + (i - first)).
2
Returns: result + (last - first).
3
Complexity: Exactly (last - first) - 1 applications of the binary operation.
4
Requires: InputIterator’s value type shall be constructible from the type of *first. The result of the expression acc + *i or binary_op(acc, *i) shall be implicitly convertible to InputIterator’s value type. acc shall be writable to the result output iterator. In the ranges [first,last] and [result,result + (last - first)] binary_op shall neither modify elements nor invalidate iterators or subranges.290
5
Remarks: result may be equal to first.
26.7.5
Adjacent difference
[adjacent.difference]
template OutputIterator adjacent_difference( InputIterator first, InputIterator last, OutputIterator result); template OutputIterator adjacent_difference( InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op);
Effects: For a non-empty range, the function creates an accumulator acc whose type is InputIterator’s value type, initializes it with *first, and assigns the result to *result. For every iterator i in [first + 1,last) in order, creates an object val whose type is InputIterator’s value type, initializes it with *i, computes val - acc or binary_op(val, acc), assigns the result to *(result + (i - first)), and move assigns from val to acc. 1
Requires: InputIterator’s value type shall be MoveAssignable (Table 22) and shall be constructible from the type of *first. acc shall be writable to the result output iterator. The result of the expression val - acc or binary_op(val, acc) shall be writable to the result output iterator. In the ranges [first,last] and [result,result + (last - first)], binary_op shall neither modify elements nor invalidate iterators or subranges.291
2
Remarks: result may be equal to first.
3
Returns: result + (last - first).
4
Complexity: Exactly (last - first) - 1 applications of the binary operation. 290) The use of fully closed ranges is intentional. 291) The use of fully closed ranges is intentional.
§ 26.7.5
955
c ISO/IEC
26.7.6
N3376
Iota
[numeric.iota]
template void iota(ForwardIterator first, ForwardIterator last, T value); 1
Requires: T shall be convertible to ForwardIterator’s value type. The expression ++val, where val has type T, shall be well formed.
2
Effects: For each element referred to by the iterator i in the range [first,last), assigns *i = value and increments value as if by ++value.
3
Complexity: Exactly last - first increments and assignments.
26.8 1 2
3
C library
[c.math]
The header simply includes the headers and . [ Note: The overloads provided in C by magic macros are already provided in and by “sufficient” additional overloads. — end note ] Tables 119 and 120 describe headers and , respectively. Table 119 — Header synopsis Type Name(s) Macros: FP_FAST_FMA FP_ILOGBNAN FP_SUBNORMAL HUGE_VALL FP_FAST_FMAF FP_INFINITE FP_ZERO INFINITY FP_FAST_FMAL FP_NAN HUGE_VAL NAN FP_ILOGB0 FP_NORMAL HUGE_VALF Types: double_t float_t Math Functions: abs cosh fmod logb acos erf frexp lrint acosh erfc hypot lround asin exp2 ilogb modf asinh exp ldexp nan atan expm1 lgamma nanf atan2 fabs llrint nanl atanh fdim llround nearbyint cbrt floor log nextafter ceil fma log10 nexttoward copysign fmax log1p pow cos fmin log2 remainder Classification/comparison Functions: fpclassify isgreaterequal islessequal isnan isfinite isinf islessgreater isnormal isgreater isless
4
5
MATH_ERRNO MATH_ERREXCEPT math_errhandling
remquo rint round scalbln scalbn sin sinh sqrt tan tanh tgamma trunc isunordered signbit
The contents of these headers are the same as the Standard C library headers <math.h> and <stdlib.h> respectively, with the following changes: The rand function has the semantics specified in the C standard, except that the implementation may specify that particular library functions may call rand. It is implementation-defined whether the rand function may introduce data races (17.6.5.9). [ Note: The random number generation (26.5) facilities in this standard are often preferable to rand. — end note ] § 26.8
956
c ISO/IEC
N3376
Table 120 — Header synopsis Type Macro: Types: div_t Functions: abs div labs
6
7
9
ldiv_t
lldiv_t
ldiv llabs lldiv
rand srand
In addition to the int versions of certain math functions in , C++ adds long and long long overloaded versions of these functions, with the same semantics. The added signatures are: long abs(long); long long abs(long long); ldiv_t div(long, long); lldiv_t div(long long, long long);
8
Name(s) RAND_MAX
// // // //
labs() llabs() ldiv() lldiv()
In addition to the double versions of the math functions in , C++ adds float and long double overloaded versions of these functions, with the same semantics. The added signatures are: float abs(float); float acos(float); float acosh(float); float asin(float); float asinh(float); float atan(float); float atan2(float, float); float atanh(float); float cbrt(float); float ceil(float); float copysign(float, float); float cos(float); float cosh(float); float erf(float); float erfc(float); float exp(float); float exp2(float); float expm1(float); float fabs(float); float fdim(float, float); float floor(float); float fma(float, float, float); float fmax(float, float); float fmin(float, float); float fmod(float, float); float frexp(float, int*); float hypot(float, float); int ilogb(float); float ldexp(float, int);
§ 26.8
957
c ISO/IEC
N3376
float lgamma(float); long long llrint(float); long long llround(float); float log(float); float log10(float); float log1p(float); float log2(float); float logb(float); long lrint(float); long lround(float); float modf(float, float*); float nearbyint(float); float nextafter(float, float); float nexttoward(float, long double); float pow(float, float); float remainder(float, float); float remquo(float, float, int *); float rint(float); float round(float); float scalbln(float, long); float scalbn(float, int); float sin(float); float sinh(float); float sqrt(float); float tan(float); float tanh(float); float tgamma(float); float trunc(float); double abs(double); long long long long long long long long long long long long long long long long long long long long long long long long
§ 26.8
double double double double double double double double double double double double double double double double double double double double double double double double
// fabs()
abs(long double); acos(long double); acosh(long double); asin(long double); asinh(long double); atan(long double); atan2(long double, long double); atanh(long double); cbrt(long double); ceil(long double); copysign(long double, long double); cos(long double); cosh(long double); erf(long double); erfc(long double); exp(long double); exp2(long double); expm1(long double); fabs(long double); fdim(long double, long double); floor(long double); fma(long double, long double, long double); fmax(long double, long double); fmin(long double, long double);
958
c ISO/IEC
N3376
long double fmod(long double, long double); long double frexp(long double, int*); long double hypot(long double, long double); int ilogb(long double); long double ldexp(long double, int); long double lgamma(long double); long long llrint(long double); long long llround(long double); long double log(long double); long double log10(long double); long double log1p(long double); long double log2(long double); long double logb(long double); long lrint(long double); long lround(long double); long double modf(long double, long double*); long double nearbyint(long double); long double nextafter(long double, long double); long double nexttoward(long double, long double); long double pow(long double, long double); long double remainder(long double, long double); long double remquo(long double, long double, int *); long double rint(long double); long double round(long double); long double scalbln(long double, long); long double scalbn(long double, int); long double sin(long double); long double sinh(long double); long double sqrt(long double); long double tan(long double); long double tanh(long double); long double tgamma(long double); long double trunc(long double); 10
The classification/comparison functions behave the same as the C macros with the corresponding names defined in 7.12.3, Classification macros, and 7.12.14, Comparison macros in the C Standard. Each function is overloaded for the three floating-point types, as follows: int fpclassify(float x); bool isfinite(float x); bool isinf(float x); bool isnan(float x); bool isnormal(float x); bool signbit(float x); bool bool bool bool bool bool
isgreater(float x, float y); isgreaterequal(float x, float y); isless(float x, float y); islessequal(float x, float y); islessgreater(float x, float y); isunordered(float x, float y);
int fpclassify(double x); bool isfinite(double x); bool isinf(double x); bool isnan(double x);
§ 26.8
959
c ISO/IEC
N3376
bool isnormal(double x); bool signbit(double x); bool bool bool bool bool bool
isgreater(double x, double y); isgreaterequal(double x, double y); isless(double x, double y); islessequal(double x, double y); islessgreater(double x, double y); isunordered(double x, double y);
int fpclassify(long double x); bool isfinite(long double x); bool isinf(long double x); bool isnan(long double x); bool isnormal(long double x); bool signbit(long double x); bool bool bool bool bool bool 11
isgreater(long double x, long double y); isgreaterequal(long double x, long double y); isless(long double x, long double y); islessequal(long double x, long double y); islessgreater(long double x, long double y); isunordered(long double x, long double y);
Moreover, there shall be additional overloads sufficient to ensure: 1. If any argument corresponding to a double parameter has type long double, then all arguments corresponding to double parameters are effectively cast to long double. 2. Otherwise, if any argument corresponding to a double parameter has type double or an integer type, then all arguments corresponding to double parameters are effectively cast to double. 3. Otherwise, all arguments corresponding to double parameters are effectively cast to float. See also: ISO C 7.5, 7.10.2, 7.10.6.
§ 26.8
960
c ISO/IEC
27 27.1 1 2
N3376
Input/output library
[input.output]
General
[input.output.general]
This Clause describes components that C++ programs may use to perform input/output operations. The following subclauses describe requirements for stream parameters, and components for forward declarations of iostreams, predefined iostreams objects, base iostreams classes, stream buffering, stream formatting and manipulators, string streams, and file streams, as summarized in Table 121. Table 121 — Input/output library summary
3
27.2 27.3 27.4 27.5 27.6 27.7
Subclause Requirements Forward declarations Standard iostream objects Iostreams base classes Stream buffers Formatting and manipulators
27.8 27.9
String streams File streams
Header(s) <streambuf> <sstream>
Figure 7 illustrates relationships among various types described in this clause. A line from A to B indicates that A is an alias (e.g. a typedef) for B or that A is defined in terms of B.
char_traits ::pos_type
char_traits<wchar_t> ::pos_type
iostreams.limits.pos
streampos
iostreams.limits.pos
wstreampos
iostream.forward
iostream.forward
fpos<mbstate_t>
char_traits ::off_type
char_traits<wchar_t> ::off_type
iostreams.limits.pos
streamoff
streamsize
iostreams.limits.pos
stream.types
signed integer type represents characters xfered or buffer sizes
stream.types
signed integer type sufficient for O/S maximum file size
Figure 7 — Stream position, offset, and size types [non-normative]
27.2 Iostreams requirements 27.2.1 Imbue limitations 1
[iostreams.requirements] [iostream.limits.imbue]
No function described in Clause 27 except for ios_base::imbue and basic_filebuf::pubimbue causes any § 27.2.1
961
c ISO/IEC
N3376
instance of basic_ios::imbue or basic_streambuf::imbue to be called. If any user function called from a function declared in Clause 27 or as an overriding virtual function of any class declared in Clause 27 calls imbue, the behavior is undefined.
27.2.2 1
2
2
[iostreams.limits.pos]
The classes of Clause 27 with template arguments charT and traits behave as described if traits::pos_type and traits::off_type are streampos and streamoff respectively. Except as noted explicitly below, their behavior when traits::pos_type and traits::off_type are other types is implementation-defined. In the classes of Clause 27, a template formal parameter with name charT represents a member of the set of types containing char, wchar_t, and any other implementation-defined character types that satisfy the requirements for a character on which any of the iostream components can be instantiated.
27.2.3 1
Positioning type limitations
Thread safety
[iostreams.threadsafety]
Concurrent access to a stream object (27.8, 27.9), stream buffer object (27.6), or C Library stream (27.9.2) by multiple threads may result in a data race (1.10) unless otherwise specified (27.4). [ Note: Data races result in undefined behavior (1.10). — end note ] If one thread makes a library call a that writes a value to a stream and, as a result, another thread reads this value from the stream through a library call b such that this does not result in a data race, then a’s write synchronizes with b’s read.
27.3
Forward declarations
[iostream.forward]
Header synopsis namespace std { template class char_traits; template class char_traits; template class char_traits; template class char_traits; template class char_traits<wchar_t>; template class allocator; template
template class basic_stringbuf; template class basic_istringstream; template class basic_ostringstream; template class basic_stringstream;
§ 27.3
962
c ISO/IEC
N3376
template
template class istreambuf_iterator; template class ostreambuf_iterator; typedef basic_ios typedef basic_ios<wchar_t>
ios; wios;
typedef typedef typedef typedef
basic_streambuf basic_istream basic_ostream basic_iostream
streambuf; istream; ostream; iostream;
typedef typedef typedef typedef
basic_stringbuf basic_istringstream basic_ostringstream basic_stringstream
typedef typedef typedef typedef
basic_filebuf basic_ifstream basic_ofstream basic_fstream
typedef typedef typedef typedef
basic_streambuf<wchar_t> basic_istream<wchar_t> basic_ostream<wchar_t> basic_iostream<wchar_t>
typedef typedef typedef typedef
basic_stringbuf<wchar_t> basic_istringstream<wchar_t> basic_ostringstream<wchar_t> basic_stringstream<wchar_t>
typedef typedef typedef typedef
basic_filebuf<wchar_t> basic_ifstream<wchar_t> basic_ofstream<wchar_t> basic_fstream<wchar_t>
stringbuf; istringstream; ostringstream; stringstream;
filebuf; ifstream; ofstream; fstream; wstreambuf; wistream; wostream; wiostream; wstringbuf; wistringstream; wostringstream; wstringstream;
wfilebuf; wifstream; wofstream; wfstream;
template class fpos; typedef fpos streampos; typedef fpos::state_type> wstreampos; } 1
Default template arguments are described as appearing both in and in the synopsis of other headers but it is well-formed to include both and one or more of the other headers.292 292) It is the implementation’s responsibility to implement headers so that including and other headers does not
§ 27.3
963
c ISO/IEC
2
3
4
5
6
7 8 9
10
N3376
[ Note: The class template specialization basic_ios serves as a virtual base class for the class templates basic_istream, basic_ostream, and class templates derived from them. basic_iostream is a class template derived from both basic_istream and basic_ostream. The class template specialization basic_streambuf serves as a base class for class templates basic_stringbuf and basic_filebuf. The class template specialization basic_istream serves as a base class for class templates basic_istringstream and basic_ifstream. The class template specialization basic_ostream serves as a base class for class templates basic_ostringstream and basic_ofstream. The class template specialization basic_iostream serves as a base class for class templates basic_stringstream and basic_fstream. Other typedefs define instances of class templates specialized for char or wchar_t types. Specializations of the class template fpos are used for specifying file position information. The types streampos and wstreampos are used for positioning streams specialized on char and wchar_t respectively. This synopsis suggests a circularity between streampos and char_traits. An implementation can avoid this circularity by substituting equivalent types. One way to do this might be template class fpos { ... }; // depends on nothing typedef ... _STATE; // implementation private declaration of stateT typedef fpos streampos; template struct char_traits { typedef streampos pos_type; }
— end note ]
27.4 27.4.1
Standard iostream objects Overview
[iostream.objects] [iostream.objects.overview]
Header synopsis #include #include #include #include
<streambuf>
namespace std { extern istream extern ostream extern ostream extern ostream extern extern extern extern
wistream wostream wostream wostream
cin; cout; cerr; clog; wcin; wcout; wcerr; wclog;
} 1
The header declares objects that associate objects with the standard C streams provided for by the functions declared in (27.9.2), and includes all the headers necessary to use these objects. violate the rules about multiple occurrences of default arguments.
§ 27.4.1
964
c ISO/IEC
2
3
4
N3376
The objects are constructed and the associations are established at some time prior to or during the first time an object of class ios_base::Init is constructed, and in any case before the body of main begins execution.293 The objects are not destroyed during program execution.294 The results of including in a translation unit shall be as if defined an instance of ios_base::Init with static storage duration. Similarly, the entire program shall behave as if there were at least one instance of ios_base::Init with static storage duration. Mixing operations on corresponding wide- and narrow-character streams follows the same semantics as mixing such operations on FILEs, as specified in Amendment 1 of the ISO C standard. Concurrent access to a synchronized (27.5.3.4) standard iostream object’s formatted and unformatted input (27.7.2.1) and output (27.7.3.1) functions or a standard C stream by multiple threads shall not result in a data race (1.10). [ Note: Users must still synchronize concurrent use of these objects and streams by multiple threads if they wish to avoid interleaved characters. — end note ]
27.4.2
Narrow stream objects
[narrow.stream.objects]
istream cin; 1
The object cin controls input from a stream buffer associated with the object stdin, declared in .
2
After the object cin is initialized, cin.tie() returns &cout. Its state is otherwise the same as required for basic_ios::init (27.5.5.2). ostream cout;
3
The object cout controls output to a stream buffer associated with the object stdout, declared in (27.9.2). ostream cerr;
4
The object cerr controls output to a stream buffer associated with the object stderr, declared in (27.9.2).
5
After the object cerr is initialized, cerr.flags() & unitbuf is nonzero and cerr.tie() returns &cout. Its state is otherwise the same as required for basic_ios::init (27.5.5.2). ostream clog;
6
The object clog controls output to a stream buffer associated with the object stderr, declared in (27.9.2).
27.4.3
Wide stream objects
[wide.stream.objects]
wistream wcin; 1
The object wcin controls input from a stream buffer associated with the object stdin, declared in .
2
After the object wcin is initialized, wcin.tie() returns &wcout. Its state is otherwise the same as required for basic_ios<wchar_t>::init (27.5.5.2). 293) If it is possible for them to do so, implementations are encouraged to initialize the objects earlier than required. 294) Constructors and destructors for static objects can access these objects to read input from stdin or write output to stdout
or stderr.
§ 27.4.3
965
c ISO/IEC
N3376
wostream wcout; 3
The object wcout controls output to a stream buffer associated with the object stdout, declared in (27.9.2). wostream wcerr;
4
The object wcerr controls output to a stream buffer associated with the object stderr, declared in (27.9.2).
5
After the object wcerr is initialized, wcerr.flags() & unitbuf is nonzero and wcerr.tie() returns &wcout. Its state is otherwise the same as required for basic_ios<wchar_t>::init (27.5.5.2). wostream wclog;
6
The object wclog controls output to a stream buffer associated with the object stderr, declared in (27.9.2).
27.5 27.5.1
Iostreams base classes Overview
[iostreams.base] [iostreams.base.overview]
Header synopsis #include namespace std { typedef implementation-defined streamoff; typedef implementation-defined streamsize; template class fpos; class ios_base; template class basic_ios; // 27.5.6, manipulators: ios_base& boolalpha (ios_base& str); ios_base& noboolalpha(ios_base& str); ios_base& showbase (ios_base& str); ios_base& noshowbase (ios_base& str); ios_base& showpoint (ios_base& str); ios_base& noshowpoint(ios_base& str); ios_base& showpos ios_base& noshowpos
(ios_base& str); (ios_base& str);
ios_base& skipws ios_base& noskipws
(ios_base& str); (ios_base& str);
ios_base& uppercase (ios_base& str); ios_base& nouppercase(ios_base& str); ios_base& unitbuf
§ 27.5.1
(ios_base& str);
966
c ISO/IEC
ios_base& nounitbuf
N3376
(ios_base& str);
// 27.5.6.2 adjustfield: ios_base& internal (ios_base& str); ios_base& left (ios_base& str); ios_base& right (ios_base& str); // 27.5.6.3 basefield: ios_base& dec ios_base& hex ios_base& oct
(ios_base& str); (ios_base& str); (ios_base& str);
// 27.5.6.4 floatfield: ios_base& fixed (ios_base& str); ios_base& scientific (ios_base& str); ios_base& hexfloat (ios_base& str); ios_base& defaultfloat(ios_base& str); // 27.5.6.5 error reporting: enum class io_errc { stream = 1 }; template struct is_error_code_enum : public true_type { }; error_code make_error_code(io_errc e); error_condition make_error_condition(io_errc e); const error_category& iostream_category(); }
27.5.2
Types
[stream.types]
typedef implementation-defined streamoff; 1
The type streamoff is a synonym for one of the signed basic integral types of sufficient size to represent the maximum possible file size for the operating system.295 typedef implementation-defined streamsize;
2
The type streamsize is a synonym for one of the signed basic integral types. It is used to represent the number of characters transferred in an I/O operation, or the size of I/O buffers.296
27.5.3
Class ios_base
[ios.base]
namespace std { class ios_base { public: class failure; // 27.5.3.1.2 fmtflags typedef T1 fmtflags; static constexpr fmtflags boolalpha = unspecified ; 295) Typically long long. 296) streamsize is used in most places where ISO C would use size_t. Most of the uses of streamsize could use size_t,
except for the strstreambuf constructors, which require negative values. It should probably be the signed type corresponding to size_t (which is what Posix.2 calls ssize_t).
§ 27.5.3
967
c ISO/IEC
static static static static static static static static static static static static static static static static static
N3376
constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr
fmtflags fmtflags fmtflags fmtflags fmtflags fmtflags fmtflags fmtflags fmtflags fmtflags fmtflags fmtflags fmtflags fmtflags fmtflags fmtflags fmtflags
// 27.5.3.1.3 iostate typedef T2 iostate; static constexpr iostate static constexpr iostate static constexpr iostate static constexpr iostate
dec = unspecified ; fixed = unspecified ; hex = unspecified ; internal = unspecified ; left = unspecified ; oct = unspecified ; right = unspecified ; scientific = unspecified ; showbase = unspecified ; showpoint = unspecified ; showpos = unspecified ; skipws = unspecified ; unitbuf = unspecified ; uppercase = unspecified ; adjustfield = see below ; basefield = see below ; floatfield = see below ;
badbit = unspecified ; eofbit = unspecified ; failbit = unspecified ; goodbit = see below ;
// 27.5.3.1.4 openmode typedef T3 openmode; static constexpr openmode static constexpr openmode static constexpr openmode static constexpr openmode static constexpr openmode static constexpr openmode
app = unspecified ; ate = unspecified ; binary = unspecified ; in = unspecified ; out = unspecified ; trunc = unspecified ;
// 27.5.3.1.5 seekdir typedef T4 seekdir; static constexpr fmtflags beg = unspecified ; static constexpr fmtflags cur = unspecified ; static constexpr fmtflags end = unspecified ; class Init; // 27.5.3.2 fmtflags state: fmtflags flags() const; fmtflags flags(fmtflags fmtfl); fmtflags setf(fmtflags fmtfl); fmtflags setf(fmtflags fmtfl, fmtflags mask); void unsetf(fmtflags mask); streamsize streamsize streamsize streamsize
precision() const; precision(streamsize prec); width() const; width(streamsize wide);
// 27.5.3.3 locales:
§ 27.5.3
968
c ISO/IEC
N3376
locale imbue(const locale& loc); locale getloc() const; // 27.5.3.5 storage: static int xalloc(); long& iword(int index); void*& pword(int index); // destructor virtual ~ios_base(); // 27.5.3.6 callbacks; enum event { erase_event, imbue_event, copyfmt_event }; typedef void (*event_callback)(event, ios_base&, int index); void register_callback(event_callback fn, int index); ios_base(const ios_base&) = delete; ios_base& operator=(const ios_base&) = delete; static bool sync_with_stdio(bool sync = true); protected: ios_base(); private: static int index; long* iarray; void** parray; };
// exposition only // exposition only // exposition only
} 1
ios_base defines several member types: — a class failure derived from system_error; — a class Init; — three bitmask types, fmtflags, iostate, and openmode; — an enumerated type, seekdir.
2
It maintains several kinds of data: — state information that reflects the integrity of the stream buffer; — control information that influences how to interpret (format) input sequences and how to generate (format) output sequences; — additional information that is stored by the program for its private use.
3
[ Note: For the sake of exposition, the maintained data is presented here as: — static int index, specifies the next available unique index for the integer or pointer arrays maintained for the private use of the program, initialized to an unspecified value; — long* iarray, points to the first element of an arbitrary-length long array maintained for the private use of the program; — void** parray, points to the first element of an arbitrary-length pointer array maintained for the private use of the program. — end note ] § 27.5.3
969
c ISO/IEC
27.5.3.1 27.5.3.1.1
N3376
Types Class ios_base::failure
[ios.types] [ios::failure]
namespace std { class ios_base::failure : public system_error { public: explicit failure(const string& msg, const error_code& ec = io_errc::stream); explicit failure(const char* msg, const error_code& ec = io_errc::stream); }; } 1
2
The class failure defines the base class for the types of all objects thrown as exceptions, by functions in the iostreams library, to report errors detected during stream buffer operations. When throwing ios_base::failure exceptions, implementations should provide values of ec that identify the specific reason for the failure. [ Note: Errors arising from the operating system would typically be reported as system_category() errors with an error value of the error number reported by the operating system. Errors arising from within the stream library would typically be reported as error_code(io_errc::stream, iostream_category()). — end note ] explicit failure(const string& msg, , const error_code& ec = io_errc::stream);
3
Effects: Constructs an object of class failure by constructing the base class with msg and ec. explicit failure(const char* msg, const error_code& ec = io_errc::stream);
4
Effects: Constructs an object of class failure by constructing the base class with msg and ec. 27.5.3.1.2
Type ios_base::fmtflags
[ios::fmtflags]
typedef T1 fmtflags; 1
The type fmtflags is a bitmask type (17.5.2.1.3). Setting its elements has the effects indicated in Table 122.
2
Type fmtflags also defines the constants indicated in Table 123. 27.5.3.1.3
Type ios_base::iostate
[ios::iostate]
typedef T2 iostate; 1
The type iostate is a bitmask type (17.5.2.1.3) that contains the elements indicated in Table 124.
2
Type iostate also defines the constant: — goodbit, the value zero. 27.5.3.1.4
Type ios_base::openmode
[ios::openmode]
typedef T3 openmode; 1
The type openmode is a bitmask type (17.5.2.1.3). It contains the elements indicated in Table 125. 27.5.3.1.5
Type ios_base::seekdir
[ios::seekdir]
typedef T4 seekdir; 1
The type seekdir is an enumerated type (17.5.2.1.2) that contains the elements indicated in Table 126.
§ 27.5.3.1.5
970
c ISO/IEC
N3376
Table 122 — fmtflags effects Element boolalpha dec fixed hex internal left oct right scientific showbase showpoint showpos skipws unitbuf uppercase
Effect(s) if set insert and extract bool type in alphabetic format converts integer input or generates integer output in decimal base generate floating-point output in fixed-point notation converts integer input or generates integer output in hexadecimal base adds fill characters at a designated internal point in certain generated output, or identical to right if no such point is designated adds fill characters on the right (final positions) of certain generated output converts integer input or generates integer output in octal base adds fill characters on the left (initial positions) of certain generated output generates floating-point output in scientific notation generates a prefix indicating the numeric base of generated integer output generates a decimal-point character unconditionally in generated floatingpoint output generates a + sign in non-negative generated numeric output skips leading whitespace before certain input operations flushes output after each output operation replaces certain lowercase letters with their uppercase equivalents in generated output
Table 123 — fmtflags constants Constant adjustfield basefield floatfield
Allowable values left | right | internal dec | oct | hex scientific | fixed
Table 124 — iostate effects Element badbit eofbit failbit
Effect(s) if set indicates a loss of integrity in an input or output sequence (such as an irrecoverable read error from a file); indicates that an input operation reached the end of an input sequence; indicates that an input operation failed to read the expected characters, or that an output operation failed to generate the desired characters.
Table 125 — openmode effects Element app ate binary in out trunc
§ 27.5.3.1.5
Effect(s) if set seek to end before each write open and seek to end immediately after opening perform input and output in binary mode (as opposed to text mode) open for input open for output truncate an existing stream when opening
971
c ISO/IEC
N3376
Table 126 — seekdir effects Element beg cur end
27.5.3.1.6
Meaning request a seek (for subsequent input or output) relative to the beginning of the stream request a seek relative to the current position within the sequence request a seek relative to the current end of the sequence
Class ios_base::Init
[ios::Init]
namespace std { class ios_base::Init { public: Init(); ~Init(); private: static int init_cnt; // exposition only }; } 1
2
The class Init describes an object whose construction ensures the construction of the eight objects declared in (27.4) that associate file stream buffers with the standard C streams provided for by the functions declared in (27.9.2). For the sake of exposition, the maintained data is presented here as: — static int init_cnt, counts the number of constructor and destructor calls for class Init, initialized to zero. Init();
3
Effects: Constructs an object of class Init. Constructs and initializes the objects cin, cout, cerr, clog, wcin, wcout, wcerr, and wclog if they have not already been constructed and initialized. ~Init();
4
Effects: Destroys an object of class Init. If there are no other instances of the class still in existence, calls cout.flush(), cerr.flush(), clog.flush(), wcout.flush(), wcerr.flush(), wclog.flush(). 27.5.3.2
ios_base state functions
[fmtflags.state]
fmtflags flags() const; 1
Returns: The format control information for both input and output. fmtflags flags(fmtflags fmtfl);
2
Postcondition: fmtfl == flags().
3
Returns: The previous value of flags(). fmtflags setf(fmtflags fmtfl);
§ 27.5.3.2
972
c ISO/IEC
4
Effects: Sets fmtfl in flags().
5
Returns: The previous value of flags().
N3376
fmtflags setf(fmtflags fmtfl, fmtflags mask); 6
Effects: Clears mask in flags(), sets fmtfl & mask in flags().
7
Returns: The previous value of flags(). void unsetf(fmtflags mask);
8
Effects: Clears mask in flags(). streamsize precision() const;
9
Returns: The precision to generate on certain output conversions. streamsize precision(streamsize prec);
10
Postcondition: prec == precision().
11
Returns: The previous value of precision(). streamsize width() const;
12
Returns: The minimum field width (number of characters) to generate on certain output conversions. streamsize width(streamsize wide);
13
Postcondition: wide == width().
14
Returns: The previous value of width(). 27.5.3.3
ios_base functions
[ios.base.locales]
locale imbue(const locale& loc); 1
Effects: Calls each registered callback pair (fn,index) (27.5.3.6) as (*fn)(imbue_event,*this,index) at such a time that a call to ios_base::getloc() from within fn returns the new locale value loc.
2
Returns: The previous value of getloc().
3
Postcondition: loc == getloc(). locale getloc() const;
4
Returns: If no locale has been imbued, a copy of the global C++ locale, locale(), in effect at the time of construction. Otherwise, returns the imbued locale, to be used to perform locale-dependent input and output operations.
§ 27.5.3.3
973
c ISO/IEC
27.5.3.4
ios_base static members
N3376
[ios.members.static]
bool sync_with_stdio(bool sync = true); 1
Returns: true if the previous state of the standard iostream objects (27.4) was synchronized and otherwise returns false. The first time it is called, the function returns true.
2
Effects: If any input or output operation has occurred using the standard streams prior to the call, the effect is implementation-defined. Otherwise, called with a false argument, it allows the standard streams to operate independently of the standard C streams.
3
When a standard iostream object str is synchronized with a standard stdio stream f, the effect of inserting a character c by fputc(f, c);
is the same as the effect of str.rdbuf()->sputc(c);
for any sequences of characters; the effect of extracting a character c by c = fgetc(f);
is the same as the effect of c = str.rdbuf()->sbumpc(c);
for any sequences of characters; and the effect of pushing back a character c by ungetc(c, f);
is the same as the effect of str.rdbuf()->sputbackc(c);
for any sequence of characters.297 27.5.3.5
ios_base storage functions
[ios.base.storage]
static int xalloc(); 1
Returns: index ++. long& iword(int idx);
2
Effects: If iarray is a null pointer, allocates an array of long of unspecified size and stores a pointer to its first element in iarray. The function then extends the array pointed at by iarray as necessary to include the element iarray[idx]. Each newly allocated element of the array is initialized to zero. The reference returned is invalid after any other operations on the object.298 However, the value of the storage referred to is retained, so that until the next call to copyfmt, calling iword with the same index yields another reference to the same value. If the function fails299 and *this is a base subobject of a basic_ios object or subobject, the effect is equivalent to calling basic_ios::setstate(badbit) on the derived object (which may throw failure).
3
Returns: On success iarray[idx]. On failure, a valid long& initialized to 0. 297) This implies that operations on a standard iostream object can be mixed arbitrarily with operations on the corresponding stdio stream. In practical terms, synchronization usually means that a standard iostream object and a standard stdio object share a buffer. 298) An implementation is free to implement both the integer array pointed at by iarray and the pointer array pointed at by parray as sparse data structures, possibly with a one-element cache for each. 299) for example, because it cannot allocate space.
§ 27.5.3.5
974
c ISO/IEC
N3376
void*& pword(int idx); 4
Effects: If parray is a null pointer, allocates an array of pointers to void of unspecified size and stores a pointer to its first element in parray. The function then extends the array pointed at by parray as necessary to include the element parray[idx]. Each newly allocated element of the array is initialized to a null pointer. The reference returned is invalid after any other operations on the object. However, the value of the storage referred to is retained, so that until the next call to copyfmt, calling pword with the same index yields another reference to the same value. If the function fails300 and *this is a base subobject of a basic_ios object or subobject, the effect is equivalent to calling basic_ios::setstate(badbit) on the derived object (which may throw failure).
5
Returns: On success parray[idx]. On failure a valid void*& initialized to 0.
6
Remarks: After a subsequent call to pword(int) for the same object, the earlier return value may no longer be valid. 27.5.3.6
ios_base callbacks
[ios.base.callback]
void register_callback(event_callback fn, int index); 1
Effects: Registers the pair (fn,index) such that during calls to imbue() (27.5.3.3), copyfmt(), or ˜ios_base() (27.5.3.7), the function fn is called with argument index. Functions registered are called when an event occurs, in opposite order of registration. Functions registered while a callback function is active are not called until the next event.
2
Requires: The function fn shall not throw exceptions. Remarks: Identical pairs are not merged. A function registered twice will be called twice. 27.5.3.7
ios_base constructors/destructor
[ios.base.cons]
ios_base(); 1
Effects: Each ios_base member has an indeterminate value after construction. The object’s members shall be initialized by calling basic_ios::init before the object’s first use or before it is destroyed, whichever comes first; otherwise the behavior is undefined. ~ios_base()
2
Effects: Destroys an object of class ios_base. Calls each registered callback pair (fn, index) (27.5.3.6) as (*fn)(erase_event, *this, index) at such time that any ios_base member function called from within fn has well defined results.
27.5.4
Class template fpos
[fpos]
namespace std { template class fpos { public: // 27.5.4.1 Members stateT state() const; void state(stateT); private; stateT st; // exposition only }; } 300) for example, because it cannot allocate space.
§ 27.5.4
975
c ISO/IEC
27.5.4.1
N3376
fpos members
[fpos.members]
void state(stateT s); 1
Effects: Assign s to st. stateT state() const;
2
Returns: Current value of st. 27.5.4.2
1
fpos requirements
[fpos.operations]
Operations specified in Table 127 are permitted. In that table, — P refers to an instance of fpos, — p and q refer to values of type P, — O refers to type streamoff, — o refers to a value of type streamoff, — sz refers to a value of type streamsize and — i refers to a value of type int. Table 127 — Position type requirements Expression
Return type
Operational semantics
P(i) P p(i); P p = i; P(o) O(p) p == q p != q q = p + o p += o q = p - o p -= o o = p - q streamsize(o) O(sz) 2
3
converts from offset converts to offset
Assertion/note pre-/post-condition p == P(i) note: a destructor is assumed. post: p == P(i).
fpos streamoff convertible to bool convertible to bool fpos
!(p == q) + offset
q - o == p
fpos
- offset
q + o == p
streamoff streamsize streamoff
distance converts converts
q + o == p streamsize(O(sz)) == sz streamsize(O(sz)) == sz
P(O(p)) == p == is an equivalence relation
[ Note: Every implementation is required to supply overloaded operators on fpos objects to satisfy the requirements of 27.5.4.2. It is unspecified whether these operators are members of fpos, global operators, or provided in some other way. — end note ] Stream operations that return a value of type traits::pos_type return P(O(-1)) as an invalid value to signal an error. If this value is used as an argument to any istream, ostream, or streambuf member that accepts a value of type traits::pos_type then the behavior of that function is undefined.
§ 27.5.4.2
976
c ISO/IEC
27.5.5 27.5.5.1
Class template basic_ios Overview
N3376
[ios] [ios.overview]
namespace std { template class basic_ios : public ios_base { public: // types: typedef charT char_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; typedef traits traits_type; explicit operator bool() const; bool operator!() const; iostate rdstate() const; void clear(iostate state = goodbit); void setstate(iostate state); bool good() const; bool eof() const; bool fail() const; bool bad() const; iostate exceptions() const; void exceptions(iostate except); // 27.5.5.2 Constructor/destructor: explicit basic_ios(basic_streambuf* sb); virtual ~basic_ios(); // 27.5.5.3 Members: basic_ostream* tie() const; basic_ostream* tie(basic_ostream* tiestr); basic_streambuf* rdbuf() const; basic_streambuf* rdbuf(basic_streambuf* sb); basic_ios& copyfmt(const basic_ios& rhs); char_type fill() const; char_type fill(char_type ch); locale imbue(const locale& loc); char narrow(char_type c, char dfault) const; char_type widen(char c) const; basic_ios(const basic_ios& ) = delete; basic_ios& operator=(const basic_ios&) = delete; protected: basic_ios(); void init(basic_streambuf* sb);
§ 27.5.5.1
977
c ISO/IEC
void void void void
N3376
move(basic_ios& rhs); move(basic_ios&& rhs); swap(basic_ios& rhs) noexcept; set_rdbuf(basic_streambuf* sb);
}; }
27.5.5.2
basic_ios constructors
[basic.ios.cons]
explicit basic_ios(basic_streambuf* sb); 1
Effects: Constructs an object of class basic_ios, assigning initial values to its member objects by calling init(sb). basic_ios();
2
Effects: Constructs an object of class basic_ios (27.5.3.7) leaving its member objects uninitialized. The object shall be initialized by calling basic_ios::init before its first use or before it is destroyed, whichever comes first; otherwise the behavior is undefined. ~basic_ios();
3
Remarks: The destructor does not destroy rdbuf(). void init(basic_streambuf* sb);
Postconditions: The postconditions of this function are indicated in Table 128. Table 128 — basic_ios::init() effects Element rdbuf() tie() rdstate() exceptions() flags() width() precision() fill() getloc() iarray parray
27.5.5.3
Value sb 0 goodbit if sb is not a null pointer, otherwise badbit. goodbit skipws | dec 0 6 widen(’ ’); a copy of the value returned by locale() a null pointer a null pointer
Member functions
[basic.ios.members]
basic_ostream* tie() const; 1
Returns: An output sequence that is tied to (synchronized with) the sequence controlled by the stream buffer. § 27.5.5.3
978
c ISO/IEC
N3376
basic_ostream* tie(basic_ostream* tiestr); 2
Requires: If tiestr is not null, tiestr must not be reachable by traversing the linked list of tied stream objects starting from tiestr->tie().
3
Postcondition: tiestr == tie().
4
Returns: The previous value of tie(). basic_streambuf* rdbuf() const;
5
Returns: A pointer to the streambuf associated with the stream. basic_streambuf* rdbuf(basic_streambuf* sb);
6
Postcondition: sb == rdbuf().
7
Effects: Calls clear().
8
Returns: The previous value of rdbuf(). locale imbue(const locale& loc);
9
10
Effects: Calls ios_base::imbue(loc) (27.5.3.3) and if rdbuf()!=0 then rdbuf()->pubimbue(loc) (27.6.3.2.1). Returns: The prior value of ios_base::imbue(). char narrow(char_type c, char dfault) const;
11
Returns: use_facet< ctype >(getloc()).narrow(c,dfault) char_type widen(char c) const;
12
Returns: use_facet< ctype >(getloc()).widen(c) char_type fill() const;
13
Returns: The character used to pad (fill) an output conversion to the specified field width. char_type fill(char_type fillch);
14
Postcondition: traits::eq(fillch, fill())
15
Returns: The previous value of fill(). basic_ios& copyfmt(const basic_ios& rhs);
16
Effects: If (this == &rhs) does nothing. Otherwise assigns to the member objects of *this the corresponding member objects of rhs as follows: 1. calls each registered callback pair (fn, index) as (*fn)(erase_event, *this, index); 2. assigns to the member objects of *this the corresponding member objects of rhs, except that § 27.5.5.3
979
c ISO/IEC
N3376
— rdstate(), rdbuf(), and exceptions() are left unchanged; — the contents of arrays pointed at by pword and iword are copied, not the pointers themselves;301 and — if any newly stored pointer values in *this point at objects stored outside the object rhs and those objects are destroyed when rhs is destroyed, the newly stored pointer values are altered to point at newly constructed copies of the objects; 3. calls each callback pair that was copied from rhs as (*fn)(copyfmt_event, *this, index); 4. calls exceptions(rhs.except()). 17
Note: The second pass through the callback pairs permits a copied pword value to be zeroed, or to have its referent deep copied or reference counted, or to have other special action taken.
18
Postconditions: The postconditions of this function are indicated in Table 129. Table 129 — basic_ios::copyfmt() effects Element rdbuf() tie() rdstate() exceptions() flags() width() precision() fill() getloc()
19
Value unchanged rhs.tie() unchanged rhs.exceptions() rhs.flags() rhs.width() rhs.precision() rhs.fill() rhs.getloc()
Returns: *this. void move(basic_ios& rhs); void move(basic_ios&& rhs);
20
Postconditions: *this shall have the state that rhs had before the function call, except that rdbuf() shall return 0. rhs shall be in a valid but unspecified state, except that rhs.rdbuf() shall return the same value as it returned before the function call, and rhs.tie() shall return 0. void swap(basic_ios& rhs) noexcept;
21
Effects: The states of *this and rhs shall be exchanged, except that rdbuf() shall return the same value as it returned before the function call, and rhs.rdbuf() shall return the same value as it returned before the function call. void set_rdbuf(basic_streambuf* sb); 301) This suggests an infinite amount of copying, but the implementation can keep track of the maximum element of the arrays that is non-zero.
§ 27.5.5.3
980
c ISO/IEC
N3376
22
Requires: sb != nullptr.
23
Effects: Associates the basic_streambuf object pointed to by sb with this stream without calling clear().
24
Postconditions: rdbuf() == sb.
25
Throws: Nothing. 27.5.5.4
basic_ios flags functions
[iostate.flags]
explicit operator bool() const; 1
Returns: !fail(). bool operator!() const;
2
Returns: fail(). iostate rdstate() const;
3
Returns: The error state of the stream buffer. void clear(iostate state = goodbit);
4
Postcondition: If rdbuf()!=0 then state == rdstate(); otherwise rdstate()==(state | ios_base ::badbit).
5
Effects: If ((state | (rdbuf() ? goodbit : badbit)) & exceptions()) == 0, returns. Otherwise, the function throws an object fail of class basic_ios::failure (27.5.3.1.1), constructed with implementation-defined argument values. void setstate(iostate state);
6
Effects: Calls clear(rdstate() | state) (which may throw basic_ios::failure (27.5.3.1.1)). bool good() const;
7
Returns: rdstate() == 0 bool eof() const;
8
Returns: true if eofbit is set in rdstate(). bool fail() const;
9
Returns: true if failbit or badbit is set in rdstate().302 bool bad() const;
10
Returns: true if badbit is set in rdstate(). 302) Checking badbit also for fail() is historical practice.
§ 27.5.5.4
981
c ISO/IEC
N3376
iostate exceptions() const; 11
Returns: A mask that determines what elements set in rdstate() cause exceptions to be thrown. void exceptions(iostate except);
12
Postcondition: except == exceptions().
13
Effects: Calls clear(rdstate()).
27.5.6 27.5.6.1
ios_base manipulators
[std.ios.manip]
fmtflags manipulators
[fmtflags.manip]
ios_base& boolalpha(ios_base& str); 1
Effects: Calls str.setf(ios_base::boolalpha).
2
Returns: str. ios_base& noboolalpha(ios_base& str);
3
Effects: Calls str.unsetf(ios_base::boolalpha).
4
Returns: str. ios_base& showbase(ios_base& str);
5
Effects: Calls str.setf(ios_base::showbase).
6
Returns: str. ios_base& noshowbase(ios_base& str);
7
Effects: Calls str.unsetf(ios_base::showbase).
8
Returns: str. ios_base& showpoint(ios_base& str);
9 10
Effects: Calls str.setf(ios_base::showpoint). Returns: str. ios_base& noshowpoint(ios_base& str);
11
Effects: Calls str.unsetf(ios_base::showpoint).
12
Returns: str. ios_base& showpos(ios_base& str);
13
Effects: Calls str.setf(ios_base::showpos).
14
Returns: str. § 27.5.6.1
982
c ISO/IEC
N3376
ios_base& noshowpos(ios_base& str); 15
Effects: Calls str.unsetf(ios_base::showpos).
16
Returns: str. ios_base& skipws(ios_base& str);
17
Effects: Calls str.setf(ios_base::skipws).
18
Returns: str. ios_base& noskipws(ios_base& str);
19
Effects: Calls str.unsetf(ios_base::skipws).
20
Returns: str. ios_base& uppercase(ios_base& str);
21
Effects: Calls str.setf(ios_base::uppercase).
22
Returns: str. ios_base& nouppercase(ios_base& str);
23
Effects: Calls str.unsetf(ios_base::uppercase).
24
Returns: str. ios_base& unitbuf(ios_base& str);
25
Effects: Calls str.setf(ios_base::unitbuf).
26
Returns: str. ios_base& nounitbuf(ios_base& str);
27
Effects: Calls str.unsetf(ios_base::unitbuf).
28
Returns: str. 27.5.6.2
adjustfield manipulators
[adjustfield.manip]
ios_base& internal(ios_base& str); 1
Effects: Calls str.setf(ios_base::internal, ios_base::adjustfield).
2
Returns: str. ios_base& left(ios_base& str);
3
Effects: Calls str.setf(ios_base::left, ios_base::adjustfield).
4
Returns: str. ios_base& right(ios_base& str);
5
Effects: Calls str.setf(ios_base::right, ios_base::adjustfield).
6
Returns: str. § 27.5.6.2
983
c ISO/IEC
27.5.6.3
basefield manipulators
N3376
[basefield.manip]
ios_base& dec(ios_base& str); 1
Effects: Calls str.setf(ios_base::dec, ios_base::basefield).
2
Returns: str303 . ios_base& hex(ios_base& str);
3
Effects: Calls str.setf(ios_base::hex, ios_base::basefield).
4
Returns: str. ios_base& oct(ios_base& str);
5
Effects: Calls str.setf(ios_base::oct, ios_base::basefield).
6
Returns: str. 27.5.6.4
floatfield manipulators
[floatfield.manip]
ios_base& fixed(ios_base& str); 1
Effects: Calls str.setf(ios_base::fixed, ios_base::floatfield).
2
Returns: str. ios_base& scientific(ios_base& str);
3
Effects: Calls str.setf(ios_base::scientific, ios_base::floatfield).
4
Returns: str. ios_base& hexfloat(ios_base& str);
5
Effects: Calls str.setf(ios_base::fixed | ios_base::scientific, ios_base::floatfield).
6
Returns: str.
7
[ Note: The more obvious use of ios_base::hex to specify hexadecimal floating-point format would change the meaning of existing well defined programs. C++2003 gives no meaning to the combination of fixed and scientific. — end note ] ios_base& defaultfloat(ios_base& str);
8
Effects: Calls str.unsetf(ios_base::floatfield).
9
Returns: str. 303) The function signature dec(ios_base&) can be called by the function signature basic_ostream& stream::operator defines types that control input from and output to character sequences.
27.6.2 1
Stream buffer requirements
[streambuf.reqts]
Stream buffers can impose various constraints on the sequences they control. Some constraints are: — The controlled input sequence can be not readable. — The controlled output sequence can be not writable. — The controlled sequences can be associated with the contents of other representations for character sequences, such as external files. — The controlled sequences can support operations directly to or from associated sequences. — The controlled sequences can impose limitations on how the program can read characters from a sequence, write characters to a sequence, put characters back into an input sequence, or alter the stream position.
2
Each sequence is characterized by three pointers which, if non-null, all point into the same charT array object. The array object represents, at any moment, a (sub)sequence of characters from the sequence. Operations performed on a sequence alter the values stored in these pointers, perform reads and writes directly to or from associated sequences, and alter “the stream position” and conversion state as needed to maintain this subsequence relationship. The three pointers are: — the beginning pointer, or lowest element address in the array (called xbeg here); — the next pointer, or next element address that is a current candidate for reading or writing (called xnext here); § 27.6.2
985
c ISO/IEC
N3376
— the end pointer, or first element address beyond the end of the array (called xend here). 3
The following semantic constraints shall always apply for any set of three pointers for a sequence, using the pointer names given immediately above: — If xnext is not a null pointer, then xbeg and xend shall also be non-null pointers into the same charT array, as described above; otherwise, xbeg and xend shall also be null. — If xnext is not a null pointer and xnext < xend for an output sequence, then a write position is available. In this case, *xnext shall be assignable as the next element to write (to put, or to store a character value, into the sequence). — If xnext is not a null pointer and xbeg < xnext for an input sequence, then a putback position is available. In this case, xnext[-1] shall have a defined value and is the next (preceding) element to store a character that is put back into the input sequence. — If xnext is not a null pointer and xnext < xend for an input sequence, then a read position is available. In this case, *xnext shall have a defined value and is the next element to read (to get, or to obtain a character value, from the sequence).
27.6.3
Class template basic_streambuf
[streambuf]
namespace std { template class basic_streambuf { public: // types: typedef charT char_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; typedef traits traits_type; virtual ~basic_streambuf(); // 27.6.3.2.1 locales: locale pubimbue(const locale& loc); locale getloc() const; // 27.6.3.2.2 buffer and positioning: basic_streambuf* pubsetbuf(char_type* s, streamsize n); pos_type pubseekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out); pos_type pubseekpos(pos_type sp, ios_base::openmode which = ios_base::in | ios_base::out); int pubsync(); // Get and put areas: // 27.6.3.2.3 Get area: streamsize in_avail(); int_type snextc(); int_type sbumpc();
§ 27.6.3
986
c ISO/IEC
N3376
int_type sgetc(); streamsize sgetn(char_type* s, streamsize n); // 27.6.3.2.4 Putback: int_type sputbackc(char_type c); int_type sungetc(); // 27.6.3.2.5 Put area: int_type sputc(char_type c); streamsize sputn(const char_type* s, streamsize n); protected: basic_streambuf(); basic_streambuf(const basic_streambuf& rhs); basic_streambuf& operator=(const basic_streambuf& rhs); void swap(basic_streambuf& rhs); // 27.6.3.3.2 Get area: char_type* eback() const; char_type* gptr() const; char_type* egptr() const; void gbump(int n); void setg(char_type* gbeg, char_type* gnext, char_type* gend); // 27.6.3.3.3 Put area: char_type* pbase() const; char_type* pptr() const; char_type* epptr() const; void pbump(int n); void setp(char_type* pbeg, char_type* pend); // 27.6.3.4 virtual functions: // 27.6.3.4.1 Locales: virtual void imbue(const locale& loc); // 27.6.3.4.2 Buffer management and positioning: virtual basic_streambuf* setbuf(char_type* s, streamsize n); virtual pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out); virtual pos_type seekpos(pos_type sp, ios_base::openmode which = ios_base::in | ios_base::out); virtual int sync(); // 27.6.3.4.3 Get area: virtual streamsize showmanyc(); virtual streamsize xsgetn(char_type* s, streamsize n); virtual int_type underflow(); virtual int_type uflow(); // 27.6.3.4.4 Putback: virtual int_type pbackfail(int_type c = traits::eof()); // 27.6.3.4.5 Put area:
§ 27.6.3
987
c ISO/IEC
N3376
virtual streamsize xsputn(const char_type* s, streamsize n); virtual int_type overflow (int_type c = traits::eof()); }; } 1
The class template basic_streambuf serves as an abstract base class for deriving various stream buffers whose objects each control two character sequences: — a character input sequence; — a character output sequence. 27.6.3.1
basic_streambuf constructors
[streambuf.cons]
basic_streambuf(); 1
Effects: Constructs an object of class basic_streambuf and initializes:304 — all its pointer member objects to null pointers, — the getloc() member to a copy the global locale, locale(), at the time of construction.
2
Remarks: Once the getloc() member is initialized, results of calling locale member functions, and of members of facets so obtained, can safely be cached until the next time the member imbue is called. basic_streambuf(const basic_streambuf& rhs);
3
Effects: Constructs a copy of rhs.
4
Postconditions: — eback() == rhs.eback() — gptr() == rhs.gptr() — egptr() == rhs.egptr() — pbase() == rhs.pbase() — pptr() == rhs.pptr() — epptr() == rhs.epptr() — getloc() == rhs.getloc() ~basic_streambuf();
5
Effects: None. 27.6.3.2 27.6.3.2.1
basic_streambuf public member functions Locales
[streambuf.members] [streambuf.locales]
locale pubimbue(const locale& loc); 1
Postcondition: loc == getloc().
2
Effects: Calls imbue(loc).
3
Returns: Previous value of getloc(). 304) The default constructor is protected for class basic_streambuf to assure that only objects for classes derived from this class may be constructed.
§ 27.6.3.2.1
988
c ISO/IEC
N3376
locale getloc() const; 4
Returns: If pubimbue() has ever been called, then the last value of loc supplied, otherwise the current global locale, locale(), in effect at the time of construction. If called after pubimbue() has been called but before pubimbue has returned (i.e., from within the call of imbue()) then it returns the previous value. 27.6.3.2.2
Buffer management and positioning
[streambuf.buffer]
basic_streambuf* pubsetbuf(char_type* s, streamsize n); 1
Returns: setbuf(s, n). pos_type pubseekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out);
2
Returns: seekoff(off, way, which). pos_type pubseekpos(pos_type sp, ios_base::openmode which = ios_base::in | ios_base::out);
3
Returns: seekpos(sp, which). int pubsync();
4
Returns: sync(). 27.6.3.2.3
Get area
[streambuf.pub.get]
streamsize in_avail(); 1
Returns: If a read position is available, returns egptr() - gptr(). Otherwise returns showmanyc() (27.6.3.4.3). int_type snextc();
2
Effects: Calls sbumpc().
3
Returns: If that function returns traits::eof(), returns traits::eof(). Otherwise, returns sgetc(). int_type sbumpc();
4
Returns: If the input sequence read position is not available, returns uflow(). Otherwise, returns traits::to_int_type(*gptr()) and increments the next pointer for the input sequence. int_type sgetc();
5
Returns: If the input sequence read position is not available, returns underflow(). Otherwise, returns traits::to_int_type(*gptr()). streamsize sgetn(char_type* s, streamsize n);
6
Returns: xsgetn(s, n). § 27.6.3.2.3
989
c ISO/IEC
27.6.3.2.4
N3376
Putback
[streambuf.pub.pback]
int_type sputbackc(char_type c); 1
Returns: If the input sequence putback position is not available, or if traits::eq(c,gptr()[-1]) is false, returns pbackfail(traits::to_int_type(c)). Otherwise, decrements the next pointer for the input sequence and returns traits::to_int_type(*gptr()). int_type sungetc();
2
Returns: If the input sequence putback position is not available, returns pbackfail(). Otherwise, decrements the next pointer for the input sequence and returns traits::to_int_type(*gptr()). 27.6.3.2.5
Put area
[streambuf.pub.put]
int_type sputc(char_type c); 1
Returns: If the output sequence write position is not available, returns overflow(traits::to_int_type(c)). Otherwise, stores c at the next pointer for the output sequence, increments the pointer, and returns traits::to_int_type(c). streamsize sputn(const char_type* s, streamsize n);
2
Returns: xsputn(s,n). 27.6.3.3 27.6.3.3.1
basic_streambuf protected member functions Assignment
[streambuf.protected] [streambuf.assign]
basic_streambuf& operator=(const basic_streambuf& rhs); 1
Effects: Assigns the data members of rhs to *this.
2
Postconditions: — eback() == rhs.eback() — gptr() == rhs.gptr() — egptr() == rhs.egptr() — pbase() == rhs.pbase() — pptr() == rhs.pptr() — epptr() == rhs.epptr() — getloc() == rhs.getloc()
3
Returns: *this. void swap(basic_streambuf& rhs);
4
Effects: Swaps the data members of rhs and *this.
§ 27.6.3.3.1
990
c ISO/IEC
27.6.3.3.2
N3376
Get area access
[streambuf.get.area]
char_type* eback() const; 1
Returns: The beginning pointer for the input sequence. char_type* gptr() const;
2
Returns: The next pointer for the input sequence. char_type* egptr() const;
3
Returns: The end pointer for the input sequence. void gbump(int n);
4
Effects: Adds n to the next pointer for the input sequence. void setg(char_type* gbeg, char_type* gnext, char_type* gend);
5
Postconditions: gbeg == eback(), gnext == gptr(), and gend == egptr(). 27.6.3.3.3
Put area access
[streambuf.put.area]
char_type* pbase() const; 1
Returns: The beginning pointer for the output sequence. char_type* pptr() const;
2
Returns: The next pointer for the output sequence. char_type* epptr() const;
3
Returns: The end pointer for the output sequence. void pbump(int n);
4
Effects: Adds n to the next pointer for the output sequence. void setp(char_type* pbeg, char_type* pend);
5
Postconditions: pbeg == pbase(), pbeg == pptr(), and pend == epptr(). 27.6.3.4 27.6.3.4.1
basic_streambuf virtual functions Locales
[streambuf.virtuals] [streambuf.virt.locales]
void imbue(const locale&) 1
Effects: Change any translations based on locale.
2
Remarks: Allows the derived class to be informed of changes in locale at the time they occur. Between invocations of this function a class derived from streambuf can safely cache results of calls to locale functions and to members of facets so obtained.
3
Default behavior: Does nothing. § 27.6.3.4.1
991
c ISO/IEC
27.6.3.4.2
N3376
Buffer management and positioning
[streambuf.virt.buffer]
basic_streambuf* setbuf(char_type* s, streamsize n); 1
Effects: Influences stream buffering in a way that is defined separately for each class derived from basic_streambuf in this Clause (27.8.2.4, 27.9.1.5).
2
Default behavior: Does nothing. Returns this. pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out);
3
Effects: Alters the stream positions within one or more of the controlled sequences in a way that is defined separately for each class derived from basic_streambuf in this Clause (27.8.2.4, 27.9.1.5).
4
Default behavior: Returns pos_type(off_type(-1)). pos_type seekpos(pos_type sp, ios_base::openmode which = ios_base::in | ios_base::out);
5
Effects: Alters the stream positions within one or more of the controlled sequences in a way that is defined separately for each class derived from basic_streambuf in this Clause (27.8.2, 27.9.1.1).
6
Default behavior: Returns pos_type(off_type(-1)). int sync();
7
Effects: Synchronizes the controlled sequences with the arrays. That is, if pbase() is non-null the characters between pbase() and pptr() are written to the controlled sequence. The pointers may then be reset as appropriate.
8
Returns:-1 on failure. What constitutes failure is determined by each derived class (27.9.1.5).
9
Default behavior: Returns zero. 27.6.3.4.3
Get area
[streambuf.virt.get]
streamsize showmanyc();305 1
Returns: An estimate of the number of characters available in the sequence, or -1. If it returns a positive value, then successive calls to underflow() will not return traits::eof() until at least that number of characters have been extracted from the stream. If showmanyc() returns -1, then calls to underflow() or uflow() will fail.306
2
Default behavior: Returns zero.
3
Remarks: Uses traits::eof(). streamsize xsgetn(char_type* s, streamsize n); 305) The morphemes of showmanyc are “es-how-many-see”, not “show-manic”. 306) underflow or uflow might fail by throwing an exception prematurely. The intention is not only that the calls will not
return eof() but that they will return “immediately.”
§ 27.6.3.4.3
992
c ISO/IEC
N3376
4
Effects: Assigns up to n characters to successive elements of the array whose first element is designated by s. The characters assigned are read from the input sequence as if by repeated calls to sbumpc(). Assigning stops when either n characters have been assigned or a call to sbumpc() would return traits::eof().
5
Returns: The number of characters assigned.307
6
Remarks: Uses traits::eof(). int_type underflow();
7
Remarks: The public members of basic_streambuf call this virtual function only if gptr() is null or gptr() >= egptr()
8
Returns: traits::to_int_type(c), where c is the first character of the pending sequence, without moving the input sequence position past it. If the pending sequence is null then the function returns traits::eof() to indicate failure.
9
The pending sequence of characters is defined as the concatenation of: a) If gptr() is non- NULL, then the egptr() - gptr() characters starting at gptr(), otherwise the empty sequence. b) Some sequence (possibly empty) of characters read from the input sequence.
10
The result character is a) If the pending sequence is non-empty, the first character of the sequence. b) If the pending sequence is empty then the next character that would be read from the input sequence.
11
The backup sequence is defined as the concatenation of: a) If eback() is null then empty, b) Otherwise the gptr() - eback() characters beginning at eback().
12
Effects: The function sets up the gptr() and egptr() satisfying one of: a) If the pending sequence is non-empty, egptr() is non-null and egptr() - gptr() characters starting at gptr() are the characters in the pending sequence b) If the pending sequence is empty, either gptr() is null or gptr() and egptr() are set to the same non-NULL pointer.
13
If eback() and gptr() are non-null then the function is not constrained as to their contents, but the “usual backup condition” is that either: a) If the backup sequence contains at least gptr() - eback() characters, then the gptr() - eback() characters starting at eback() agree with the last gptr() - eback() characters of the backup sequence. b) Or the n characters starting at gptr() - n agree with the backup sequence (where n is the length of the backup sequence)
14
Default behavior: Returns traits::eof(). 307) Classes derived from basic_streambuf can provide more efficient ways to implement xsgetn() and xsputn() by overriding these definitions from the base class.
§ 27.6.3.4.3
993
c ISO/IEC
N3376
int_type uflow(); 15
Requires: The constraints are the same as for underflow(), except that the result character shall be transferred from the pending sequence to the backup sequence, and the pending sequence shall not be empty before the transfer.
16
Default behavior: Calls underflow(). If underflow() returns traits::eof(), returns traits::eof(). Otherwise, returns the value of traits::to_int_type(*gptr()) and increment the value of the next pointer for the input sequence.
17
Returns: traits::eof() to indicate failure. 27.6.3.4.4
Putback
[streambuf.virt.pback]
int_type pbackfail(int_type c = traits::eof()); 1
Remarks: The public functions of basic_streambuf call this virtual function only when gptr() is null, gptr() == eback(), or traits::eq(traits::to_char_type(c),gptr()[-1]) returns false. Other calls shall also satisfy that constraint. The pending sequence is defined as for underflow(), with the modifications that — If traits::eq_int_type(c,traits::eof()) returns true, then the input sequence is backed up one character before the pending sequence is determined. — If traits::eq_int_type(c,traits::eof()) return false, then c is prepended. Whether the input sequence is backed up or modified in any other way is unspecified.
2
Postcondition: On return, the constraints of gptr(), eback(), and pptr() are the same as for underflow().
3
Returns: traits::eof() to indicate failure. Failure may occur because the input sequence could not be backed up, or if for some other reason the pointers could not be set consistent with the constraints. pbackfail() is called only when put back has really failed.
4
Returns some value other than traits::eof() to indicate success.
5
Default behavior: Returns traits::eof(). 27.6.3.4.5
Put area
[streambuf.virt.put]
streamsize xsputn(const char_type* s, streamsize n); 1
Effects: Writes up to n characters to the output sequence as if by repeated calls to sputc(c). The characters written are obtained from successive elements of the array whose first element is designated by s. Writing stops when either n characters have been written or a call to sputc(c) would return traits::eof(). Is is unspecified whether the function calls overflow() when pptr() == epptr() becomes true or whether it achieves the same effects by other means.
2
Returns: The number of characters written. int_type overflow(int_type c = traits::eof());
3
Effects: Consumes some initial subsequence of the characters of the pending sequence. The pending sequence is defined as the concatenation of a) if pbase() is NULL then the empty sequence otherwise, pptr() - pbase() characters beginning at pbase(). b) if traits::eq_int_type(c,traits::eof()) returns true, then the empty sequence otherwise, the sequence consisting of c. § 27.6.3.4.5
994
c ISO/IEC
N3376
4
Remarks: The member functions sputc() and sputn() call this function in case that no room can be found in the put buffer enough to accommodate the argument character sequence.
5
Requires: Every overriding definition of this virtual function shall obey the following constraints: 1) The effect of consuming a character on the associated output sequence is specified308 2) Let r be the number of characters in the pending sequence not consumed. If r is non-zero then pbase() and pptr() shall be set so that: pptr() - pbase() == r and the r characters starting at pbase() are the associated output stream. In case r is zero (all characters of the pending sequence have been consumed) then either pbase() is set to NULL, or pbase() and pptr() are both set to the same NULL non-value. 3) The function may fail if either appending some character to the associated output stream fails or if it is unable to establish pbase() and pptr() according to the above rules.
6
Returns: traits::eof() or throws an exception if the function fails. Otherwise, returns some value other than traits::eof() to indicate success.309
7
Default behavior: Returns traits::eof().
27.7 27.7.1
Formatting and manipulators Overview
[iostream.format] [iostream.format.overview]
Header synopsis namespace std { template class basic_istream; typedef basic_istream istream; typedef basic_istream<wchar_t> wistream; template class basic_iostream; typedef basic_iostream iostream; typedef basic_iostream<wchar_t> wiostream; template basic_istream& ws(basic_istream& is); template basic_istream& operator>>(basic_istream&& is, T& x); }
Header synopsis namespace std { template class basic_ostream; typedef basic_ostream ostream; typedef basic_ostream<wchar_t> wostream; template 308) That is, for each class derived from an instance of basic_streambuf in this Clause (27.8.2, 27.9.1.1), a specification of how consuming a character effects the associated output sequence is given. There is no requirement on a program-defined class. 309) Typically, overflow returns c to indicate success, except when traits::eq_int_type(c,traits::eof()) returns true, in which case it returns traits::not_eof(c).
§ 27.7.1
995
c ISO/IEC
N3376
basic_ostream& endl(basic_ostream& os); template basic_ostream& ends(basic_ostream& os); template basic_ostream& flush(basic_ostream& os); template basic_ostream& operator( basic_istream& (*pf)(basic_istream&)); basic_istream& operator>>( basic_ios& (*pf)(basic_ios&)); basic_istream& operator>>(
§ 27.7.2.1
996
c ISO/IEC
N3376
ios_base& (*pf)(ios_base&)); basic_istream& basic_istream& basic_istream& basic_istream& basic_istream& basic_istream& basic_istream& basic_istream& basic_istream& basic_istream& basic_istream& basic_istream&
operator>>(bool& n); operator>>(short& n); operator>>(unsigned short& n); operator>>(int& n); operator>>(unsigned int& n); operator>>(long& n); operator>>(unsigned long& n); operator>>(long long& n); operator>>(unsigned long long& n); operator>>(float& f); operator>>(double& f); operator>>(long double& f);
basic_istream& operator>>(void*& p); basic_istream& operator>>( basic_streambuf* sb); // 27.7.2.3 Unformatted input: streamsize gcount() const; int_type get(); basic_istream& get(char_type& c); basic_istream& get(char_type* s, streamsize n); basic_istream& get(char_type* s, streamsize n, char_type delim); basic_istream& get(basic_streambuf& sb); basic_istream& get(basic_streambuf& sb, char_type delim); basic_istream& getline(char_type* s, streamsize n); basic_istream& getline(char_type* s, streamsize n, char_type delim); basic_istream& streamsize n = 1, int_type int_type basic_istream& streamsize
ignore( delim = traits::eof()); peek(); read (char_type* s, streamsize n); readsome(char_type* s, streamsize n);
basic_istream& putback(char_type c); basic_istream& unget(); int sync(); pos_type tellg(); basic_istream& seekg(pos_type); basic_istream& seekg(off_type, ios_base::seekdir); protected: basic_istream(const basic_istream& rhs) = delete; basic_istream(basic_istream&& rhs); // 27.7.2.1.2 Assign/swap: basic_istream& operator=(const basic_istream& rhs) = delete; basic_istream& operator=(basic_istream&& rhs);
§ 27.7.2.1
997
c ISO/IEC
N3376
void swap(basic_istream& rhs); }; // 27.7.2.2.3 character extraction templates: template basic_istream& operator>>(basic_istream&, charT&); template basic_istream& operator>>(basic_istream&, unsigned char&); template basic_istream& operator>>(basic_istream&, signed char&); template basic_istream& operator>>(basic_istream&, charT*); template basic_istream& operator>>(basic_istream&, unsigned char*); template basic_istream& operator>>(basic_istream&, signed char*); } 1
2
3
4
The class basic_istream defines a number of member function signatures that assist in reading and interpreting input from sequences controlled by a stream buffer. Two groups of member function signatures share common properties: the formatted input functions (or extractors) and the unformatted input functions. Both groups of input functions are described as if they obtain (or extract) input characters by calling rdbuf()->sbumpc() or rdbuf()->sgetc(). They may use other public members of istream. If rdbuf()->sbumpc() or rdbuf()->sgetc() returns traits::eof(), then the input function, except as explicitly noted otherwise, completes its actions and does setstate(eofbit), which may throw ios_base::failure (27.5.5.4), before returning. If one of these called functions throws an exception, then unless explicitly noted otherwise, the input function sets badbit in error state. If badbit is on in exceptions(), the input function rethrows the exception without completing its actions, otherwise it does not throw anything and proceeds as if the called function had returned a failure indication. 27.7.2.1.1 basic_istream constructors [istream.cons] explicit basic_istream(basic_streambuf* sb);
1
Effects: Constructs an object of class basic_istream, assigning initial values to the base class by calling basic_ios::init(sb) (27.5.5.2).
2
Postcondition: gcount() == 0 basic_istream(basic_istream&& rhs);
3
Effects: Move constructs from the rvalue rhs. This is accomplished by default constructing the base class, copying the gcount() from rhs, calling basic_ios::move(rhs) to initialize the base class, and setting the gcount() for rhs to 0. virtual ~basic_istream();
§ 27.7.2.1.1
998
c ISO/IEC
N3376
4
Effects: Destroys an object of class basic_istream.
5
Remarks: Does not perform any operations of rdbuf(). 27.7.2.1.2
Class basic_istream assign and swap
[istream.assign]
basic_istream& operator=(basic_istream&& rhs); 1
Effects: swap(rhs);.
2
Returns: *this. void swap(basic_istream& rhs);
3
Effects: Calls basic_ios::swap(rhs). Exchanges the values returned by gcount() and rhs.gcount(). 27.7.2.1.3
Class basic_istream::sentry
[istream::sentry]
namespace std { template class basic_istream::sentry { typedef traits traits_type; bool ok_; // exposition only public: explicit sentry(basic_istream& is, bool noskipws = false); ~sentry(); explicit operator bool() const { return ok_; } sentry(const sentry&) = delete; sentry& operator=(const sentry&) = delete; }; } 1
The class sentry defines a class that is responsible for doing exception safe prefix and suffix operations. explicit sentry(basic_istream& is, bool noskipws = false);
2
Effects: If is.good() is false, calls is.setstate(failbit). Otherwise, prepares for formatted or unformatted input. First, if is.tie() is not a null pointer, the function calls is.tie()->flush() to synchronize the output sequence with any associated external C stream. Except that this call can be suppressed if the put area of is.tie() is empty. Further an implementation is allowed to defer the call to flush until a call of is.rdbuf()->underflow() occurs. If no such call occurs before the sentry object is destroyed, the call to flush may be eliminated entirely.310 If noskipws is zero and is.flags() & ios_base::skipws is nonzero, the function extracts and discards each character as long as the next available input character c is a whitespace character. If is.rdbuf()->sbumpc() or is.rdbuf()->sgetc() returns traits::eof(), the function calls setstate(failbit | eofbit) (which may throw ios_base::failure).
3
Remarks: The constructor explicit sentry(basic_istream& is, bool noskipws = false) uses the currently imbued locale in is, to determine whether the next input character is whitespace or not.
4
To decide if the character c is a whitespace character, the constructor performs as if it executes the following code fragment: 310) This will be possible only in functions that are part of the library. The semantics of the constructor used in user code is as specified.
§ 27.7.2.1.3
999
c ISO/IEC
N3376
const ctype& ctype = use_facet(is.getloc()); if (ctype.is(ctype.space,c)!=0) // c is a whitespace character. 5
If, after any preparation is completed, is.good() is true, ok_ != false otherwise, ok_ == false. During preparation, the constructor may call setstate(failbit) (which may throw ios_base:: failure (27.5.5.4))311 ~sentry();
6
Effects: None. explicit operator bool() const;
7
Effects: Returns ok_. 27.7.2.2 27.7.2.2.1
1
Formatted input functions Common requirements
[istream.formatted] [istream.formatted.reqmts]
Each formatted input function begins execution by constructing an object of class sentry with the noskipws (second) argument false. If the sentry object returns true, when converted to a value of type bool, the function endeavors to obtain the requested input. If an exception is thrown during input then ios::badbit is turned on312 in *this’s error state. If (exceptions()&badbit) != 0 then the exception is rethrown. In any case, the formatted input function destroys the sentry object. If no exception has been thrown, it returns *this. 27.7.2.2.2 Arithmetic extractors [istream.formatted.arithmetic] operator>>(unsigned short& val); operator>>(unsigned int& val); operator>>(long& val); operator>>(unsigned long& val); operator>>(long long& val); operator>>(unsigned long long& val); operator>>(float& val); operator>>(double& val); operator>>(long double& val); operator>>(bool& val); operator>>(void*& val);
1
As in the case of the inserters, these extractors depend on the locale’s num_get (22.4.2.1) object to perform parsing the input stream data. These extractors behave as formatted input functions (as described in 27.7.2.2.1). After a sentry object is constructed, the conversion occurs as if performed by the following code fragment: typedef num_get< charT,istreambuf_iterator > numget; iostate err = iostate::goodbit; use_facet< numget >(loc).get(*this, 0, *this, err, val); setstate(err);
In the above fragment, loc stands for the private member of the basic_ios class. [ Note: The first argument provides an object of the istreambuf_iterator class which is an iterator pointed to an input stream. It bypasses istreams and uses streambufs directly. — end note ] Class locale relies on this type as its interface to istream, so that it does not need to depend directly on istream. 311) The sentry constructor and destructor can also perform additional implementation-dependent operations. 312) This is done without causing an ios::failure to be thrown.
§ 27.7.2.2.2
1000
c ISO/IEC
N3376
operator>>(short& val); 2
The conversion occurs as if performed by the following code fragment (using the same notation as for the preceding code fragment): typedef num_get numget; iostate err = ios_base::goodbit; long lval; use_facet(loc).get(*this, 0, *this, err, lval); if (lval < numeric_limits<short>::min()) { err |= ios_base::failbit; val = numeric_limits<short>::min(); } else if (numeric_limits<short>::max() < lval) { err |= ios_base::failbit; val = numeric_limits<short>::max(); } else val = static_cast<short>(lval); setstate(err);
operator>>(int& val); 3
The conversion occurs as if performed by the following code fragment (using the same notation as for the preceding code fragment): typedef num_get numget; iostate err = ios_base::goodbit; long lval; use_facet(loc).get(*this, 0, *this, err, lval); if (lval < numeric_limits::min()) { err |= ios_base::failbit; val = numeric_limits::min(); } else if (numeric_limits::max() < lval) { err |= ios_base::failbit; val = numeric_limits::max(); } else val = static_cast(lval); setstate(err);
27.7.2.2.3
basic_istream::operator>>
[istream::extractors]
basic_istream& operator>> (basic_istream& (*pf)(basic_istream&)) 1
Effects: None. This extractor does not behave as a formatted input function (as described in 27.7.2.2.1.)
2
Returns: pf(*this).313 basic_istream& operator>> (basic_ios& (*pf)(basic_ios&));
3
Effects: Calls pf(*this). This extractor does not behave as a formatted input function (as described in 27.7.2.2.1).
4
Returns: *this. 313) See, for example, the function signature ws(basic_istream&) (27.7.2.4).
§ 27.7.2.2.3
1001
c ISO/IEC
N3376
basic_istream& operator>> (ios_base& (*pf)(ios_base&)); 5
Effects: Calls pf(*this).314 This extractor does not behave as a formatted input function (as described in 27.7.2.2.1).
6
Returns: *this. template basic_istream& operator>>(basic_istream& in, charT* s); template basic_istream& operator>>(basic_istream& in, unsigned char* s); template basic_istream& operator>>(basic_istream& in, signed char* s);
7
Effects: Behaves like a formatted input member (as described in 27.7.2.2.1) of in. After a sentry object is constructed, operator>> extracts characters and stores them into successive locations of an array whose first element is designated by s. If width() is greater than zero, n is width(). Otherwise n is the number of elements of the largest array of char_type that can store a terminating charT(). n is the maximum number of characters stored.
8
Characters are extracted and stored until any of the following occurs: — n-1 characters are stored; — end of file occurs on the input sequence; — ct.is(ct.space,c) is true for the next available input character c, where ct is use_facet >(in.getloc()).
9
operator>> then stores a null byte (charT()) in the next position, which may be the first position if no characters were extracted. operator>> then calls width(0).
10
If the function extracted no characters, it calls setstate(failbit), which may throw ios_base:: failure (27.5.5.4).
11
Returns: in. template basic_istream& operator>>(basic_istream& in, charT& c); template basic_istream& operator>>(basic_istream& in, unsigned char& c); template basic_istream& operator>>(basic_istream& in, signed char& c);
12
Effects: Behaves like a formatted input member (as described in 27.7.2.2.1) of in. After a sentry object is constructed a character is extracted from in, if one is available, and stored in c. Otherwise, the function calls in.setstate(failbit).
13
Returns: in. 314) See, for example, the function signature dec(ios_base&) (27.5.6.3).
§ 27.7.2.2.3
1002
c ISO/IEC
N3376
basic_istream& operator>> (basic_streambuf* sb); 14
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1). If sb is null, calls setstate(failbit), which may throw ios_base::failure (27.5.5.4). After a sentry object is constructed, extracts characters from *this and inserts them in the output sequence controlled by sb. Characters are extracted and inserted until any of the following occurs: — end-of-file occurs on the input sequence; — inserting in the output sequence fails (in which case the character to be inserted is not extracted); — an exception occurs (in which case the exception is caught).
15
If the function inserts no characters, it calls setstate(failbit), which may throw ios_base:: failure (27.5.5.4). If it inserted no characters because it caught an exception thrown while extracting characters from *this and failbit is on in exceptions() (27.5.5.4), then the caught exception is rethrown.
16
Returns: *this. 27.7.2.3
1
Unformatted input functions
[istream.unformatted]
Each unformatted input function begins execution by constructing an object of class sentry with the default argument noskipws (second) argument true. If the sentry object returns true, when converted to a value of type bool, the function endeavors to obtain the requested input. Otherwise, if the sentry constructor exits by throwing an exception or if the sentry object returns false, when converted to a value of type bool, the function returns without attempting to obtain any input. In either case the number of extracted characters is set to 0; unformatted input functions taking a character array of non-zero size as an argument shall also store a null character (using charT()) in the first location of the array. If an exception is thrown during input then ios::badbit is turned on315 in *this’s error state. (Exceptions thrown from basic_ios::clear() are not caught or rethrown.) If (exceptions()&badbit) != 0 then the exception is rethrown. It also counts the number of characters extracted. If no exception has been thrown it ends by storing the count in a member object and returning the value specified. In any event the sentry object is destroyed before leaving the unformatted input function. streamsize gcount() const;
2
Effects: None. This member function does not behave as an unformatted input function (as described in 27.7.2.3, paragraph 1).
3
Returns: The number of characters extracted by the last unformatted input member function called for the object. int_type get();
4
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1). After constructing a sentry object, extracts a character c, if one is available. Otherwise, the function calls setstate(failbit), which may throw ios_base::failure (27.5.5.4),
5
Returns: c if available, otherwise traits::eof(). basic_istream& get(char_type& c); 315) This is done without causing an ios::failure to be thrown.
§ 27.7.2.3
1003
c ISO/IEC
N3376
6
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1). After constructing a sentry object, extracts a character, if one is available, and assigns it to c.316 Otherwise, the function calls setstate(failbit) (which may throw ios_base::failure (27.5.5.4)).
7
Returns: *this. basic_istream& get(char_type* s, streamsize n, char_type delim );
8
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1). After constructing a sentry object, extracts characters and stores them into successive locations of an array whose first element is designated by s.317 Characters are extracted and stored until any of the following occurs: — n is less than one or n - 1 characters are stored; — end-of-file occurs on the input sequence (in which case the function calls setstate(eofbit)); — traits::eq(c, delim) for the next available input character c (in which case c is not extracted).
9
10
If the function stores no characters, it calls setstate(failbit) (which may throw ios_base:: failure (27.5.5.4)). In any case, if n is greater than zero it then stores a null character into the next successive location of the array. Returns: *this. basic_istream& get(char_type* s, streamsize n)
11
Effects: Calls get(s,n,widen(’\n’))
12
Returns: Value returned by the call. basic_istream& get(basic_streambuf& sb, char_type delim );
13
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1). After constructing a sentry object, extracts characters and inserts them in the output sequence controlled by sb. Characters are extracted and inserted until any of the following occurs: — end-of-file occurs on the input sequence; — inserting in the output sequence fails (in which case the character to be inserted is not extracted); — traits::eq(c, delim) for the next available input character c (in which case c is not extracted); — an exception occurs (in which case, the exception is caught but not rethrown).
14
If the function inserts no characters, it calls setstate(failbit), which may throw ios_base:: failure (27.5.5.4).
15
Returns: *this. basic_istream& get(basic_streambuf& sb); 316) Note that this function is not overloaded on types signed char and unsigned char. 317) Note that this function is not overloaded on types signed char and unsigned char.
§ 27.7.2.3
1004
c ISO/IEC
16
Effects: Calls get(sb, widen(’\n’))
17
Returns: Value returned by the call.
N3376
basic_istream& getline(char_type* s, streamsize n, char_type delim); 18
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1). After constructing a sentry object, extracts characters and stores them into successive locations of an array whose first element is designated by s.318 Characters are extracted and stored until one of the following occurs: 1. end-of-file occurs on the input sequence (in which case the function calls setstate(eofbit)); 2. traits::eq(c, delim) for the next available input character c (in which case the input character is extracted but not stored);319 3. n is less than one or n - 1 characters are stored (in which case the function calls setstate( failbit)).
19
These conditions are tested in the order shown.320
20
If the function extracts no characters, it calls setstate(failbit) (which may throw ios_base:: failure (27.5.5.4)).321
21
In any case, if n is greater than zero, it then stores a null character (using charT()) into the next successive location of the array.
22
Returns: *this.
23
[ Example: #include int main() { using namespace std; const int line_buffer_size = 100; char buffer[line_buffer_size]; int line_number = 0; while (cin.getline(buffer, line_buffer_size, ’\n’) || cin.gcount()) { int count = cin.gcount(); if (cin.eof()) cout sungetc(). If rdbuf() is null, or if sungetc() returns traits::eof(), calls setstate(badbit) (which may throw ios_base::failure (27.5.5.4)). [ Note: This function extracts no characters, so the value returned by the next call to gcount() is 0. — end note ]
37
Returns: *this. int sync();
38
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1), except that it does not count the number of characters extracted and does not affect the value returned by subsequent calls to gcount(). After constructing a sentry object, if rdbuf() is a null pointer, returns -1 . Otherwise, calls rdbuf()->pubsync() and, if that function returns -1 calls setstate(badbit) (which may throw ios_base::failure (27.5.5.4), and returns -1. Otherwise, returns zero. pos_type tellg();
39
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1), except that it does not count the number of characters extracted and does not affect the value returned by subsequent calls to gcount().
40
Returns: After constructing a sentry object, if fail() != false, returns pos_type(-1) to indicate failure. Otherwise, returns rdbuf()->pubseekoff(0, cur, in). basic_istream& seekg(pos_type pos);
41
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1), except that the function first clears eofbit, it does not count the number of characters extracted, and it does not affect the value returned by subsequent calls to gcount(). After constructing a sentry object, if fail() != true, executes rdbuf()->pubseekpos(pos, ios_base::in). In case of failure, the function calls setstate(failbit) (which may throw ios_base::failure).
42
Returns: *this. § 27.7.2.3
1007
c ISO/IEC
N3376
basic_istream& seekg(off_type off, ios_base::seekdir dir); 43
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1), except that it does not count the number of characters extracted and does not affect the value returned by subsequent calls to gcount(). After constructing a sentry object, if fail() != true, executes rdbuf()->pubseekoff(off, dir, ios_base::in). In case of failure, the function calls setstate( failbit) (which may throw ios_base::failure).
44
Returns: *this. 27.7.2.4
Standard basic_istream manipulators
[istream.manip]
namespace std { template basic_istream& ws(basic_istream& is); } 1
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1), except that it does not count the number of characters extracted and does not affect the value returned by subsequent calls to is.gcount(). After constructing a sentry object extracts characters as long as the next available character c is whitespace or until there are no more characters in the sequence. Whitespace characters are distinguished with the same criterion as used by sentry::sentry (27.7.2.1.3). If ws stops extracting characters because there are no more available it sets eofbit, but not failbit.
2
Returns: is. 27.7.2.5
Class template basic_iostream
[iostreamclass]
namespace std { template class basic_iostream : public basic_istream, public basic_ostream { public: // types: typedef charT char_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type; typedef typename traits::off_type off_type; typedef traits traits_type; // constructor/destructor explicit basic_iostream(basic_streambuf* sb); virtual ~basic_iostream(); protected: basic_iostream(const basic_iostream& rhs) = delete; basic_iostream(basic_iostream&& rhs); // assign/swap basic_iostream& operator=(const basic_iostream& rhs) = delete; basic_iostream& operator=(basic_iostream&& rhs); void swap(basic_iostream& rhs); }; }
§ 27.7.2.5
1008
c ISO/IEC
1
N3376
The class basic_iostream inherits a number of functions that allow reading input and writing output to sequences controlled by a stream buffer. 27.7.2.5.1 basic_iostream constructors [iostream.cons] explicit basic_iostream(basic_streambuf* sb);
1
Effects: Constructs an object of class basic_iostream, assigning initial values to the base classes by calling basic_istream(sb) (27.7.2.1) and basic_ostream(sb) (27.7.3.1)
2
Postcondition: rdbuf()==sb and gcount()==0. basic_iostream(basic_iostream&& rhs);
3
Effects: Move constructs from the rvalue rhs by constructing the basic_istream base class with move(rhs). 27.7.2.5.2
basic_iostream destructor
[iostream.dest]
virtual ~basic_iostream(); 1
Effects: Destroys an object of class basic_iostream.
2
Remarks: Does not perform any operations on rdbuf(). 27.7.2.5.3
basic_iostream assign and swap
[iostream.assign]
basic_iostream& operator=(basic_iostream&& rhs); 1
Effects: swap(rhs). void swap(basic_iostream& rhs);
2
Effects: Calls basic_istream::swap(rhs). 27.7.2.6
Rvalue stream extraction
[istream.rvalue]
template basic_istream& operator>>(basic_istream&& is, T& x); 1
Effects: is » x
2
Returns: is
27.7.3 1
Output streams
[output.streams]
The header defines a type and several function signatures that control output to a stream buffer along with a function template that inserts into stream rvalues. 27.7.3.1 Class template basic_ostream [ostream] namespace std { template class basic_ostream : virtual public basic_ios { public: // types (inherited from basic_ios (27.5.5)): typedef charT char_type; typedef typename traits::int_type int_type; typedef typename traits::pos_type pos_type;
§ 27.7.3.1
1009
c ISO/IEC
N3376
typedef typename traits::off_type off_type; typedef traits traits_type; // 27.7.3.2 Constructor/destructor: explicit basic_ostream(basic_streambuf* sb); virtual ~basic_ostream(); // 27.7.3.4 Prefix/suffix: class sentry; // 27.7.3.6 Formatted output: basic_ostream& operator class regex_iterator { public: typedef basic_regex regex_type; typedef match_results value_type; typedef std::ptrdiff_t difference_type; typedef const value_type* pointer; typedef const value_type& reference; typedef std::forward_iterator_tag iterator_category; regex_iterator(); regex_iterator(BidirectionalIterator a, BidirectionalIterator b, const regex_type& re, regex_constants::match_flag_type m = regex_constants::match_default); regex_iterator(const regex_iterator&); regex_iterator& operator=(const regex_iterator&); bool operator==(const regex_iterator&) const; bool operator!=(const regex_iterator&) const;
§ 28.12.1
1088
c ISO/IEC
N3376
const value_type& operator*() const; const value_type* operator->() const; regex_iterator& operator++(); regex_iterator operator++(int); private: // these members are shown for exposition only: BidirectionalIterator begin; BidirectionalIterator end; const regex_type* pregex; regex_constants::match_flag_type flags; match_results match; }; } 2
An object of type regex_iterator that is not an end-of-sequence iterator holds a zero-length match if match[0].matched == true and match[0].first == match[0].second. [ Note: For example, this can occur when the part of the regular expression that matched consists only of an assertion (such as ’^’, ’$’, ’\b’, ’\B’). — end note ] 28.12.1.1 regex_iterator constructors [re.regiter.cnstr] regex_iterator();
1
Effects: Constructs an end-of-sequence iterator. regex_iterator(BidirectionalIterator a, BidirectionalIterator b, const regex_type& re, regex_constants::match_flag_type m = regex_constants::match_default);
2
Effects: Initializes begin and end to a and b, respectively, sets pregex to &re, sets flags to m, then calls regex_search(begin, end, match, *pregex, flags). If this call returns false the constructor sets *this to the end-of-sequence iterator. 28.12.1.2
regex_iterator comparisons
[re.regiter.comp]
bool operator==(const regex_iterator& right) const; 1
Returns: true if *this and right are both end-of-sequence iterators or if the following conditions all hold: — begin == right.begin, — end == right.end, — pregex == right.pregex, — flags == right.flags, and — match[0] == right.match[0]; otherwise false. bool operator!=(const regex_iterator& right) const;
2
Returns: !(*this == right).
§ 28.12.1.2
1089
c ISO/IEC
28.12.1.3
N3376
regex_iterator dereference
[re.regiter.deref]
const value_type& operator*() const; 1
Returns: match. const value_type* operator->() const;
2
Returns: &match. 28.12.1.4
regex_iterator increment
[re.regiter.incr]
regex_iterator& operator++(); 1
Effects: Constructs a local variable start of type BidirectionalIterator and initializes it with the value of match[0].second.
2
If the iterator holds a zero-length match and start == end the operator sets *this to the end-ofsequence iterator and returns *this.
3
Otherwise, if the iterator holds a zero-length match the operator calls regex_search(start, end, match, *pregex, flags | regex_constants::match_not_null | regex_constants::match_ continuous). If the call returns true the operator returns *this. Otherwise the operator increments start and continues as if the most recent match was not a zero-length match.
4
If the most recent match was not a zero-length match, the operator sets flags to flags | regex_constants ::match_prev_avail and calls regex_search(start, end, match, *pregex, flags). If the call returns false the iterator sets *this to the end-of-sequence iterator. The iterator then returns *this.
5
In all cases in which the call to regex_search returns true, match.prefix().first shall be equal to the previous value of match[0].second, and for each index i in the half-open range [0, match.size()) for which match[i].matched is true, match[i].position() shall return distance(begin, match[i]. first).
6
[ Note: This means that match[i].position() gives the offset from the beginning of the target sequence, which is often not the same as the offset from the sequence passed in the call to regex_search. — end note ]
7
It is unspecified how the implementation makes these adjustments.
8
[ Note: This means that a compiler may call an implementation-specific search function, in which case a user-defined specialization of regex_search will not be called. — end note ] regex_iterator operator++(int);
9
Effects: regex_iterator tmp = *this; ++(*this); return tmp;
28.12.2 1
Class template regex_token_iterator
[re.tokiter]
The class template regex_token_iterator is an iterator adaptor; that is to say it represents a new view of an existing iterator sequence, by enumerating all the occurrences of a regular expression within that sequence, and presenting one or more sub-expressions for each match found. Each position enumerated by the iterator is a sub_match class template instance that represents what matched a particular sub-expression within the regular expression. § 28.12.2
1090
c ISO/IEC
2
3
4
5
6
N3376
When class regex_token_iterator is used to enumerate a single sub-expression with index -1 the iterator performs field splitting: that is to say it enumerates one sub-expression for each section of the character container sequence that does not match the regular expression specified. After it is constructed, the iterator finds and stores a value regex_iterator position and sets the internal count N to zero. It also maintains a sequence subs which contains a list of the sub-expressions which will be enumerated. Every time operator++ is used the count N is incremented; if N exceeds or equals subs.size(), then the iterator increments member position and sets count N to zero. If the end of sequence is reached (position is equal to the end of sequence iterator), the iterator becomes equal to the end-of-sequence iterator value, unless the sub-expression being enumerated has index -1, in which case the iterator enumerates one last sub-expression that contains all the characters from the end of the last regular expression match to the end of the input sequence being enumerated, provided that this would not be an empty sub-expression. The default constructor constructs an end-of-sequence iterator object, which is the only legitimate iterator to be used for the end condition. The result of operator* on an end-of-sequence iterator is not defined. For any other iterator value a const sub_match& is returned. The result of operator-> on an end-of-sequence iterator is not defined. For any other iterator value a const sub_match* is returned. It is impossible to store things into regex_token_iterators. Two end-of-sequence iterators are always equal. An end-of-sequence iterator is not equal to a non-end-of-sequence iterator. Two non-end-of-sequence iterators are equal when they are constructed from the same arguments. namespace std { template ::value_type, class traits = regex_traits > class regex_token_iterator { public: typedef basic_regex regex_type; typedef sub_match value_type; typedef std::ptrdiff_t difference_type; typedef const value_type* pointer; typedef const value_type& reference; typedef std::forward_iterator_tag iterator_category; regex_token_iterator(); regex_token_iterator(BidirectionalIterator a, BidirectionalIterator b, const regex_type& re, int submatch = 0, regex_constants::match_flag_type m = regex_constants::match_default); regex_token_iterator(BidirectionalIterator a, BidirectionalIterator b, const regex_type& re, const std::vector& submatches, regex_constants::match_flag_type m = regex_constants::match_default); regex_token_iterator(BidirectionalIterator a, BidirectionalIterator b, const regex_type& re, initializer_list submatches, regex_constants::match_flag_type m = regex_constants::match_default); template <std::size_t N> regex_token_iterator(BidirectionalIterator a, BidirectionalIterator b, const regex_type& re,
§ 28.12.2
1091
c ISO/IEC
N3376
const int (&submatches)[N], regex_constants::match_flag_type m = regex_constants::match_default); regex_token_iterator(const regex_token_iterator&); regex_token_iterator& operator=(const regex_token_iterator&); bool operator==(const regex_token_iterator&) const; bool operator!=(const regex_token_iterator&) const; const value_type& operator*() const; const value_type* operator->() const; regex_token_iterator& operator++(); regex_token_iterator operator++(int); private: // data members for exposition only: typedef regex_iterator position_iterator; position_iterator position; const value_type *result; value_type suffix; std::size_t N; std::vector subs; }; } 7
8
9
A suffix iterator is a regex_token_iterator object that points to a final sequence of characters at the end of the target sequence. In a suffix iterator the member result holds a pointer to the data member suffix, the value of the member suffix.match is true, suffix.first points to the beginning of the final sequence, and suffix.second points to the end of the final sequence. [ Note: For a suffix iterator, data member suffix.first is the same as the end of the last match found, and suffix.second is the same as the end of the target sequence — end note ] The current match is (*position).prefix() if subs[N] == -1, or (*position)[subs[N]] for any other value of subs[N]. 28.12.2.1 regex_token_iterator constructors [re.tokiter.cnstr] regex_token_iterator();
1
Effects: Constructs the end-of-sequence iterator. regex_token_iterator(BidirectionalIterator a, BidirectionalIterator b, const regex_type& re, int submatch = 0, regex_constants::match_flag_type m = regex_constants::match_default); regex_token_iterator(BidirectionalIterator a, BidirectionalIterator b, const regex_type& re, const std::vector& submatches, regex_constants::match_flag_type m = regex_constants::match_default); regex_token_iterator(BidirectionalIterator a, BidirectionalIterator b, const regex_type& re, initializer_list submatches, regex_constants::match_flag_type m = regex_constants::match_default); template <std::size_t N> regex_token_iterator(BidirectionalIterator a, BidirectionalIterator b,
§ 28.12.2.1
1092
c ISO/IEC
N3376
const regex_type& re, const int (&submatches)[N], regex_constants::match_flag_type m = regex_constants::match_default); 2
Requires: Each of the initialization values of submatches shall be >= -1.
3
Effects: The first constructor initializes the member subs to hold the single value submatch. The second constructor initializes the member subs to hold a copy of the argument submatches. The third and fourth constructors initialize the member subs to hold a copy of the sequence of integer values pointed to by the iterator range [submatches.begin(),submatches.end()) and [&submatches,&submatches + N), respectively.
4
Each constructor then sets N to 0, and position to position_iterator(a, b, re, m). If position is not an end-of-sequence iterator the constructor sets result to the address of the current match. Otherwise if any of the values stored in subs is equal to -1 the constructor sets *this to a suffix iterator that points to the range [a,b), otherwise the constructor sets *this to an end-of-sequence iterator. 28.12.2.2
regex_token_iterator comparisons
[re.tokiter.comp]
bool operator==(const regex_token_iterator& right) const; 1
Returns: true if *this and right are both end-of-sequence iterators, or if *this and right are both suffix iterators and suffix == right.suffix; otherwise returns false if *this or right is an endof-sequence iterator or a suffix iterator. Otherwise returns true if position == right.position, N == right.N, and subs == right.subs. Otherwise returns false. bool operator!=(const regex_token_iterator& right) const;
2
Returns: !(*this == right). 28.12.2.3
regex_token_iterator dereference
[re.tokiter.deref]
const value_type& operator*() const; 1
Returns: *result. const value_type* operator->() const;
2
Returns: result. 28.12.2.4
regex_token_iterator increment
[re.tokiter.incr]
regex_token_iterator& operator++(); 1
Effects: Constructs a local variable prev of type position_iterator, initialized with the value of position.
2
If *this is a suffix iterator, sets *this to an end-of-sequence iterator.
3
Otherwise, if N + 1 < subs.size(), increments N and sets result to the address of the current match.
4
Otherwise, sets N to 0 and increments position. If position is not an end-of-sequence iterator the operator sets result to the address of the current match.
5
Otherwise, if any of the values stored in subs is equal to -1 and prev->suffix().length() is not 0 the operator sets *this to a suffix iterator that points to the range [prev->suffix().first, prev->suffix().second). § 28.12.2.4
1093
c ISO/IEC
6
N3376
Otherwise, sets *this to an end-of-sequence iterator. Returns: *this regex_token_iterator& operator++(int);
7
Effects: Constructs a copy tmp of *this, then calls ++(*this).
8
Returns: tmp.
28.13 1
2
3
Modified ECMAScript regular expression grammar
[re.grammar]
The regular expression grammar recognized by basic_regex objects constructed with the ECMAScript flag is that specified by ECMA-262, except as specified below. Objects of type specialization of basic_regex store within themselves a default-constructed instance of their traits template parameter, henceforth referred to as traits_inst. This traits_inst object is used to support localization of the regular expression; basic_regex member functions shall not call any locale dependent C or C++ API, including the formatted string input functions. Instead they shall call the appropriate traits member function to achieve the required effect. The following productions within the ECMAScript grammar are modified as follows: ClassAtom :: ClassAtomNoDash ClassAtomExClass ClassAtomCollatingElement ClassAtomEquivalence
4
The following new productions are then added: ClassAtomExClass :: [: ClassName :] ClassAtomCollatingElement :: [. ClassName .] ClassAtomEquivalence :: [= ClassName =] ClassName :: ClassNameCharacter ClassNameCharacter ClassName ClassNameCharacter :: SourceCharacter but not one of "." "=" ":"
5
6
7
The productions ClassAtomExClass, ClassAtomCollatingElement and ClassAtomEquivalence provide functionality equivalent to that of the same features in regular expressions in POSIX. The regular expression grammar may be modified by any regex_constants::syntax_option_type flags specified when constructing an object of type specialization of basic_regex according to the rules in Table 138. A ClassName production, when used in ClassAtomExClass, is not valid if traits_inst.lookup_classname returns zero for that name. The names recognized as valid ClassNames are determined by the type of the traits class, but at least the following names shall be recognized: alnum, alpha, blank, cntrl, digit, graph, lower, print, punct, space, upper, xdigit, d, s, w. In addition the following expressions shall be equivalent: § 28.13
1094
c ISO/IEC
N3376
\d and [[:digit:]] \D and [^[:digit:]] \s and [[:space:]] \S and [^[:space:]] \w and [_[:alnum:]] \W and [^_[:alnum:]] 8
9
10
11
12
13
14
A ClassName production when used in a ClassAtomCollatingElement production is not valid if the value returned by traits_inst.lookup_collatename for that name is an empty string. The results from multiple calls to traits_inst.lookup_classname can be bitwise OR’ed together and subsequently passed to traits_inst.isctype. A ClassName production when used in a ClassAtomEquivalence production is not valid if the value returned by traits_inst.lookup_collatename for that name is an empty string or if the value returned by traits_inst.transform_primary for the result of the call to traits_inst.lookup_collatename is an empty string. When the sequence of characters being transformed to a finite state machine contains an invalid class name the translator shall throw an exception object of type regex_error. If the CV of a UnicodeEscapeSequence is greater than the largest value that can be held in an object of type charT the translator shall throw an exception object of type regex_error. [ Note: This means that values of the form "uxxxx" that do not fit in a character are invalid. — end note ] Where the regular expression grammar requires the conversion of a sequence of characters to an integral value, this is accomplished by calling traits_inst.value. The behavior of the internal finite state machine representation when used to match a sequence of characters is as described in ECMA-262. The behavior is modified according to any match_flag_type flags 28.5.2 specified when using the regular expression object in one of the regular expression algorithms 28.11. The behavior is also localized by interaction with the traits class template parameter as follows: — During matching of a regular expression finite state machine against a sequence of characters, two characters c and d are compared using the following rules: 1. if (flags() & regex_constants::icase) the two characters are equal if traits_inst.translate_nocase(c) == traits_inst.translate_nocase(d); 2. otherwise, if flags() & regex_constants::collate the two characters are equal if traits_inst.translate(c) == traits_inst.translate(d); 3. otherwise, the two characters are equal if c == d. — During matching of a regular expression finite state machine against a sequence of characters, comparison of a collating element range c1-c2 against a character c is conducted as follows: if flags() & regex_constants ::collate is false then the character c is matched if c1 & y) noexcept; template int try_lock(L1&, L2&, L3&...); template void lock(L1&, L2&, L3&...); struct once_flag { constexpr once_flag() noexcept; once_flag(const once_flag&) = delete; once_flag& operator=(const once_flag&) = delete; }; template void call_once(once_flag& flag, Callable func, Args&&... args); }
30.4.1 1
1
2 3
4
Mutex requirements
[thread.mutex.requirements]
30.4.1.1 In general [thread.mutex.requirements.general] A mutex object facilitates protection against data races and allows safe synchronization of data between execution agents (30.2.5). An execution agent owns a mutex from the time it successfully calls one of the lock functions until it calls unlock. Mutexes can be either recursive or non-recursive, and can grant simultaneous ownership to one or many execution agents. The mutex types supplied by the standard library provide exclusive ownership semantics: only one thread may own the mutex at a time. Both recursive and non-recursive mutexes are supplied. 30.4.1.2 Mutex types [thread.mutex.requirements.mutex] The mutex types are the standard library types std::mutex, std::recursive_mutex, std::timed_mutex, and std::recursive_timed_mutex. They shall meet the requirements set out in this section. In this description, m denotes an object of a mutex type. The mutex types shall meet the Lockable requirements (30.2.5.3). The mutex types shall be DefaultConstructible and Destructible. If initialization of an object of a mutex type fails, an exception of type system_error shall be thrown. The mutex types shall not be copyable or movable. The error conditions for error codes, if any, reported by member functions of the mutex types shall be: — resource_unavailable_try_again — if any native handle type manipulated is not available. — operation_not_permitted — if the thread does not have the privilege to perform the operation. § 30.4.1.2
1124
c ISO/IEC
N3376
— device_or_resource_busy — if any native handle type manipulated is already locked. — invalid_argument — if any native handle type manipulated as part of mutex construction is incorrect. 5
6
The implementation shall provide lock and unlock operations, as described below. For purposes of determining the existence of a data race, these behave as atomic operations (1.10). The lock and unlock operations on a single mutex shall appear to occur in a single total order. [ Note: this can be viewed as the modification order (1.10) of the mutex. — end note ] [ Note: Construction and destruction of an object of a mutex type need not be thread-safe; other synchronization should be used to ensure that mutex objects are initialized and visible to other threads. — end note ] The expression m.lock() shall be well-formed and have the following semantics:
7
Requires: If m is of type std::mutex or std::timed_mutex, the calling thread does not own the mutex.
8
Effects: Blocks the calling thread until ownership of the mutex can be obtained for the calling thread.
9
Postcondition: The calling thread owns the mutex.
10
Return type: void
11
Synchronization: Prior unlock() operations on the same object shall synchronize with (1.10) this operation.
12
Throws: system_error when an exception is required (30.2.2).
13
Error conditions: — operation_not_permitted — if the thread does not have the privilege to perform the operation. — resource_deadlock_would_occur — if the implementation detects that a deadlock would occur. — device_or_resource_busy — if the mutex is already locked and blocking is not possible.
14
The expression m.try_lock() shall be well-formed and have the following semantics:
15
Requires: If m is of type std::mutex or std::timed_mutex, the calling thread does not own the mutex.
16
Effects: Attempts to obtain ownership of the mutex for the calling thread without blocking. If ownership is not obtained, there is no effect and try_lock() immediately returns. An implementation may fail to obtain the lock even if it is not held by any other thread. [ Note: This spurious failure is normally uncommon, but allows interesting implementations based on a simple compare and exchange (Clause 29). — end note ] An implementation should ensure that try_lock() does not consistently return false in the absence of contending mutex acquisitions.
17
Return type: bool
18
Returns: true if ownership of the mutex was obtained for the calling thread, otherwise false.
19
Synchronization: If try_lock() returns true, prior unlock() operations on the same object synchronize with (1.10) this operation. [ Note: Since lock() does not synchronize with a failed subsequent try_lock(), the visibility rules are weak enough that little would be known about the state after a failure, even in the absence of spurious failures. — end note ]
20
Throws: Nothing.
21
The expression m.unlock() shall be well-formed and have the following semantics:
22
Requires: The calling thread shall own the mutex.
23
Effects: Releases the calling thread’s ownership of the mutex.
24
Return type: void
25
Synchronization: This operation synchronizes with (1.10) subsequent lock operations that obtain ownership on the same object.
26
Throws: Nothing. § 30.4.1.2
1125
c ISO/IEC
30.4.1.2.1
N3376
Class mutex
[thread.mutex.class]
namespace std { class mutex { public: constexpr mutex() noexcept; ~mutex(); mutex(const mutex&) = delete; mutex& operator=(const mutex&) = delete; void lock(); bool try_lock(); void unlock(); typedef implementation-defined native_handle_type; // See 30.2.3 native_handle_type native_handle(); // See 30.2.3 }; } 1
2
3
4
5
The class mutex provides a non-recursive mutex with exclusive ownership semantics. If one thread owns a mutex object, attempts by another thread to acquire ownership of that object will fail (for try_lock()) or block (for lock()) until the owning thread has released ownership with a call to unlock(). [ Note: After a thread A has called unlock(), releasing a mutex, it is possible for another thread B to lock the same mutex, observe that it is no longer in use, unlock it, and destroy it, before thread A appears to have returned from its unlock call. Implementations are required to handle such scenarios correctly, as long as thread A doesn’t access the mutex after the unlock call returns. These cases typically occur when a reference-counted object contains a mutex that is used to protect the reference count. — end note ] The class mutex shall satisfy all the Mutex requirements (30.4.1). It shall be a standard-layout class (Clause 9). [ Note: A program may deadlock if the thread that owns a mutex object calls lock() on that object. If the implementation can detect the deadlock, a resource_deadlock_would_occur error condition may be observed. — end note ] The behavior of a program is undefined if it destroys a mutex object owned by any thread or a thread terminates while owning a mutex object. 30.4.1.2.2 Class recursive_mutex [thread.mutex.recursive] namespace std { class recursive_mutex { public: recursive_mutex(); ~recursive_mutex(); recursive_mutex(const recursive_mutex&) = delete; recursive_mutex& operator=(const recursive_mutex&) = delete; void lock(); bool try_lock() noexcept; void unlock(); typedef implementation-defined native_handle_type; // See 30.2.3 native_handle_type native_handle(); // See 30.2.3 }; }
§ 30.4.1.2.2
1126
c ISO/IEC
1
2
3
4
N3376
The class recursive_mutex provides a recursive mutex with exclusive ownership semantics. If one thread owns a recursive_mutex object, attempts by another thread to acquire ownership of that object will fail (for try_lock()) or block (for lock()) until the first thread has completely released ownership. The class recursive_mutex shall satisfy all the Mutex requirements (30.4.1). It shall be a standard-layout class (Clause 9). A thread that owns a recursive_mutex object may acquire additional levels of ownership by calling lock() or try_lock() on that object. It is unspecified how many levels of ownership may be acquired by a single thread. If a thread has already acquired the maximum level of ownership for a recursive_mutex object, additional calls to try_lock() shall fail, and additional calls to lock() shall throw an exception of type system_error. A thread shall call unlock() once for each level of ownership acquired by calls to lock() and try_lock(). Only when all levels of ownership have been released may ownership be acquired by another thread. The behavior of a program is undefined if: — it destroys a recursive_mutex object owned by any thread or — a thread terminates while owning a recursive_mutex object. 30.4.1.3
1
2 3 4
Timed mutex types
[thread.timedmutex.requirements]
The timed mutex types are the standard library types std::timed_mutex and std::recursive_timed_mutex. They shall meet the requirements set out below. In this description, m denotes an object of a mutex type, rel_time denotes an object of an instantiation of duration (20.11.5), and abs_time denotes an object of an instantiation of time_point (20.11.6). The timed mutex types shall meet the TimedLockable requirements (30.2.5.4). The expression m.try_lock_for(rel_time) shall be well-formed and have the following semantics: Requires: If the tick period of rel_time is not exactly convertible to the native tick period, the duration shall be rounded up to the nearest native tick period. If m is of type std::timed_mutex, the calling thread does not own the mutex.
5
Effects: The function attempts to obtain ownership of the mutex within the relative timeout (30.2.4) specified by rel_time. If the time specified by rel_time is less than or equal to rel_time.zero(), the function attempts to obtain ownership without blocking (as if by calling try_lock()). The function shall return within the timeout specified by rel_time only if it has obtained ownership of the mutex object. [ Note: As with try_lock(), there is no guarantee that ownership will be obtained if the lock is available, but implementations are expected to make a strong effort to do so. — end note ]
6
Return type: bool
7
Returns: true if ownership was obtained, otherwise false.
8
Synchronization: If try_lock_for() returns true, prior unlock() operations on the same object synchronize with (1.10) this operation.
9
Throws: Nothing.
10
The expression m.try_lock_until(abs_time) shall be well-formed and have the following semantics:
11
Requires: If m is of type std::timed_mutex, the calling thread does not own the mutex.
12
Effects: The function attempts to obtain ownership of the mutex. If abs_time has already passed, the function attempts to obtain ownership without blocking (as if by calling try_lock()). The function shall return before the absolute timeout (30.2.4) specified by abs_time only if it has obtained ownership of the mutex object. [ Note: As with try_lock(), there is no guarantee that ownership will be obtained if the lock is available, but implementations are expected to make a strong effort to do so. — end note ]
13
Return type: bool § 30.4.1.3
1127
c ISO/IEC
N3376
14
Returns: true if ownership was obtained, otherwise false.
15
Synchronization: If try_lock_until() returns true, prior unlock() operations on the same object synchronize with (1.10) this operation.
16
Throws: Nothing. 30.4.1.3.1
Class timed_mutex
[thread.timedmutex.class]
namespace std { class timed_mutex { public: timed_mutex(); ~timed_mutex(); timed_mutex(const timed_mutex&) = delete; timed_mutex& operator=(const timed_mutex&) = delete; void lock(); bool try_lock(); template bool try_lock_for(const chrono::duration& rel_time); template bool try_lock_until(const chrono::time_point& abs_time); void unlock(); typedef implementation-defined native_handle_type; // See 30.2.3 native_handle_type native_handle(); // See 30.2.3 }; } 1
2
3
The class timed_mutex provides a non-recursive mutex with exclusive ownership semantics. If one thread owns a timed_mutex object, attempts by another thread to acquire ownership of that object will fail (for try_lock()) or block (for lock(), try_lock_for(), and try_lock_until()) until the owning thread has released ownership with a call to unlock() or the call to try_lock_for() or try_lock_until() times out (having failed to obtain ownership). The class timed_mutex shall satisfy all of the TimedMutex requirements (30.4.1.3). It shall be a standardlayout class (Clause 9). The behavior of a program is undefined if: — it destroys a timed_mutex object owned by any thread, — a thread that owns a timed_mutex object calls lock(), try_lock(), try_lock_for(), or try_lock_until() on that object, or — a thread terminates while owning a timed_mutex object. 30.4.1.3.2
Class recursive_timed_mutex
[thread.timedmutex.recursive]
namespace std { class recursive_timed_mutex { public: recursive_timed_mutex(); ~recursive_timed_mutex(); recursive_timed_mutex(const recursive_timed_mutex&) = delete; recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete;
§ 30.4.1.3.2
1128
c ISO/IEC
N3376
void lock(); bool try_lock() noexcept; template bool try_lock_for(const chrono::duration& rel_time); template bool try_lock_until(const chrono::time_point& abs_time); void unlock(); typedef implementation-defined native_handle_type; // See 30.2.3 native_handle_type native_handle(); // See 30.2.3 }; } 1
2
3
4
The class recursive_timed_mutex provides a recursive mutex with exclusive ownership semantics. If one thread owns a recursive_timed_mutex object, attempts by another thread to acquire ownership of that object will fail (for try_lock()) or block (for lock(), try_lock_for(), and try_lock_until()) until the owning thread has completely released ownership or the call to try_lock_for() or try_lock_until() times out (having failed to obtain ownership). The class recursive_timed_mutex shall satisfy all of the TimedMutex requirements (30.4.1.3). It shall be a standard-layout class (Clause 9). A thread that owns a recursive_timed_mutex object may acquire additional levels of ownership by calling lock(), try_lock(), try_lock_for(), or try_lock_until() on that object. It is unspecified how many levels of ownership may be acquired by a single thread. If a thread has already acquired the maximum level of ownership for a recursive_timed_mutex object, additional calls to try_lock(), try_lock_for(), or try_lock_until() shall fail, and additional calls to lock() shall throw an exception of type system_error. A thread shall call unlock() once for each level of ownership acquired by calls to lock(), try_lock(), try_lock_for(), and try_lock_until(). Only when all levels of ownership have been released may ownership of the object be acquired by another thread. The behavior of a program is undefined if: — it destroys a recursive_timed_mutex object owned by any thread, or — a thread terminates while owning a recursive_timed_mutex object.
30.4.2 1
2
Locks
[thread.lock]
A lock is an object that holds a reference to a lockable object and may unlock the lockable object during the lock’s destruction (such as when leaving block scope). An execution agent may use a lock to aid in managing ownership of a lockable object in an exception safe manner. A lock is said to own a lockable object if it is currently managing the ownership of that lockable object for an execution agent. A lock does not manage the lifetime of the lockable object it references. [ Note: Locks are intended to ease the burden of unlocking the lockable object under both normal and exceptional circumstances. — end note ] Some lock constructors take tag types which describe what should be done with the lockable object during the lock’s construction. namespace std { struct defer_lock_t { }; struct try_to_lock_t { }; struct adopt_lock_t
{ };
// // // // //
constexpr defer_lock_t constexpr try_to_lock_t constexpr adopt_lock_t
do not acquire ownership of the mutex try to acquire ownership of the mutex without blocking assume the calling thread has already obtained mutex ownership and manage it
defer_lock { }; try_to_lock { }; adopt_lock { };
}
§ 30.4.2
1129
c ISO/IEC
30.4.2.1
Class template lock_guard
N3376
[thread.lock.guard]
namespace std { template class lock_guard { public: typedef Mutex mutex_type; explicit lock_guard(mutex_type& m); lock_guard(mutex_type& m, adopt_lock_t); ~lock_guard(); lock_guard(lock_guard const&) = delete; lock_guard& operator=(lock_guard const&) = delete; private: mutex_type& pm; // exposition only }; } 1
An object of type lock_guard controls the ownership of a lockable object within a scope. A lock_guard object maintains ownership of a lockable object throughout the lock_guard object’s lifetime (3.8). The behavior of a program is undefined if the lockable object referenced by pm does not exist for the entire lifetime of the lock_guard object. The supplied Mutex type shall meet the BasicLockable requirements (30.2.5.2). explicit lock_guard(mutex_type& m);
2
Requires: If mutex_type is not a recursive mutex, the calling thread does not own the mutex m.
3
Effects: m.lock()
4
Postcondition: &pm == &m lock_guard(mutex_type& m, adopt_lock_t);
5
Requires: The calling thread owns the mutex m.
6
Postcondition: &pm == &m
7
Throws: Nothing. ~lock_guard();
8
Effects: pm.unlock() 30.4.2.2
Class template unique_lock
[thread.lock.unique]
namespace std { template class unique_lock { public: typedef Mutex mutex_type; // 30.4.2.2.1, construct/copy/destroy: unique_lock() noexcept; explicit unique_lock(mutex_type& m); unique_lock(mutex_type& m, defer_lock_t) noexcept; unique_lock(mutex_type& m, try_to_lock_t);
§ 30.4.2.2
1130
c ISO/IEC
N3376
unique_lock(mutex_type& m, adopt_lock_t); template unique_lock(mutex_type& m, const chrono::time_point& abs_time); template unique_lock(mutex_type& m, const chrono::duration& rel_time); ~unique_lock(); unique_lock(unique_lock const&) = delete; unique_lock& operator=(unique_lock const&) = delete; unique_lock(unique_lock&& u) noexcept; unique_lock& operator=(unique_lock&& u) noexcept; // 30.4.2.2.2, locking: void lock(); bool try_lock(); template bool try_lock_for(const chrono::duration& rel_time); template bool try_lock_until(const chrono::time_point& abs_time); void unlock(); // 30.4.2.2.3, modifiers: void swap(unique_lock& u) noexcept; mutex_type *release() noexcept; // 30.4.2.2.4, observers: bool owns_lock() const noexcept; explicit operator bool () const noexcept; mutex_type* mutex() const noexcept; private: mutex_type *pm; // exposition only bool owns; // exposition only }; template void swap(unique_lock<Mutex>& x, unique_lock<Mutex>& y) noexcept; } 1
2
An object of type unique_lock controls the ownership of a lockable object within a scope. Ownership of the lockable object may be acquired at construction or after construction, and may be transferred, after acquisition, to another unique_lock object. Objects of type unique_lock are not copyable but are movable. The behavior of a program is undefined if the contained pointer pm is not null and the lockable object pointed to by pm does not exist for the entire remaining lifetime (3.8) of the unique_lock object. The supplied Mutex type shall meet the BasicLockable requirements (30.2.5.2). [ Note: unique_lock<Mutex> meets the BasicLockable requirements. If Mutex meets the Lockable requirements (30.2.5.3), unique_lock<Mutex> also meets the Lockable requirements; if Mutex meets the TimedLockable requirements (30.2.5.4), unique_lock<Mutex> also meets the TimedLockable requirements. — end note ] 30.4.2.2.1 unique_lock constructors, destructor, and assignment [thread.lock.unique.cons] unique_lock() noexcept;
§ 30.4.2.2.1
1131
c ISO/IEC
1
Effects: Constructs an object of type unique_lock.
2
Postconditions: pm == 0 and owns == false.
N3376
explicit unique_lock(mutex_type& m); 3
Requires: If mutex_type is not a recursive mutex the calling thread does not own the mutex.
4
Effects: Constructs an object of type unique_lock and calls m.lock().
5
Postconditions: pm == &m and owns == true. unique_lock(mutex_type& m, defer_lock_t) noexcept;
6
Effects: Constructs an object of type unique_lock.
7
Postconditions: pm == &m and owns == false. unique_lock(mutex_type& m, try_to_lock_t);
8
Requires: The supplied Mutex type shall meet the Lockable requirements (30.2.5.3). If mutex_type is not a recursive mutex the calling thread does not own the mutex.
9
Effects: Constructs an object of type unique_lock and calls m.try_lock().
10
Postconditions: pm == &m and owns == res, where res is the value returned by the call to m.try_lock(). unique_lock(mutex_type& m, adopt_lock_t);
11
Requires: The calling thread own the mutex.
12
Effects: Constructs an object of type unique_lock.
13
Postconditions: pm == &m and owns == true.
14
Throws: Nothing. template unique_lock(mutex_type& m, const chrono::time_point& abs_time);
15
Requires: If mutex_type is not a recursive mutex the calling thread does not own the mutex. The supplied Mutex type shall meet the TimedLockable requirements (30.2.5.4).
16
Effects: Constructs an object of type unique_lock and calls m.try_lock_until(abs_time).
17
Postconditions: pm == &m and owns == res, where res is the value returned by the call to m.try_lock_until(abs_time). template unique_lock(mutex_type& m, const chrono::duration& rel_time);
18
Requires: If mutex_type is not a recursive mutex the calling thread does not own the mutex. The supplied Mutex type shall meet the TimedLockable requirements (30.2.5.4).
19
Effects: Constructs an object of type unique_lock and calls m.try_lock_for(rel_time).
20
Postconditions: pm == &m and owns == res, where res is the value returned by the call to m.try_lock_for(rel_time). § 30.4.2.2.1
1132
c ISO/IEC
N3376
unique_lock(unique_lock&& u) noexcept; 21
Postconditions: pm == u_p.pm and owns == u_p.owns (where u_p is the state of u just prior to this construction), u.pm == 0 and u.owns == false. unique_lock& operator=(unique_lock&& u) noexcept;
22
Effects: If owns calls pm->unlock().
23
Postconditions: pm == u_p.pm and owns == u_p.owns (where u_p is the state of u just prior to this construction), u.pm == 0 and u.owns == false.
24
[ Note: With a recursive mutex it is possible for both *this and u to own the same mutex before the assignment. In this case, *this will own the mutex after the assignment and u will not. — end note ] ~unique_lock();
25
Effects: If owns calls pm->unlock(). 30.4.2.2.2
unique_lock locking
[thread.lock.unique.locking]
void lock(); 1
Effects: pm->lock()
2
Postcondition: owns == true
3
Throws: Any exception thrown by pm->lock(). system_error if an exception is required (30.2.2). system_error with an error condition of operation_not_permitted if pm is 0. system_error with an error condition of resource_deadlock_would_occur if on entry owns is true. bool try_lock();
4
Requires: The supplied Mutex shall meet the Lockable requirements (30.2.5.3).
5
Effects: pm->try_lock()
6
Returns: The value returned by the call to try_lock().
7
Postcondition: owns == res, where res is the value returned by the call to try_lock().
8
Throws: Any exception thrown by pm->try_lock(). system_error if an exception is required (30.2.2). system_error with an error condition of operation_not_permitted if pm is 0. system_error with an error condition of resource_deadlock_would_occur if on entry owns is true. template bool try_lock_until(const chrono::time_point& abs_time);
9
Requires: The supplied Mutex type shall meet the TimedLockable requirements (30.2.5.4).
10
Effects: pm->try_lock_until(abs_time)
11
Returns: The value returned by the call to try_lock_until(abs_time).
12
Postcondition: owns == res, where res is the value returned by the call to try_lock_until(abs_time).
13
Throws: Any exception thrown by pm->try_lock_until(). system_error if an exception is required (30.2.2). system_error with an error condition of operation_not_permitted if pm is 0. system_error with an error condition of resource_deadlock_would_occur if on entry owns is true. § 30.4.2.2.2
1133
c ISO/IEC
N3376
template bool try_lock_for(const chrono::duration& rel_time); 14
Requires: The supplied Mutex type shall meet the TimedLockable requirements (30.2.5.4).
15
Effects: pm->try_lock_for(rel_time).
16
Returns: The value returned by the call to try_lock_until(rel_time).
17
Postcondition: owns == res, where res is the value returned by the call to try_lock_for(rel_time).
18
Throws: Any exception thrown by pm->try_lock_for(). system_error if an exception is required (30.2.2). system_error with an error condition of operation_not_permitted if pm is 0. system_error with an error condition of resource_deadlock_would_occur if on entry owns is true. void unlock();
19
Effects: pm->unlock()
20
Postcondition: owns == false
21
Throws: system_error when an exception is required (30.2.2).
22
Error conditions: — operation_not_permitted — if on entry owns is false. 30.4.2.2.3
unique_lock modifiers
[thread.lock.unique.mod]
void swap(unique_lock& u) noexcept; 1
Effects: Swaps the data members of *this and u. mutex_type *release() noexcept;
2
Returns: The previous value of pm.
3
Postconditions: pm == 0 and owns == false. template void swap(unique_lock<Mutex>& x, unique_lock<Mutex>& y) noexcept;
4
Effects: x.swap(y) 30.4.2.2.4
unique_lock observers
[thread.lock.unique.obs]
bool owns_lock() const noexcept; 1
Returns: owns explicit operator bool() const noexcept;
2
Returns: owns mutex_type *mutex() const noexcept;
3
Returns: pm § 30.4.2.2.4
1134
c ISO/IEC
30.4.3
Generic locking algorithms
N3376
[thread.lock.algorithm]
template int try_lock(L1&, L2&, L3&...); 1
Requires: Each template parameter type shall meet the Lockable requirements. [ Note: The unique_lock class template meets these requirements when suitably instantiated. — end note ]
2
Effects: Calls try_lock() for each argument in order beginning with the first until all arguments have been processed or a call to try_lock() fails, either by returning false or by throwing an exception. If a call to try_lock() fails, unlock() shall be called for all prior arguments and there shall be no further calls to try_lock().
3
Returns: -1 if all calls to try_lock() returned true, otherwise a 0-based index value that indicates the argument for which try_lock() returned false. template void lock(L1&, L2&, L3&...);
4
Requires: Each template parameter type shall meet the Lockable requirements, [ Note: The unique_lock class template meets these requirements when suitably instantiated. — end note ]
5
Effects: All arguments are locked via a sequence of calls to lock(), try_lock(), or unlock() on each argument. The sequence of calls shall not result in deadlock, but is otherwise unspecified. [ Note: A deadlock avoidance algorithm such as try-and-back-off must be used, but the specific algorithm is not specified to avoid over-constraining implementations. — end note ] If a call to lock() or try_lock() throws an exception, unlock() shall be called for any argument that had been locked by a call to lock() or try_lock().
30.4.4
Call once
[thread.once]
The class once_flag is an opaque data structure that call_once uses to initialize data without causing a data race or deadlock. 30.4.4.1 Struct once_flag [thread.once.onceflag] constexpr once_flag() noexcept; 1
Effects: Constructs an object of type once_flag.
2
Synchronization: The construction of a once_flag object is not synchronized.
3
Postcondition: The object’s internal state is set to indicate to an invocation of call_once with the object as its initial argument that no function has been called. 30.4.4.2
Function call_once
[thread.once.callonce]
template void call_once(once_flag& flag, Callable&& func, Args&&... args); 1
Requires: Callable and each Ti in Args shall satisfy the MoveConstructible requirements. INVOKE ( DECAY_COPY ( std::forward(func)), DECAY_COPY (std::forward(args))...) (20.8.2) shall be a valid expression.
2
Effects: An execution of call_once that does not call its func is a passive execution. An execution of call_once that calls its func is an active execution. An active execution shall call INVOKE (DECAY_COPY ( std::forward(func)), DECAY_COPY (std::forward(args))...). If such a call to func throws an exception the execution is exceptional, otherwise it is returning. An exceptional execution shall propagate the exception to the caller of call_once. Among all executions of call_once for any given once_flag: at most one shall be a returning execution; if there is a returning execution, it shall be the last active execution; and there are passive executions only if there is a § 30.4.4.2
1135
c ISO/IEC
N3376
returning execution. [ Note: passive executions allow other threads to reliably observe the results produced by the earlier returning execution. — end note ] 3
Synchronization: For any given once_flag: all active executions occur in a total order; completion of an active execution synchronizes with (1.10) the start of the next one in this total order; and the returning execution synchronizes with the return from all passive executions.
4
Throws: system_error when an exception is required (30.2.2), or any exception thrown by func.
5
Error conditions: — invalid_argument — if the once_flag object is no longer valid.
6
[ Example: // global flag, regular function void init(); std::once_flag flag; void f() { std::call_once(flag, init); } // function static flag, function object struct initializer { void operator()(); }; void g() { static std::once_flag flag2; std::call_once(flag2, initializer()); } // object flag, member function class information { std::once_flag verified; void verifier(); public: void verify() { std::call_once(verified, &information::verifier, *this); } };
— end example ]
30.5 1
2
3
Condition variables
[thread.condition]
Condition variables provide synchronization primitives used to block a thread until notified by some other thread that some condition is met or until a system time is reached. Class condition_variable provides a condition variable that can only wait on an object of type unique_lock<mutex>, allowing maximum efficiency on some platforms. Class condition_variable_any provides a general condition variable that can wait on objects of user-supplied lock types. Condition variables permit concurrent invocation of the wait, wait_for, wait_until, notify_one and notify_all member functions. The execution of notify_one and notify_all shall be atomic. The execution of wait, wait_for, and wait_until shall be performed in three atomic parts: 1. the release of the mutex and entry into the waiting state; 2. the unblocking of the wait; and § 30.5
1136
c ISO/IEC
N3376
3. the reacquisition of the lock. 4
5
The implementation shall behave as if notify_one, notify_all, and each part of the wait, wait_for, and wait_until executions are executed in some unspecified total order. Condition variable construction and destruction need not be synchronized. Header condition_variable synopsis namespace std { class condition_variable; class condition_variable_any; void notify_all_at_thread_exit(condition_variable& cond, unique_lock<mutex> lk); enum class cv_status { no_timeout, timeout }; } void notify_all_at_thread_exit(condition_variable& cond, unique_lock<mutex> lk);
6
Requires: lk is locked by the calling thread and either — no other thread is waiting on cond, or — lk.mutex() returns the same value for each of the lock arguments supplied by all concurrently waiting (via wait, wait_for, or wait_until) threads.
7
Effects: transfers ownership of the lock associated with lk into internal storage and schedules cond to be notified when the current thread exits, after all objects of thread storage duration associated with the current thread have been destroyed. This notification shall be as if lk.unlock(); cond.notify_all();
8
Synchronization: The call to notify_all_at_thread_exit and the completion of the destructors for all the current thread’s variables of thread storage duration synchronize with (1.10) calls to functions waiting on cond.
9
Note: The supplied lock will be held until the thread exits, and care must be taken to ensure that this does not cause deadlock due to lock ordering issues. After calling notify_all_at_thread_exit it is recommended that the thread should be exited as soon as possible, and that no blocking or time-consuming tasks are run on that thread.
10
Note: It is the user’s responsibility to ensure that waiting threads do not erroneously assume that the thread has finished if they experience spurious wakeups. This typically requires that the condition being waited for is satisfied while holding the lock on lk, and that this lock is not released and reacquired prior to calling notify_all_at_thread_exit.
30.5.1
Class condition_variable
[thread.condition.condvar]
namespace std { class condition_variable { public: condition_variable(); ~condition_variable(); condition_variable(const condition_variable&) = delete;
§ 30.5.1
1137
c ISO/IEC
N3376
condition_variable& operator=(const condition_variable&) = delete; void notify_one() noexcept; void notify_all() noexcept; void wait(unique_lock<mutex>& lock); template void wait(unique_lock<mutex>& lock, Predicate pred); template cv_status wait_until(unique_lock<mutex>& lock, const chrono::time_point& abs_time); template bool wait_until(unique_lock<mutex>& lock, const chrono::time_point& abs_time, Predicate pred); template cv_status wait_for(unique_lock<mutex>& lock, const chrono::duration& rel_time); template bool wait_for(unique_lock<mutex>& lock, const chrono::duration& rel_time, Predicate pred); typedef implementation-defined native_handle_type; // See 30.2.3 native_handle_type native_handle(); // See 30.2.3 }; } 1
The class condition_variable shall be a standard-layout class (Clause 9). condition_variable();
2
Effects: Constructs an object of type condition_variable.
3
Throws: system_error when an exception is required (30.2.2).
4
Error conditions: — resource_unavailable_try_again — if some non-memory resource limitation prevents initialization. ~condition_variable();
5
Requires: There shall be no thread blocked on *this. [ Note: That is, all threads shall have been notified; they may subsequently block on the lock specified in the wait. This relaxes the usual rules, which would have required all wait calls to happen before destruction. Only the notification to unblock the wait must happen before destruction. The user must take care to ensure that no threads wait on *this once the destructor has been started, especially when the waiting threads are calling the wait functions in a loop or using the overloads of wait, wait_for, or wait_until that take a predicate. — end note ]
6
Effects: Destroys the object. void notify_one() noexcept;
7
Effects: If any threads are blocked waiting for *this, unblocks one of those threads. § 30.5.1
1138
c ISO/IEC
N3376
void notify_all() noexcept; 8
Effects: Unblocks all threads that are blocked waiting for *this. void wait(unique_lock<mutex>& lock);
9
Requires: lock.owns_lock() is true and lock.mutex() is locked by the calling thread, and either — no other thread is waiting on this condition_variable object or — lock.mutex() returns the same value for each of the lock arguments supplied by all concurrently waiting (via wait or timed_wait) threads.
10
Effects: — Atomically calls lock.unlock() and blocks on *this. — When unblocked, calls lock.lock() (possibly blocking on the lock), then returns. — The function will unblock when signaled by a call to notify_one() or a call to notify_all(), or spuriously. — If the function exits via an exception, lock.lock() shall be called prior to exiting the function scope.
11
Postcondition: lock.owns_lock() is true and lock.mutex() is locked by the calling thread.
12
Throws: system_error when an exception is required (30.2.2).
13
Error conditions: — equivalent error condition from lock.lock() or lock.unlock(). template void wait(unique_lock<mutex>& lock, Predicate pred);
14
Requires: lock.owns_lock() is true and lock.mutex() is locked by the calling thread, and either — no other thread is waiting on this condition_variable object or — lock.mutex() returns the same value for each of the lock arguments supplied by all concurrently waiting (via wait or timed_wait) threads.
15
Effects: while (!pred()) wait(lock);
16
Postcondition: lock.owns_lock() is true and lock.mutex() is locked by the calling thread.
17
Throws: std::system_error when an exception is required (30.2.2).
18
Error conditions: — equivalent error condition from lock.lock() or lock.unlock(). template cv_status wait_until(unique_lock<mutex>& lock, const chrono::time_point& abs_time);
§ 30.5.1
1139
c ISO/IEC
19
N3376
Requires: lock.owns_lock() is true and lock.mutex() is locked by the calling thread, and either — no other thread is waiting on this condition_variable object or — lock.mutex() returns the same value for each of the lock arguments supplied by all concurrently waiting (via wait, wait_for, or wait_until) threads.
20
Effects: — Atomically calls lock.unlock() and blocks on *this. — When unblocked, calls lock.lock() (possibly blocking on the lock), then returns. — The function will unblock when signaled by a call to notify_one(), a call to notify_all(), expiration of the absolute timeout (30.2.4) specified by abs_time, or spuriously. — If the function exits via an exception, lock.lock() shall be called prior to exiting the function scope.
21
Postcondition: lock.owns_lock() is true and lock.mutex() is locked by the calling thread.
22
Returns: cv_status::timeout if the absolute timeout (30.2.4) specified by abs_time expired, otherwise cv_status::no_timeout.
23
Throws: system_error when an exception is required (30.2.2).
24
Error conditions: — equivalent error condition from lock.lock() or lock.unlock(). template cv_status wait_for(unique_lock<mutex>& lock, const chrono::duration& rel_time);
25
Requires: lock.owns_lock() is true and lock.mutex() is locked by the calling thread, and either — no other thread is waiting on this condition_variable object or — lock.mutex() returns the same value for each of the lock arguments supplied by all concurrently waiting (via wait, wait_for, or wait_until) threads.
26
Effects: as if return wait_until(lock, chrono::steady_clock::now() + rel_time);
27
Returns: cv_status::timeout if the relative timeout (30.2.4) specified by rel_time expired, otherwise cv_status::no_timeout.
28
Postcondition: lock.owns_lock() is true and lock.mutex() is locked by the calling thread.
29
Throws: system_error when an exception is required (30.2.2).
30
Error conditions: — equivalent error condition from lock.lock() or lock.unlock(). template bool wait_until(unique_lock<mutex>& lock, const chrono::time_point& abs_time, Predicate pred);
31
Requires: lock.owns_lock() is true and lock.mutex() is locked by the calling thread, and either § 30.5.1
1140
c ISO/IEC
N3376
— no other thread is waiting on this condition_variable object or — lock.mutex() returns the same value for each of the lock arguments supplied by all concurrently waiting (via wait or timed_wait) threads. 32
Effects: while (!pred()) if (wait_until(lock, abs_time) == cv_status::timeout) return pred(); return true;
33
Returns: pred()
34
Postcondition: lock.owns_lock() is true and lock.mutex() is locked by the calling thread.
35
[ Note: The returned value indicates whether the predicate evaluated to true regardless of whether the timeout was triggered. — end note ]
36
Throws: std::system_error when an exception is required (30.2.2).
37
Error conditions: — equivalent error condition from lock.lock() or lock.unlock(). template bool wait_for(unique_lock<mutex>& lock, const chrono::duration& rel_time, Predicate pred);
38
Requires: lock.owns_lock() is true and lock.mutex() is locked by the calling thread, and either — no other thread is waiting on this condition_variable object or — lock.mutex() returns the same value for each of the lock arguments supplied by all concurrently waiting (via wait, wait_for, or wait_until) threads.
39
Effects: as if return wait_until(lock, chrono::steady_clock::now() + rel_time, std::move(pred));
40
[ Note: There is no blocking if pred() is initially true, even if the timeout has already expired. — end note ]
41
Postcondition: lock.owns_lock() is true and lock.mutex() is locked by the calling thread.
42
Returns: pred()
43
[ Note: The returned value indicates whether the predicate evaluates to true regardless of whether the timeout was triggered. — end note ]
44
Throws: system_error when an exception is required (30.2.2).
45
Error conditions: — equivalent error condition from lock.lock() or lock.unlock().
§ 30.5.1
1141
c ISO/IEC
30.5.2 1
Class condition_variable_any
N3376
[thread.condition.condvarany]
A Lock type shall meet the BasicLockable requirements (30.2.5.2). [ Note: All of the standard mutex types meet this requirement. If a Lock type other than one of the standard mutex types or a unique_lock wrapper for a standard mutex type is used with condition_variable_any, the user must ensure that any necessary synchronization is in place with respect to the predicate associated with the condition_variable_any instance. — end note ] namespace std { class condition_variable_any { public: condition_variable_any(); ~condition_variable_any(); condition_variable_any(const condition_variable_any&) = delete; condition_variable_any& operator=(const condition_variable_any&) = delete; void notify_one() noexcept; void notify_all() noexcept; template void wait(Lock& lock); template void wait(Lock& lock, Predicate pred); template cv_status wait_until(Lock& lock, const chrono::time_point& abs_time); template bool wait_until(Lock& lock, const chrono::time_point& abs_time, Predicate pred); template cv_status wait_for(Lock& lock, const chrono::duration& rel_time); template bool wait_for(Lock& lock, const chrono::duration& rel_time, Predicate pred); }; } condition_variable_any();
2
Effects: Constructs an object of type condition_variable_any.
3
Throws: bad_alloc or system_error when an exception is required (30.2.2).
4
Error conditions: — resource_unavailable_try_again — if any native handle type manipulated is not available. — operation_not_permitted — if the thread does not have the privilege to perform the operation. ~condition_variable_any();
5
Requires: There shall be no thread blocked on *this. [ Note: That is, all threads shall have been notified; they may subsequently block on the lock specified in the wait. This relaxes the usual rules, which would have required all wait calls to happen before destruction. Only the notification to unblock the wait must happen before destruction. The user must take care to ensure that no threads wait on *this once the destructor has been started, especially when the waiting threads are calling the wait functions in a loop or using the overloads of wait, wait_for, or wait_until that take a predicate. — end note ] § 30.5.2
1142
c ISO/IEC
6
N3376
Effects: Destroys the object. void notify_one() noexcept;
7
Effects: If any threads are blocked waiting for *this, unblocks one of those threads. void notify_all() noexcept;
8
Effects: Unblocks all threads that are blocked waiting for *this. template void wait(Lock& lock);
9
10
Note: if any of the wait functions exits via an exception, it is unspecified whether the Lock is held. One can use a Lock type that allows to query that, such as the unique_lock wrapper. Effects: — Atomically calls lock.unlock() and blocks on *this. — When unblocked, calls lock.lock() (possibly blocking on the lock) and returns. — The function will unblock when signaled by a call to notify_one(), a call to notify_all(), or spuriously. — If the function exits via an exception, lock.lock() shall be called prior to exiting the function scope.
11
Postcondition: lock is locked by the calling thread.
12
Throws: system_error when an exception is required (30.2.2).
13
Error conditions: — equivalent error condition from lock.lock() or lock.unlock(). template void wait(Lock& lock, Predicate pred);
14
Effects: while (!pred()) wait(lock);
template cv_status wait_until(Lock& lock, const chrono::time_point& abs_time); 15
Effects: — Atomically calls lock.unlock() and blocks on *this. — When unblocked, calls lock.lock() (possibly blocking on the lock) and returns. — The function will unblock when signaled by a call to notify_one(), a call to notify_all(), expiration of the absolute timeout (30.2.4) specified by abs_time, or spuriously.
§ 30.5.2
1143
c ISO/IEC
N3376
— If the function exits via an exception, lock.lock() shall be called prior to exiting the function scope. 16
Postcondition: lock is locked by the calling thread.
17
Returns: cv_status::timeout if the absolute timeout (30.2.4) specified by abs_time expired, otherwise cv_status::no_timeout.
18
Throws: system_error when an exception is required (30.2.2).
19
Error conditions: — equivalent error condition from lock.lock() or lock.unlock(). template cv_status wait_for(Lock& lock, const chrono::duration& rel_time);
20
Effects: as if return wait_until(lock, chrono::steady_clock::now() + rel_time);
21
Returns: cv_status::timeout if the relative timeout (30.2.4) specified by rel_time expired, otherwise cv_status::no_timeout.
22
Postcondition: lock is locked by the calling thread.
23
Throws: system_error when an exception is required (30.2.2).
24
Error conditions: — equivalent error condition from lock.lock() or lock.unlock(). template bool wait_until(Lock& lock, const chrono::time_point& abs_time, Predicate pred);
25
Effects: while (!pred()) if (wait_until(lock, abs_time) == cv_status::timeout) return pred(); return true;
26
Returns: pred()
27
[ Note: The returned value indicates whether the predicate evaluates to true regardless of whether the timeout was triggered. — end note ] template bool wait_for(Lock& lock, const chrono::duration& rel_time, Predicate pred);
28
Effects: as if return wait_until(lock, chrono::steady_clock::now() + rel_time, std::move(pred));
§ 30.5.2
1144
c ISO/IEC
N3376
29
[ Note: There is no blocking if pred() is initially true, even if the timeout has already expired. — end note ]
30
Postcondition: lock is locked by the calling thread.
31
Returns: pred()
32
[ Note: The returned value indicates whether the predicate evaluates to true regardless of whether the timeout was triggered. — end note ]
33
Throws: system_error when an exception is required (30.2.2).
34
Error conditions: — equivalent error condition from lock.lock() or lock.unlock().
30.6 30.6.1 1
Futures Overview
[futures] [futures.overview]
30.6 describes components that a C++ program can use to retrieve in one thread the result (value or exception) from a function that has run in the same thread or another thread. [ Note: These components are not restricted to multi-threaded programs but can be useful in single-threaded programs as well. — end note ] Header synopsis namespace std { enum class future_errc { broken_promise, future_already_retrieved, promise_already_satisfied, no_state }; enum class launch : unspecified { async = unspecified , deferred = unspecified , implementation-defined }; enum class future_status { ready, timeout, deferred }; template struct is_error_code_enum : public true_type { }; error_code make_error_code(future_errc e) noexcept; error_condition make_error_condition(future_errc e) noexcept; const error_category& future_category() noexcept; class future_error; template class promise; template class promise; template class promise; template
§ 30.6.1
1145
c ISO/IEC
N3376
void swap(promise& x, promise& y) noexcept; template struct uses_allocator<promise, Alloc>; template class future; template class future; template class future; template class shared_future; template class shared_future; template class shared_future; template class packaged_task; template class packaged_task;
// undefined
template void swap(packaged_task&, packaged_task&) noexcept; template struct uses_allocator<packaged_task, Alloc>; template future async(F&& f, Args&&... args); template future async(launch policy, F&& f, Args&&... args); } 2
The enum type launch is a bitmask type (17.5.2.1.3) with launch::async and launch::deferred denoting individual bits. [ Note: Implementations can provide bitmasks to specify restrictions on task interaction by functions launched by async() applicable to a corresponding subset of available launch policies. Implementations can extend the behavior of the first overload of async() by adding their extensions to the launch policy under the “as if” rule. — end note ]
30.6.2
Error handling
[futures.errors]
const error_category& future_category() noexcept; 1
Returns: A reference to an object of a type derived from class error_category.
2
The object’s default_error_condition and equivalent virtual functions shall behave as specified for the class error_category. The object’s name virtual function shall return a pointer to the string "future". error_code make_error_code(future_errc e) noexcept;
3
Returns: error_code(static_cast(e), future_category()). error_condition make_error_condition(future_errc e) noexcept;
4
Returns: error_condition(static_cast(e), future_category()).
§ 30.6.2
1146
c ISO/IEC
30.6.3
Class future_error
N3376
[futures.future_error]
namespace std { class future_error : public logic_error { public: future_error(error_code ec); // exposition only const error_code& code() const noexcept; const char* what() const noexcept; }; } const error_code& code() const noexcept; 1
Returns: The value of ec that was passed to the object’s constructor. const char *what() const noexcept;
2
Returns: An ntbs incorporating code().message().
30.6.4 1
2
3
4
5
Shared state
[futures.state]
Many of the classes introduced in this sub-clause use some state to communicate results. This shared state consists of some state information and some (possibly not yet evaluated) result, which can be a (possibly void) value or an exception. [ Note: Futures, promises, and tasks defined in this clause reference such shared state. — end note ] [ Note: The result can be any kind of object including a function to compute that result, as used by async when policy is launch::deferred. — end note ] An asynchronous return object is an object that reads results from an shared state. A waiting function of an asynchronous return object is one that potentially blocks to wait for the shared state to be made ready. If a waiting function can return before the state is made ready because of a timeout (30.2.5), then it is a timed waiting function, otherwise it is a non-timed waiting function. An asynchronous provider is an object that provides a result to a shared state. The result of a shared state is set by respective functions on the asynchronous provider. [ Note: Such as promises or tasks. — end note ] The means of setting the result of a shared state is specified in the description of those classes and functions that create such a state object. When an asynchronous return object or an asynchronous provider is said to release its shared state, it means: — if the return object or provider holds the last reference to its shared state, the shared state is destroyed; and — the return object or provider gives up its reference to its shared state.
6
When an asynchronous provider is said to make its shared state ready, it means: — first, the provider marks its shared state as ready; and — second, the provider unblocks any execution agents waiting for its shared state to become ready.
7
When an asynchronous provider is said to abandon its shared state, it means: — first, if that state is not ready, the provider — stores an exception object of type future_error with an error condition of broken_promise within its shared state; and then § 30.6.4
1147
c ISO/IEC
N3376
— makes its shared state ready; — second, the provider releases its shared state. 8
9
10
11
A shared state is ready only if it holds a value or an exception ready for retrieval. Waiting for a shared state to become ready may invoke code to compute the result on the waiting thread if so specified in the description of the class or function that creates the state object. Calls to functions that successfully set the stored result of a shared state synchronize with (1.10) calls to functions successfully detecting the ready state resulting from that setting. The storage of the result (whether normal or exceptional) into the shared state synchronizes with (1.10) the successful return from a call to a waiting function on the shared state. Some functions (e.g., promise::set_value_at_thread_exit) delay making the shared state ready until the calling thread exits. The destruction of each of that thread’s objects with thread storage duration (3.7.2) is sequenced before making that shared state ready. Access to the result of the same shared state may conflict (1.10). [ Note: this explicitly specifies that the result of the shared state is visible in the objects that reference this state in the sense of data race avoidance (17.6.5.9). For example, concurrent accesses through references returned by shared_future::get() (30.6.7) must either use read-only operations or provide additional synchronization. — end note ]
30.6.5
Class template promise
[futures.promise]
namespace std { template class promise { public: promise(); template promise(allocator_arg_t, const Allocator& a); promise(promise&& rhs) noexcept; promise(const promise& rhs) = delete; ~promise(); // assignment promise& operator=(promise&& rhs) noexcept; promise& operator=(const promise& rhs) = delete; void swap(promise& other) noexcept; // retrieving the result future get_future(); // setting the result void set_value(see below ); void set_exception(exception_ptr p); // setting the result with deferred notification void set_value_at_thread_exit(const R& r); void set_value_at_thread_exit(see below ); void set_exception_at_thread_exit(exception_ptr p); }; template void swap(promise& x, promise& y) noexcept; template struct uses_allocator<promise, Alloc>; }
§ 30.6.5
1148
c ISO/IEC
1
2
N3376
The implementation shall provide the template promise and two specializations, promise and promise< void>. These differ only in the argument type of the member function set_value, as set out in its description, below. The set_value, set_exception, set_value_at_thread_exit, and set_exception_at_thread_exit member functions behave as though they acquire a single mutex associated with the promise object while updating the promise object. template struct uses_allocator<promise, Alloc> : true_type { };
3
Requires: Alloc shall be an Allocator (17.6.3.5). promise(); template promise(allocator_arg_t, const Allocator& a);
4
Effects: constructs a promise object and a shared state. The second constructor uses the allocator a to allocate memory for the shared state. promise(promise&& rhs) noexcept;
5
Effects: constructs a new promise object and transfers ownership of the shared state of rhs (if any) to the newly-constructed object.
6
Postcondition: rhs has no shared state. ~promise();
7
Effects: Abandons any shared state (30.6.4). promise& operator=(promise&& rhs) noexcept;
8
Effects: Abandons any shared state (30.6.4) and then as if promise(std::move(rhs)).swap(*this).
9
Returns: *this. void swap(promise& other) noexcept;
10
Effects: Exchanges the shared state of *this and other.
11
Postcondition: *this has the shared state (if any) that other had prior to the call to swap. other has the shared state (if any) that *this had prior to the call to swap. future get_future();
12
Returns: A future object with the same shared state as *this.
13
Throws: future_error if *this has no shared state or if get_future has already been called on a promise with the same shared state as *this.
14
Error conditions: — future_already_retrieved if get_future has already been called on a promise with the same shared state as *this. § 30.6.5
1149
c ISO/IEC
N3376
— no_state if *this has no shared state. void void void void
promise::set_value(const R& r); promise::set_value(R&& r); promise::set_value(R& r); promise::set_value();
15
Effects: atomically stores the value r in the shared state and makes that state ready (30.6.4).
16
Throws: — future_error if its shared state already has a stored value or exception, or — for the first version, any exception thrown by the copy constructor of R, or — for the second version, any exception thrown by the move constructor of R.
17
Error conditions: — promise_already_satisfied if its shared state already has a stored value or exception. — no_state if *this has no shared state. void set_exception(exception_ptr p);
18
Effects: atomically stores the exception pointer p in the shared state and makes that state ready (30.6.4).
19
Throws: future_error if its shared state already has a stored value or exception.
20
Error conditions: — promise_already_satisfied if its shared state already has a stored value or exception. — no_state if *this has no shared state. void void void void
promise::set_value_at_thread_exit(const R& r); promise::set_value_at_thread_exit(R&& r); promise::set_value_at_thread_exit(R& r); promise::set_value_at_thread_exit();
21
Effects: Stores the value r in the shared state without making that state ready immediately. Schedules that state to be made ready when the current thread exits, after all objects of thread storage duration associated with the current thread have been destroyed.
22
Throws: future_error if an error condition occurs.
23
Error conditions: — promise_already_satisfied if its shared state already has a stored value or exception. — no_state if *this has no shared state. void promise::set_exception_at_thread_exit(exception_ptr p);
24
Effects: Stores the exception pointer p in the shared state without making that state ready immediately. Schedules that state to be made ready when the current thread exits, after all objects of thread storage duration associated with the current thread have been destroyed.
25
Throws: future_error if an error condition occurs.
26
Error conditions: § 30.6.5
1150
c ISO/IEC
N3376
— promise_already_satisfied if its shared state already has a stored value or exception. — no_state if *this has no shared state. template void swap(promise& x, promise& y); 27
Effects: x.swap(y).
30.6.6 1
2
3
Class template future
[futures.unique_future]
The class template future defines a type for asynchronous return objects which do not share their shared state with other asynchronous return objects. A default-constructed future object has no shared state. A future object with shared state can be created by functions on asynchronous providers (30.6.4) or by the move constructor and shares its shared state with the original asynchronous provider. The result (value or exception) of a future object can be set by calling a respective function on an object that shares the same shared state. [ Note: Member functions of future do not synchronize with themselves or with member functions of shared_future. — end note ] The effect of calling any member function other than the destructor, the move-assignment operator, or valid on a future object for which valid() == false is undefined. [ Note: Implementations are encouraged to detect this case and throw an object of type future_error with an error condition of future_errc::no_state. — end note ] namespace std { template class future { public: future() noexcept; future(future &&) noexcept; future(const future& rhs) = delete; ~future(); future& operator=(const future& rhs) = delete; future& operator=(future&&) noexcept; shared_future share(); // retrieving the value see below get(); // functions to check state bool valid() const noexcept; void wait() const; template future_status wait_for(const chrono::duration& rel_time) const; template future_status wait_until(const chrono::time_point& abs_time) const; }; }
4
The implementation shall provide the template future and two specializations, future and future< void>. These differ only in the return type and return value of the member function get, as set out in its description, below. future() noexcept;
§ 30.6.6
1151
c ISO/IEC
5
Effects: constructs an empty future object that does not refer to an shared state.
6
Postcondition: valid() == false.
N3376
future(future&& rhs) noexcept; 7
Effects: move constructs a future object that refers to the shared state that was originally referred to by rhs (if any).
8
Postconditions: — valid() returns the same value as rhs.valid() prior to the constructor invocation. — rhs.valid() == false. ~future();
9
Effects: — releases any shared state (30.6.4); — destroys *this. future& operator=(future&& rhs) noexcept;
10
Effects: — releases any shared state (30.6.4). — move assigns the contents of rhs to *this.
11
Postconditions: — valid() returns the same value as rhs.valid() prior to the assignment. — rhs.valid() == false. shared_future share();
12
Returns: shared_future(std::move(*this)).
13
Postcondition: valid() == false. R future::get(); R& future::get(); void future::get();
14
Note: as described above, the template and its two required specializations differ only in the return type and return value of the member function get.
15
Effects: wait()s until the shared state is ready, then retrieves the value stored in the shared state.
16
Returns: — future::get() returns the value v stored in the object’s shared state as std::move(v). — future::get() returns the reference stored as value in the object’s shared state. — future::get() returns nothing. § 30.6.6
1152
c ISO/IEC
N3376
17
Throws: the stored exception, if an exception was stored in the shared state.
18
Postcondition: valid() == false. bool valid() const noexcept;
19
Returns: true only if *this refers to a shared state. void wait() const;
20
Effects: blocks until the shared state is ready. template future_status wait_for(const chrono::duration& rel_time) const;
21
Effects: none if the shared state contains a deferred function (30.6.8), otherwise blocks until the shared state is ready or until the relative timeout (30.2.4) specified by rel_time has expired.
22
Returns: — future_status::deferred if the shared state contains a deferred function. — future_status::ready if the shared state is ready. — future_status::timeout if the function is returning because the relative timeout (30.2.4) specified by rel_time has expired. template future_status wait_until(const chrono::time_point& abs_time) const;
23
Effects: none if the shared state contains a deferred function (30.6.8), otherwise blocks until the shared state is ready or until the absolute timeout (30.2.4) specified by abs_time has expired.
24
Returns: — future_status::deferred if the shared state contains a deferred function. — future_status::ready if the shared state is ready. — future_status::timeout if the function is returning because the absolute timeout (30.2.4) specified by abs_time has expired.
30.6.7 1
2
3
Class template shared_future
[futures.shared_future]
The class template shared_future defines a type for asynchronous return objects which may share their shared state with other asynchronous return objects. A default-constructed shared_future object has no shared state. A shared_future object with shared state can be created by conversion from a future object and shares its shared state with the original asynchronous provider (30.6.4) of the shared state. The result (value or exception) of a shared_future object can be set by calling a respective function on an object that shares the same shared state. [ Note: Member functions of shared_future do not synchronize with themselves, but they synchronize with the shared shared state. — end note ] The effect of calling any member function other than the destructor, the move-assignment operator, or valid() on a shared_future object for which valid() == false is undefined. [ Note: Implementations are encouraged to detect this case and throw an object of type future_error with an error condition of future_errc::no_state. — end note ] § 30.6.7
1153
c ISO/IEC
N3376
namespace std { template class shared_future { public: shared_future() noexcept; shared_future(const shared_future& rhs); shared_future(future&&) noexcept; shared_future(shared_future&& rhs) noexcept; ~shared_future(); shared_future& operator=(const shared_future& rhs); shared_future& operator=(shared_future&& rhs) noexcept; // retrieving the value see below get() const; // functions to check state bool valid() const noexcept; void wait() const; template future_status wait_for(const chrono::duration& rel_time) const; template future_status wait_until(const chrono::time_point& abs_time) const; }; } 4
The implementation shall provide the template shared_future and two specializations, shared_future and shared_future. These differ only in the return type and return value of the member function get, as set out in its description, below. shared_future() noexcept;
5
Effects: constructs an empty shared_future object that does not refer to an shared state.
6
Postcondition: valid() == false. shared_future(const shared_future& rhs);
7
Effects: constructs a shared_future object that refers to the same shared state as rhs (if any).
8
Postcondition: valid() returns the same value as rhs.valid(). shared_future(future&& rhs) noexcept; shared_future(shared_future&& rhs) noexcept;
9
10
Effects: move constructs a shared_future object that refers to the shared state that was originally referred to by rhs (if any). Postconditions: — valid() returns the same value as rhs.valid() returned prior to the constructor invocation. — rhs.valid() == false. ~shared_future();
11
Effects: § 30.6.7
1154
c ISO/IEC
N3376
— releases any shared state (30.6.4); — destroys *this. shared_future& operator=(shared_future&& rhs) noexcept; 12
Effects: — releases any shared state (30.6.4); — move assigns the contents of rhs to *this.
13
Postconditions: — valid() returns the same value as rhs.valid() returned prior to the assignment. — rhs.valid() == false. shared_future& operator=(const shared_future& rhs);
14
Effects: — releases any shared state (30.6.4); — assigns the contents of rhs to *this. [ Note: As a result, *this refers to the same shared state as rhs (if any). — end note ]
15
Postconditions: valid() == rhs.valid(). const R& shared_future::get() const; R& shared_future::get() const; void shared_future::get() const;
16
Note: as described above, the template and its two required specializations differ only in the return type and return value of the member function get.
17
Note: access to a value object stored in the shared state is unsynchronized, so programmers should apply only those operations on R that do not introduce a data race (1.10).
18
Effects: wait()s until the shared state is ready, then retrieves the value stored in the shared state.
19
Returns: — shared_future::get() returns a const reference to the value stored in the object’s shared state. [ Note: Access through that reference after the shared state has been destroyed produces undefined behavior; this can be avoided by not storing the reference in any storage with a greater lifetime than the shared_future object that returned the reference. — end note ] — shared_future::get() returns the reference stored as value in the object’s shared state. — shared_future::get() returns nothing.
20
Throws: the stored exception, if an exception was stored in the shared state. bool valid() const noexcept;
21
Returns: true only if *this refers to a shared state.
§ 30.6.7
1155
c ISO/IEC
N3376
void wait() const; 22
Effects: blocks until the shared state is ready. template future_status wait_for(const chrono::duration& rel_time) const;
23
Effects: none if the shared state contains a deferred function (30.6.8), otherwise blocks until the shared state is ready or until the relative timeout (30.2.4) specified by rel_time has expired.
24
Returns: — future_status::deferred if the shared state contains a deferred function. — future_status::ready if the shared state is ready. — future_status::timeout if the function is returning because the relative timeout (30.2.4) specified by rel_time has expired. template future_status wait_until(const chrono::time_point& abs_time) const;
25
Effects: none if the shared state contains a deferred function (30.6.8), otherwise blocks until the shared state is ready or until the absolute timeout (30.2.4) specified by abs_time has expired.
26
Returns: — future_status::deferred if the shared state contains a deferred function. — future_status::ready if the shared state is ready. — future_status::timeout if the function is returning because the absolute timeout (30.2.4) specified by abs_time has expired.
30.6.8 1
Function template async
[futures.async]
The function template async provides a mechanism to launch a function potentially in a new thread and provides the result of the function in a future object with which it shares a shared state. template future async(F&& f, Args&&... args); template future async(launch policy, F&& f, Args&&... args);
2
Requires: F and each Ti in Args shall satisfy the MoveConstructible requirements. INVOKE (DECAY_COPY (std::forward(f)), DECAY_COPY (std::forward(args))...) (20.8.2, 30.3.1.2) shall be a valid expression.
3
Effects: The first function behaves the same as a call to the second function with a policy argument of launch::async | launch::deferred and the same arguments for F and Args. The second function creates a shared state that is associated with the returned future object. The further behavior of the second function depends on the policy argument as follows (if more than one of these conditions applies, the implementation may choose any of the corresponding policies):
§ 30.6.8
1156
c ISO/IEC
N3376
— if policy & launch::async is non-zero — calls INVOKE (DECAY_COPY (std::forward(f)), DECAY_COPY (std::forward(args))...) (20.8.2, 30.3.1.2) as if in a new thread of execution represented by a thread object with the calls to DECAY_COPY () being evaluated in the thread that called async. Any return value is stored as the result in the shared state. Any exception propagated from the execution of INVOKE (DECAY_COPY (std::forward(f)), DECAY_COPY (std::forward(args))...) is stored as the exceptional result in the shared state. The thread object is stored in the shared state and affects the behavior of any asynchronous return objects that reference that state. — if policy & launch::deferred is non-zero — Stores DECAY_COPY (std::forward(f)) and DECAY_COPY (std::forward(args))... in the shared state. These copies of f and args constitute a deferred function. Invocation of the deferred function evaluates INVOKE (std::move(g), std::move(xyz)) where g is the stored value of DECAY_COPY (std::forward(f)) and xyz is the stored copy of DECAY_COPY (std::forward(args)).... The shared state is not made ready until the function has completed. The first call to a non-timed waiting function (30.6.4) on an asynchronous return object referring to this shared state shall invoke the deferred function in the thread that called the waiting function. Once evaluation of INVOKE (std::move(g), std::move(xyz)) begins, the function is no longer considered deferred. [ Note: If this policy is specified together with other policies, such as when using a policy value of launch::async | launch::deferred, implementations should defer invocation or the selection of the policy when no more concurrency can be effectively exploited. — end note ] 4
Returns: An object of type future that refers to the shared state created by this call to async.
5
Synchronization: Regardless of the provided policy argument, — the invocation of async synchronizes with (1.10) the invocation of f. [ Note: This statement applies even when the corresponding future object is moved to another thread. — end note ]; and — the completion of the function f is sequenced before (1.10) the shared state is made ready. [ Note: f might not be called at all, so its completion might never happen. — end note ] If the implementation chooses the launch::async policy, — a call to a waiting function on an asynchronous return object that shares the shared state created by this async call shall block until the associated thread has completed, as if joined (30.3.1.5); — the associated thread completion synchronizes with (1.10) the return from the first function that successfully detects the ready status of the shared state or with the return from the last function that releases the shared state, whichever happens first.
6
Throws: system_error if policy is launch::async and the implementation is unable to start a new thread.
7
Error conditions: — resource_unavailable_try_again — if policy is launch::async and the system is unable to start a new thread.
8
9
Remarks: The first signature shall not participate in overload resolution if decay::type is std:: launch. [ Example:
§ 30.6.8
1157
c ISO/IEC
N3376
int work1(int value); int work2(int value); int work(int value) { auto handle = std::async([=]{ return work2(value); }); int tmp = work1(value); return tmp + handle.get(); // #1 }
[ Note: Line #1 might not result in concurrency because the async call uses the default policy, which may use launch::deferred, in which case the lambda might not be invoked until the get() call; in that case, work1 and work2 are called on the same thread and there is no concurrency. — end note ] — end example ]
30.6.9 1
2
Class template packaged_task
[futures.task]
The class template packaged_task defines a type for wrapping a function or callable object so that the return value of the function or callable object is stored in a future when it is invoked. When the packaged_task object is invoked, its stored task is invoked and the result (whether normal or exceptional) stored in the shared state. Any futures that share the shared state will then be able to access the stored result. namespace std { template class packaged_task; // undefined template class packaged_task { public: // construction and destruction packaged_task() noexcept; template explicit packaged_task(F&& f); template explicit packaged_task(allocator_arg_t, const Allocator& a, F&& f); ~packaged_task(); // no copy packaged_task(const packaged_task&) = delete; packaged_task& operator=(const packaged_task&) = delete; // move support packaged_task(packaged_task&& rhs) noexcept; packaged_task& operator=(packaged_task&& rhs) noexcept; void swap(packaged_task& other) noexcept; bool valid() const noexcept; // result retrieval future get_future(); // execution void operator()(ArgTypes... ); void make_ready_at_thread_exit(ArgTypes...); void reset(); }; template
§ 30.6.9
1158
c ISO/IEC
N3376
void swap(packaged_task& x, packaged_task& y) noexcept; template struct uses_allocator<packaged_task, Alloc>; }
30.6.9.1
packaged_task member functions
[futures.task.members]
packaged_task() noexcept; 1
Effects: constructs a packaged_task object with no shared state and no stored task. template packaged_task(F&& f); template explicit packaged_task(allocator_arg_t, const Allocator& a, F&& f);
2
Requires: INVOKE (f, t1, t2, ..., tN, R), where t1, t2, ..., tN are values of the corresponding types in ArgTypes..., shall be a valid expression. Invoking a copy of f shall behave the same as invoking f.
3
Effects: constructs a new packaged_task object with a shared state and initializes the object’s stored task with std::forward(f). The constructors that take an Allocator argument use it to allocate memory needed to store the internal data structures.
4
Throws: any exceptions thrown by the copy or move constructor of f, or std::bad_alloc if memory for the internal data structures could not be allocated. packaged_task(packaged_task&& rhs) noexcept;
5
Effects: constructs a new packaged_task object and transfers ownership of rhs’s shared state to *this, leaving rhs with no shared state. Moves the stored task from rhs to *this.
6
Postcondition: rhs has no shared state. packaged_task& operator=(packaged_task&& rhs) noexcept;
7
Effects: — releases any shared state (30.6.4). — packaged_task(std::move(rhs)).swap(*this). ~packaged_task();
8
Effects: Abandons any shared state. (30.6.4). void swap(packaged_task& other) noexcept;
9 10
Effects: exchanges the shared states and stored tasks of *this and other. Postcondition: *this has the same shared state and stored task (if any) as other prior to the call to swap. other has the same shared state and stored task (if any) as *this prior to the call to swap. bool valid() const noexcept;
§ 30.6.9.1
1159
c ISO/IEC
11
N3376
Returns: true only if *this has a shared state. future get_future();
12
Returns: A future object that shares the same shared state as *this.
13
Throws: a future_error object if an error occurs.
14
Error conditions: — future_already_retrieved if get_future has already been called on a packaged_task object with the same shared state as *this. — no_state if *this has no shared state. void operator()(ArgTypes... args);
15
Effects: INVOKE (f, t1, t2, ..., tN, R), where f is the stored task of *this and t1, t2, ..., tN are the values in args.... If the task returns normally, the return value is stored as the asynchronous result in the shared state of *this, otherwise the exception thrown by the task is stored. The shared state of *this is made ready, and any threads blocked in a function waiting for the shared state of *this to become ready are unblocked.
16
Throws: a future_error exception object if there is no shared state or the stored task has already been invoked.
17
Error conditions: — promise_already_satisfied if the stored task has already been invoked. — no_state if *this has no shared state.
18
Synchronization: a successful call to operator() synchronizes with (1.10) a call to any member function of a future or shared_future object that shares the shared state of *this. The completion of the invocation of the stored task and the storage of the result (whether normal or exceptional) into the shared state synchronizes with (1.10) the successful return from any member function that detects that the state is set to ready. [ Note: operator() synchronizes and serializes with other functions through the shared state. — end note ] void make_ready_at_thread_exit(ArgTypes... args);
19
Effects: INVOKE (f, t1, t2, ..., tN, R), where f is the stored task and t1, t2, ..., tN are the values in args.... If the task returns normally, the return value is stored as the asynchronous result in the shared state of *this, otherwise the exception thrown by the task is stored. In either case, this shall be done without making that state ready (30.6.4) immediately. Schedules the shared state to be made ready when the current thread exits, after all objects of thread storage duration associated with the current thread have been destroyed.
20
Throws: future_error if an error condition occurs.
21
Error conditions: — promise_already_satisfied if the stored task has already been invoked. — no_state if *this has no shared state. void reset();
§ 30.6.9.1
1160
c ISO/IEC
N3376
22
Effects: as if *this = packaged_task(std::move(f)), where f is the task stored in *this. [ Note: This constructs a new shared state for *this. The old state is abandoned (30.6.4). — end note ]
23
Throws: — bad_alloc if memory for the new shared state could not be allocated. — any exception thrown by the move constructor of the task stored in the shared state. — future_error with an error condition of no_state if *this has no shared state. 30.6.9.2
packaged_task globals
[futures.task.nonmembers]
template void swap(packaged_task& x, packaged_task& y) noexcept; 1
Effects: x.swap(y) template struct uses_allocator<packaged_task, Alloc> : true_type { };
2
Requires: Alloc shall be an Allocator (17.6.3.5).
§ 30.6.9.2
1161
c ISO/IEC
Annex A (informative) Grammar summary 1
[gram]
This summary of C++ syntax is intended to be an aid to comprehension. It is not an exact statement of the language. In particular, the grammar described here accepts a superset of valid C++ constructs. Disambiguation rules (6.8, 7.1, 10.2) must be applied to distinguish expressions from declarations. Further, access control, ambiguity, and type rules must be used to weed out syntactically valid but meaningless constructs.
A.1 1
N3376
Keywords
[gram.key]
New context-dependent keywords are introduced into a program by typedef (7.1.3), namespace (7.3.1), class (clause 9), enumeration (7.2), and template (clause 14) declarations. typedef-name: identifier namespace-name: original-namespace-name namespace-alias original-namespace-name: identifier namespace-alias: identifier class-name: identifier simple-template-id enum-name: identifier template-name: identifier
Note that a typedef-name naming a class is also a class-name (9.1).
A.2
Lexical conventions
[gram.lex]
hex-quad: hexadecimal-digit hexadecimal-digit hexadecimal-digit hexadecimal-digit universal-character-name: \u hex-quad \U hex-quad hex-quad preprocessing-token: header-name identifier pp-number character-literal user-defined-character-literal string-literal user-defined-string-literal preprocessing-op-or-punc each non-white-space character that cannot be one of the above
§ A.2
1162
c ISO/IEC
N3376
token: identifier keyword literal operator punctuator header-name: < h-char-sequence > " q-char-sequence " h-char-sequence: h-char h-char-sequence h-char h-char: any member of the source character set except new-line and > q-char-sequence: q-char q-char-sequence q-char q-char: any member of the source character set except new-line and " pp-number: digit . digit pp-number digit pp-number identifier-nondigit pp-number e sign pp-number E sign pp-number . identifier: identifier-nondigit identifier identifier-nondigit identifier digit identifier-nondigit: nondigit universal-character-name other implementation-defined characters nondigit: one of 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 _ digit: one of 0 1 2 3 4 5 6 7 8 9 preprocessing-op-or-punc: one of { } [ ] # ## ( %: %:%: ; new delete ? :: . .* + * / % ˆ & ! = < > += -= *= ˆ= &= |= > >>=
~
1163
c ISO/IEC
N3376
literal: integer-literal character-literal floating-literal string-literal boolean-literal pointer-literal user-defined-literal integer-literal: decimal-literal integer-suffixopt octal-literal integer-suffixopt hexadecimal-literal integer-suffixopt decimal-literal: nonzero-digit decimal-literal digit octal-literal: 0 octal-literal octal-digit hexadecimal-literal: 0x hexadecimal-digit 0X hexadecimal-digit hexadecimal-literal hexadecimal-digit nonzero-digit: one of 1 2 3 4 5 6 7 8 9 octal-digit: one of 0 1 2 3 4 5 6 7 hexadecimal-digit: one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F integer-suffix: unsigned-suffix long-suffixopt unsigned-suffix long-long-suffixopt long-suffix unsigned-suffixopt long-long-suffix unsigned-suffixopt unsigned-suffix: one of u U long-suffix: one of l L long-long-suffix: one of ll LL character-literal: ’ c-char-sequence ’ u’ c-char-sequence ’ U’ c-char-sequence ’ L’ c-char-sequence ’ c-char-sequence: c-char c-char-sequence c-char c-char: any member of the source character set except the single-quote ’, backslash \, or new-line character escape-sequence universal-character-name
§ A.2
1164
c ISO/IEC
N3376
escape-sequence: simple-escape-sequence octal-escape-sequence hexadecimal-escape-sequence simple-escape-sequence: one of \’ \" \? \\ \a \b \f \n \r \t \v octal-escape-sequence: \ octal-digit \ octal-digit octal-digit \ octal-digit octal-digit octal-digit hexadecimal-escape-sequence: \x hexadecimal-digit hexadecimal-escape-sequence hexadecimal-digit floating-literal: fractional-constant exponent-partopt floating-suffixopt digit-sequence exponent-part floating-suffixopt fractional-constant: digit-sequenceopt . digit-sequence digit-sequence . exponent-part: e signopt digit-sequence E signopt digit-sequence sign: one of + digit-sequence: digit digit-sequence digit floating-suffix: one of f l F L string-literal: encoding-prefixopt " s-char-sequenceopt " encoding-prefixopt R raw-string encoding-prefix: u8 u U L s-char-sequence: s-char s-char-sequence s-char s-char: any member of the source character set except the double-quote ", backslash \, or new-line character escape-sequence universal-character-name raw-string: " d-char-sequenceopt ( r-char-sequenceopt ) d-char-sequenceopt " r-char-sequence: r-char r-char-sequence r-char
§ A.2
1165
c ISO/IEC
N3376
r-char: any member of the source character set, except a right parenthesis ) followed by the initial d-char-sequence (which may be empty) followed by a double quote ". d-char-sequence: d-char d-char-sequence d-char d-char: any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash \, and the control characters representing horizontal tab, vertical tab, form feed, and newline. boolean-literal: false true pointer-literal: nullptr user-defined-literal: user-defined-integer-literal user-defined-floating-literal user-defined-string-literal user-defined-character-literal user-defined-integer-literal: decimal-literal ud-suffix octal-literal ud-suffix hexadecimal-literal ud-suffix user-defined-floating-literal: fractional-constant exponent-partopt ud-suffix digit-sequence exponent-part ud-suffix user-defined-string-literal: string-literal ud-suffix user-defined-character-literal: character-literal ud-suffix ud-suffix: identifier
A.3
Basic concepts
[gram.basic]
translation-unit: declaration-seqopt
A.4
Expressions
[gram.expr]
primary-expression: literal this ( expression ) id-expression lambda-expression id-expression: unqualified-id qualified-id
§ A.4
1166
c ISO/IEC
N3376
unqualified-id: identifier operator-function-id conversion-function-id literal-operator-id ~ class-name ~ decltype-specifier template-id qualified-id: nested-name-specifier templateopt unqualified-id :: identifier :: operator-function-id :: literal-operator-id :: template-id nested-name-specifier: ::opt type-name :: ::opt namespace-name :: decltype-specifier :: nested-name-specifier identifier :: nested-name-specifier templateopt simple-template-id :: lambda-expression: lambda-introducer lambda-declaratoropt compound-statement lambda-introducer: [ lambda-captureopt ] lambda-capture: capture-default capture-list capture-default , capture-list capture-default: & = capture-list: capture ...opt capture-list , capture ...opt capture: identifier & identifier this lambda-declarator: ( parameter-declaration-clause ) mutableopt exception-specificationopt attribute-specifier-seqopt trailing-return-typeopt
§ A.4
1167
c ISO/IEC
N3376
postfix-expression: primary-expression postfix-expression [ expression ] postfix-expression [ braced-init-list ] postfix-expression ( expression-listopt ) simple-type-specifier ( expression-listopt ) typename-specifier ( expression-listopt ) simple-type-specifier braced-init-list typename-specifier braced-init-list postfix-expression . templateopt id-expression postfix-expression -> templateopt id-expression postfix-expression . pseudo-destructor-name postfix-expression -> pseudo-destructor-name postfix-expression ++ postfix-expression -dynamic_cast < type-id > ( expression ) static_cast < type-id > ( expression ) reinterpret_cast < type-id > ( expression ) const_cast < type-id > ( expression ) typeid ( expression ) typeid ( type-id ) expression-list: initializer-list pseudo-destructor-name: nested-name-specifieropt type-name :: ~ type-name nested-name-specifier template simple-template-id :: ~ type-name nested-name-specifieropt ~ type-name ~ decltype-specifier unary-expression: postfix-expression ++ cast-expression -- cast-expression unary-operator cast-expression sizeof unary-expression sizeof ( type-id ) sizeof ... ( identifier ) alignof ( type-id ) noexcept-expression new-expression delete-expression unary-operator: one of * & + - ! ~ new-expression: ::opt new new-placementopt new-type-id new-initializeropt ::opt new new-placementopt ( type-id ) new-initializeropt new-placement: ( expression-list ) new-type-id: type-specifier-seq new-declaratoropt new-declarator: ptr-operator new-declaratoropt noptr-new-declarator
§ A.4
1168
c ISO/IEC
N3376
noptr-new-declarator: [ expression ] attribute-specifier-seqopt noptr-new-declarator [ constant-expression ] attribute-specifier-seqopt new-initializer: ( expression-listopt ) braced-init-list delete-expression: ::opt delete cast-expression ::opt delete [ ] cast-expression noexcept-expression: noexcept ( expression ) cast-expression: unary-expression ( type-id ) cast-expression pm-expression: cast-expression pm-expression .* cast-expression pm-expression ->* cast-expression multiplicative-expression: pm-expression multiplicative-expression * pm-expression multiplicative-expression / pm-expression multiplicative-expression % pm-expression additive-expression: multiplicative-expression additive-expression + multiplicative-expression additive-expression - multiplicative-expression shift-expression: additive-expression shift-expression > additive-expression relational-expression: shift-expression relational-expression < shift-expression relational-expression > shift-expression relational-expression = shift-expression equality-expression: relational-expression equality-expression == relational-expression equality-expression != relational-expression and-expression: equality-expression and-expression & equality-expression exclusive-or-expression: and-expression exclusive-or-expression ˆ and-expression inclusive-or-expression: exclusive-or-expression inclusive-or-expression | exclusive-or-expression logical-and-expression: inclusive-or-expression logical-and-expression && inclusive-or-expression
§ A.4
1169
c ISO/IEC
N3376
logical-or-expression: logical-and-expression logical-or-expression || logical-and-expression conditional-expression: logical-or-expression logical-or-expression ? expression : assignment-expression assignment-expression: conditional-expression logical-or-expression assignment-operator initializer-clause throw-expression assignment-operator: one of = *= /= %= += -= >>= > ++
ˆ -= >>= --
& *=
literal-operator-id: operator "" identifier
A.12
Templates
[gram.temp]
template-declaration: template < template-parameter-list > declaration
§ A.12
1178
c ISO/IEC
N3376
template-parameter-list: template-parameter template-parameter-list , template-parameter template-parameter: type-parameter parameter-declaration type-parameter: class ...opt identifieropt class identifieropt = type-id typename ...opt identifieropt typename identifieropt = type-id template < template-parameter-list > class ...opt identifieropt template < template-parameter-list > class identifieropt = id-expression simple-template-id: template-name < template-argument-listopt > template-id: simple-template-id operator-function-id < template-argument-listopt > literal-operator-id < template-argument-listopt > template-name: identifier template-argument-list: template-argument ...opt template-argument-list , template-argument ...opt template-argument: constant-expression type-id id-expression typename-specifier: typename nested-name-specifier identifier typename nested-name-specifier templateopt simple-template-id explicit-instantiation: externopt template declaration explicit-specialization: template < > declaration
A.13
Exception handling
[gram.except]
try-block: try compound-statement handler-seq function-try-block: try ctor-initializeropt compound-statement handler-seq handler-seq: handler handler-seqopt handler: catch ( exception-declaration ) compound-statement exception-declaration: attribute-specifier-seqopt type-specifier-seq declarator attribute-specifier-seqopt type-specifier-seq abstract-declaratoropt ... throw-expression: throw assignment-expressionopt
§ A.13
1179
c ISO/IEC
N3376
exception-specification: dynamic-exception-specification noexcept-specification dynamic-exception-specification: throw ( type-id-listopt ) type-id-list: type-id ...opt type-id-list , type-id ...opt noexcept-specification: noexcept ( constant-expression ) noexcept
A.14
Preprocessing directives
[gram.cpp]
preprocessing-file: groupopt group: group-part group group-part group-part: if-section control-line text-line # non-directive if-section: if-group elif-groupsopt else-groupopt endif-line if-group: # if constant-expression new-line groupopt # ifdef identifier new-line groupopt # ifndef identifier new-line groupopt elif-groups: elif-group elif-groups elif-group elif-group: # elif constant-expression new-line groupopt else-group: # else new-line groupopt endif-line: # endif new-line control-line: # include pp-tokens new-line # define identifier replacement-list new-line # define identifier lparen identifier-listopt ) replacement-list new-line # define identifier lparen ... ) replacement-list new-line # define identifier lparen identifier-list, ... ) replacement-list new-line # undef identifier new-line # line pp-tokens new-line # error pp-tokensopt new-line # pragma pp-tokensopt new-line # new-line text-line: pp-tokensopt new-line non-directive: pp-tokens new-line
§ A.14
1180
c ISO/IEC
N3376
lparen: a ( character not immediately preceded by white-space identifier-list: identifier identifier-list , identifier replacement-list: pp-tokensopt pp-tokens: preprocessing-token pp-tokens preprocessing-token new-line: the new-line character
§ A.14
1181
c ISO/IEC
Annex B (informative) Implementation quantities 1
2
N3376
[implimits]
Because computers are finite, C++ implementations are inevitably limited in the size of the programs they can successfully process. Every implementation shall document those limitations where known. This documentation may cite fixed limits where they exist, say how to compute variable limits as a function of available resources, or say that fixed limits do not exist or are unknown. The limits may constrain quantities that include those described below or others. The bracketed number following each quantity is recommended as the minimum for that quantity. However, these quantities are only guidelines and do not determine compliance. — Nesting levels of compound statements, iteration control structures, and selection control structures [256]. — Nesting levels of conditional inclusion [256]. — Pointer, array, and function declarators (in any combination) modifying a class, arithmetic, or incomplete type in a declaration [256]. — Nesting levels of parenthesized expressions within a full-expression [256]. — Number of characters in an internal identifier or macro name [1 024]. — Number of characters in an external identifier [1 024]. — External identifiers in one translation unit [65 536]. — Identifiers with block scope declared in one block [1 024]. — Macro identifiers simultaneously defined in one translation unit [65 536]. — Parameters in one function definition [256]. — Arguments in one function call [256]. — Parameters in one macro definition [256]. — Arguments in one macro invocation [256]. — Characters in one logical source line [65 536]. — Characters in a string literal (after concatenation) [65 536]. — Size of an object [262 144]. — Nesting levels for #include files [256]. — Case labels for a switch statement (excluding those for any nested switch statements) [16 384]. — Data members in a single class [16 384]. — Enumeration constants in a single enumeration [4 096]. — Levels of nested class definitions in a single member-specification [256]. Implementation quantities
1182
c ISO/IEC
N3376
— Functions registered by atexit() [32]. — Functions registered by at_quick_exit() [32]. — Direct and indirect base classes [16 384]. — Direct base classes for a single class [1 024]. — Members declared in a single class [4 096]. — Final overriding virtual functions in a class, accessible or not [16 384]. — Direct and indirect virtual bases of a class [1 024]. — Static members of a class [1 024]. — Friend declarations in a class [4 096]. — Access control declarations in a class [4 096]. — Member initializers in a constructor definition [6 144]. — Scope qualifications of one identifier [256]. — Nested external specifications [1 024]. — Recursive constexpr function invocations [512]. — Template arguments in a template declaration [1 024]. — Recursively nested template instantiations, including substitution during template argument deduction (14.8.2) [1 024]. — Handlers per try block [256]. — Throw specifications on a single function declaration [256]. — Number of placeholders (20.8.9.1.4) [10].
Implementation quantities
1183
c ISO/IEC
N3376
Annex C (informative) Compatibility C.1 1
C++ and ISO C
[diff.iso]
This subclause lists the differences between
C.1.1
[diff]
C++
and ISO C, by the chapters of this document.
Clause 2: lexical conventions
[diff.lex]
2.12 Change: New Keywords New keywords are added to C++; see 2.12. Rationale: These keywords were added in order to implement the new semantics of C++. Effect on original feature: Change to semantics of well-defined feature. Any ISO C programs that used any of these keywords as identifiers are not valid C++ programs. Difficulty of converting: Syntactic transformation. Converting one specific program is easy. Converting a large collection of related programs takes more work. How widely used: Common. 2.14.3 Change: Type of character literal is changed from int to char Rationale: This is needed for improved overloaded function argument type matching. For example: int function( int i ); int function( char c ); function( ’x’ );
It is preferable that this call match the second version of function rather than the first. Effect on original feature: Change to semantics of well-defined feature. ISO C programs which depend on sizeof(’x’) == sizeof(int)
will not work the same as C++ programs. Difficulty of converting: Simple. How widely used: Programs which depend upon sizeof(’x’) are probably rare. Subclause 2.14.5: Change: String literals made const The type of a string literal is changed from “array of char” to “array of const char.” The type of a char16_t string literal is changed from “array of some-integer-type” to “array of const char16_t.” The type of a char32_t string literal is changed from “array of some-integer-type” to “array of const char32_t.” The type of a wide string literal is changed from “array of wchar_t” to “array of const wchar_t.” Rationale: This avoids calling an inappropriate overloaded function, which might expect to be able to modify its argument. Effect on original feature: Change to semantics of well-defined feature. Difficulty of converting: Syntactic transformation. The fix is to add a cast: char* p = "abc"; void f(char*) { char* p = (char*)"abc"; f(p);
§ C.1.1
// valid in C, invalid in C++ // OK: cast added
1184
c ISO/IEC
f((char*)"def");
N3376
// OK: cast added
}
How widely used: Programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are probably rare.
C.1.2
Clause 3: basic concepts
[diff.basic]
3.1 Change: C++ does not have “tentative definitions” as in C E.g., at file scope, int i; int i;
is valid in C, invalid in C++. This makes it impossible to define mutually referential file-local static objects, if initializers are restricted to the syntactic forms of C. For example, struct X { int i; struct X *next; }; static struct X a; static struct X b = { 0, &a }; static struct X a = { 1, &b };
Rationale: This avoids having different initialization rules for fundamental types and user-defined types. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Semantic transformation. Rationale: In C++, the initializer for one of a set of mutually-referential file-local static objects must invoke a function call to achieve the initialization. How widely used: Seldom. 3.3 Change: A struct is a scope in C++, not in C Rationale: Class scope is crucial to C++, and a struct is a class. Effect on original feature: Change to semantics of well-defined feature. Difficulty of converting: Semantic transformation. How widely used: C programs use struct extremely frequently, but the change is only noticeable when struct, enumeration, or enumerator names are referred to outside the struct. The latter is probably rare. 3.5 [also 7.1.6] Change: A name of file scope that is explicitly declared const, and not explicitly declared extern, has internal linkage, while in C it would have external linkage Rationale: Because const objects can be used as compile-time values in C++, this feature urges programmers to provide explicit initializer values for each const. This feature allows the user to put constobjects in header files that are included in many compilation units. Effect on original feature: Change to semantics of well-defined feature. Difficulty of converting: Semantic transformation How widely used: Seldom 3.6 Change: Main cannot be called recursively and cannot have its address taken Rationale: The main function may require special actions. Effect on original feature: Deletion of semantically well-defined feature Difficulty of converting: Trivial: create an intermediary function such as mymain(argc, argv). How widely used: Seldom 3.9 Change: C allows “compatible types” in several places, C++ does not For example, otherwise-identical § C.1.2
1185
c ISO/IEC
N3376
struct types with different tag names are “compatible” in C but are distinctly different types in C++. Rationale: Stricter type checking is essential for C++. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Semantic transformation. The “typesafe linkage” mechanism will find many, but not all, of such problems. Those problems not found by typesafe linkage will continue to function properly, according to the “layout compatibility rules” of this International Standard. How widely used: Common.
C.1.3
Clause 4: standard conversions
[diff.conv]
4.10 Change: Converting void* to a pointer-to-object type requires casting char a[10]; void *b=a; void foo() { char *c=b; }
ISO C will accept this usage of pointer to void being assigned to a pointer to object type. C++ will not. Rationale: C++ tries harder than C to enforce compile-time type safety. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Could be automated. Violations will be diagnosed by the C++ translator. The fix is to add a cast. For example: char *c = (char *) b;
How widely used: This is fairly widely used but it is good programming practice to add the cast when assigning pointer-to-void to pointer-to-object. Some ISO C translators will give a warning if the cast is not used.
C.1.4
Clause 5: expressions
[diff.expr]
5.2.2 Change: Implicit declaration of functions is not allowed Rationale: The type-safe nature of C++. Effect on original feature: Deletion of semantically well-defined feature. Note: the original feature was labeled as “obsolescent” in ISO C. Difficulty of converting: Syntactic transformation. Facilities for producing explicit function declarations are fairly widespread commercially. How widely used: Common. 5.3.3, 5.4 Change: Types must be declared in declarations, not in expressions In C, a sizeof expression or cast expression may create a new type. For example, p = (void*)(struct x {int i;} *)0;
declares a new type, struct x . Rationale: This prohibition helps to clarify the location of declarations in the source code. Effect on original feature: Deletion of a semantically well-defined feature. Difficulty of converting: Syntactic transformation. How widely used: Seldom. 5.16, 5.17, 5.18 Change: The result of a conditional expression, an assignment expression, or a comma expression may be an lvalue Rationale: C++ is an object-oriented language, placing relatively more emphasis on lvalues. For example, § C.1.4
1186
c ISO/IEC
N3376
functions may return lvalues. Effect on original feature: Change to semantics of well-defined feature. Some C expressions that implicitly rely on lvalue-to-rvalue conversions will yield different results. For example, char arr[100]; sizeof(0, arr)
yields 100 in C++ and sizeof(char*) in C. Difficulty of converting: Programs must add explicit casts to the appropriate rvalue. How widely used: Rare.
C.1.5
Clause 6: statements
[diff.stat]
6.4.2, 6.6.4 Change: It is now invalid to jump past a declaration with explicit or implicit initializer (except across entire block not entered) Rationale: Constructors used in initializers may allocate resources which need to be de-allocated upon leaving the block. Allowing jump past initializers would require complicated run-time determination of allocation. Furthermore, any use of the uninitialized object could be a disaster. With this simple compiletime rule, C++ assures that if an initialized variable is in scope, then it has assuredly been initialized. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Semantic transformation. How widely used: Seldom. 6.6.3 Change: It is now invalid to return (explicitly or implicitly) from a function which is declared to return a value without actually returning a value Rationale: The caller and callee may assume fairly elaborate return-value mechanisms for the return of class objects. If some flow paths execute a return without specifying any value, the implementation must embody many more complications. Besides, promising to return a value of a given type, and then not returning such a value, has always been recognized to be a questionable practice, tolerated only because very-old C had no distinction between void functions and int functions. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Semantic transformation. Add an appropriate return value to the source code, such as zero. How widely used: Seldom. For several years, many existing C implementations have produced warnings in this case.
C.1.6
Clause 7: declarations
[diff.dcl]
7.1.1 Change: In C++, the static or extern specifiers can only be applied to names of objects or functions Using these specifiers with type declarations is illegal in C++. In C, these specifiers are ignored when used on type declarations. Example: static struct S { int i; };
// valid C, invalid in C++
Rationale: Storage class specifiers don’t have any meaning when associated with a type. In C++, class members can be declared with the static storage class specifier. Allowing storage class specifiers on type declarations could render the code confusing for users. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Syntactic transformation. How widely used: Seldom. § C.1.6
1187
c ISO/IEC
N3376
7.1.3 Change: A C++ typedef name must be different from any class type name declared in the same scope (except if the typedef is a synonym of the class name with the same name). In C, a typedef name and a struct tag name declared in the same scope can have the same name (because they have different name spaces) Example: typedef struct name1 { /∗...∗/ } name1; // valid C and C++ struct name { /∗...∗/ }; typedef int name; // valid C, invalid C++
Rationale: For ease of use, C++ doesn’t require that a type name be prefixed with the keywords class, struct or union when used in object declarations or type casts. Example: class name { /∗...∗/ }; name i;
// i has type class name
Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Semantic transformation. One of the 2 types has to be renamed. How widely used: Seldom. 7.1.6 [see also 3.5] Change: const objects must be initialized in C++ but can be left uninitialized in C Rationale: A const object cannot be assigned to so it must be initialized to hold a useful value. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Semantic transformation. How widely used: Seldom. 7.1.6 Change: Banning implicit int In C++ a decl-specifier-seq must contain a type-specifier, unless it is followed by a declarator for a constructor, a destructor, or a conversion function. In the following example, the left-hand column presents valid C; the right-hand column presents equivalent C++: void f(const parm); const n = 3; main() /∗ ... ∗/
void f(const int parm); const int n = 3; int main() /∗ ... ∗/
Rationale: In C++, implicit int creates several opportunities for ambiguity between expressions involving function-like casts and declarations. Explicit declaration is increasingly considered to be proper style. Liaison with WG14 (C) indicated support for (at least) deprecating implicit int in the next revision of C. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Syntactic transformation. Could be automated. How widely used: Common. 7.1.6.4 Change: The keyword auto cannot be used as a storage class specifier. void f() { auto int x; }
// valid C, invalid C++
Rationale: Allowing the use of auto to deduce the type of a variable from its initializer results in undesired § C.1.6
1188
c ISO/IEC
N3376
interpretations of auto as a storage class specifier in certain contexts. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Syntactic transformation. How widely used: Rare. 7.2 Change: C++ objects of enumeration type can only be assigned values of the same enumeration type. In C, objects of enumeration type can be assigned values of any integral type Example: enum color { red, blue, green }; enum color c = 1; // valid C, invalid C++
Rationale: The type-safe nature of C++. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Syntactic transformation. (The type error produced by the assignment can be automatically corrected by applying an explicit cast.) How widely used: Common. 7.2 Change: In C++, the type of an enumerator is its enumeration. In C, the type of an enumerator is int. Example: enum e { A }; sizeof(A) == sizeof(int) // in C sizeof(A) == sizeof(e) // in C++ /∗ and sizeof(int) is not necessarily equal to sizeof(e) ∗/
Rationale: In C++, an enumeration is a distinct type. Effect on original feature: Change to semantics of well-defined feature. Difficulty of converting: Semantic transformation. How widely used: Seldom. The only time this affects existing C code is when the size of an enumerator is taken. Taking the size of an enumerator is not a common C coding practice.
C.1.7
Clause 8: declarators
[diff.decl]
8.3.5 Change: In C++, a function declared with an empty parameter list takes no arguments. In C, an empty parameter list means that the number and type of the function arguments are unknown. Example: int f();
// means int f(void) in C++ // int f( unknown ) in C
Rationale: This is to avoid erroneous function calls (i.e., function calls with the wrong number or type of arguments). Effect on original feature: Change to semantics of well-defined feature. This feature was marked as “obsolescent” in C. Difficulty of converting: Syntactic transformation. The function declarations using C incomplete declaration style must be completed to become full prototype declarations. A program may need to be updated further if different calls to the same (non-prototype) function have different numbers of arguments or if the type of corresponding arguments differed. How widely used: Common. 8.3.5 [see 5.3.3] Change: In C++, types may not be defined in return or parameter types. In C, these type definitions are allowed § C.1.7
1189
c ISO/IEC
N3376
Example: void f( struct S { int a; } arg ) {} enum E { A, B, C } f() {}
// valid C, invalid C++ // valid C, invalid C++
Rationale: When comparing types in different compilation units, C++ relies on name equivalence when C relies on structural equivalence. Regarding parameter types: since the type defined in an parameter list would be in the scope of the function, the only legal calls in C++ would be from within the function itself. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Semantic transformation. The type definitions must be moved to file scope, or in header files. How widely used: Seldom. This style of type definitions is seen as poor coding style. 8.4 Change: In C++, the syntax for function definition excludes the “old-style” C function. In C, “old-style” syntax is allowed, but deprecated as “obsolescent.” Rationale: Prototypes are essential to type safety. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Syntactic transformation. How widely used: Common in old programs, but already known to be obsolescent. 8.5.2 Change: In C++, when initializing an array of character with a string, the number of characters in the string (including the terminating ’\0’) must not exceed the number of elements in the array. In C, an array can be initialized with a string even if the array is not large enough to contain the string-terminating ’\0’ Example: char array[4] = "abcd";
// valid C, invalid C++
Rationale: When these non-terminated arrays are manipulated by standard string routines, there is potential for major catastrophe. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Semantic transformation. The arrays must be declared one element bigger to contain the string terminating ’\0’. How widely used: Seldom. This style of array initialization is seen as poor coding style.
C.1.8
Clause 9: classes
[diff.class]
9.1 [see also 7.1.3] Change: In C++, a class declaration introduces the class name into the scope where it is declared and hides any object, function or other declaration of that name in an enclosing scope. In C, an inner scope declaration of a struct tag name never hides the name of an object or function in an outer scope Example: int x[99]; void f() { struct x { int a; }; sizeof(x); /∗ size of the array in C ∗/ /∗ size of the struct in C++ ∗/ }
Rationale: This is one of the few incompatibilities between C and C++ that can be attributed to the new C++ name space definition where a name can be declared as a type and as a non-type in a single scope causing the non-type name to hide the type name and requiring that the keywords class, struct, union or enum be used to refer to the type name. This new name space definition provides important notational § C.1.8
1190
c ISO/IEC
N3376
conveniences to C++ programmers and helps making the use of the user-defined types as similar as possible to the use of fundamental types. The advantages of the new name space definition were judged to outweigh by far the incompatibility with C described above. Effect on original feature: Change to semantics of well-defined feature. Difficulty of converting: Semantic transformation. If the hidden name that needs to be accessed is at global scope, the :: C++ operator can be used. If the hidden name is at block scope, either the type or the struct tag has to be renamed. How widely used: Seldom. 9.7 Change: In C++, the name of a nested class is local to its enclosing class. In C the name of the nested class belongs to the same scope as the name of the outermost enclosing class. Example: struct X { struct Y { /∗ ... ∗/ } y; }; struct Y yy;
// valid C, invalid C++
Rationale: C++ classes have member functions which require that classes establish scopes. The C rule would leave classes as an incomplete scope mechanism which would prevent C++ programmers from maintaining locality within a class. A coherent set of scope rules for C++ based on the C rule would be very complicated and C++ programmers would be unable to predict reliably the meanings of nontrivial examples involving nested or local functions. Effect on original feature: Change of semantics of well-defined feature. Difficulty of converting: Semantic transformation. To make the struct type name visible in the scope of the enclosing struct, the struct tag could be declared in the scope of the enclosing struct, before the enclosing struct is defined. Example: struct Y; struct X { struct Y { /∗ ... ∗/ } y; };
// struct Y and struct X are at the same scope
All the definitions of C struct types enclosed in other struct definitions and accessed outside the scope of the enclosing struct could be exported to the scope of the enclosing struct. Note: this is a consequence of the difference in scope rules, which is documented in 3.3. How widely used: Seldom. 9.9 Change: In C++, a typedef name may not be redeclared in a class definition after being used in that definition Example: typedef int I; struct S { I i; int I; };
// valid C, invalid C++
Rationale: When classes become complicated, allowing such a redefinition after the type has been used can create confusion for C++ programmers as to what the meaning of ’I’ really is. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Semantic transformation. Either the type or the struct member has to be
§ C.1.8
1191
c ISO/IEC
N3376
renamed. How widely used: Seldom.
C.1.9
Clause 12: special member functions
[diff.special]
12.8 Change: Copying volatile objects The implicitly-declared copy constructor and implicitly-declared copy assignment operator cannot make a copy of a volatile lvalue. For example, the following is valid in ISO C: struct X volatile struct X struct X x3 = x1;
{ int i; }; struct X x1 = {0}; x2(x1); x3;
// invalid C++ // also invalid C++
Rationale: Several alternatives were debated at length. Changing the parameter to volatile const X& would greatly complicate the generation of efficient code for class objects. Discussion of providing two alternative signatures for these implicitly-defined operations raised unanswered concerns about creating ambiguities and complicating the rules that specify the formation of these operators according to the bases and members. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Semantic transformation. If volatile semantics are required for the copy, a user-declared constructor or assignment must be provided. [ Note: This user-declared constructor may be explicitly defaulted. — end note ] If non-volatile semantics are required, an explicit const_cast can be used. How widely used: Seldom.
C.1.10
Clause 16: preprocessing directives
[diff.cpp]
16.8 Change: Whether _ _ STDC _ _ is defined and if so, what its value is, are implementation-defined Rationale: C++ is not identical to ISO C. Mandating that _ _ STDC _ _ be defined would require that translators make an incorrect claim. Each implementation must choose the behavior that will be most useful to its marketplace. Effect on original feature: Change to semantics of well-defined feature. Difficulty of converting: Semantic transformation. How widely used: Programs and headers that reference _ _ STDC _ _ are quite common.
C.2 1
C++ and ISO C++ 2003
[diff.cpp03]
This subclause lists the differences between C++ and ISO C++ 2003 (ISO/IEC 14882:2003, Programming Languages — C++ ), by the chapters of this document.
C.2.1
Clause 2: lexical conventions
[diff.cpp03.lex]
2.5 Change: New kinds of string literals Rationale: Required for new features. Effect on original feature: Valid C++ 2003 code may fail to compile or produce different results in this International Standard. Specifically, macros named R, u8, u8R, u, uR, U, UR, or LR will not be expanded when adjacent to a string literal but will be interpreted as part of the string literal. For example, #define u8 "abc" const char *s = u8"def";
// Previously "abcdef", now "def"
2.5 Change: User-defined literal string support Rationale: Required for new features. § C.2.1
1192
c ISO/IEC
N3376
Effect on original feature: Valid C++ 2003 code may fail to compile or produce different results in this International Standard, as the following example illustrates. #define _x "there" "hello"_x // #1
Previously, #1 would have consisted of two separate preprocessing tokens and the macro _x would have been expanded. In this International Standard, #1 consists of a single preprocessing tokens, so the macro is not expanded. 2.12 Change: New keywords Rationale: Required for new features. Effect on original feature: Added to Table 4, the following identifiers are new keywords: alignas, alignof, char16_t, char32_t, constexpr, decltype, noexcept, nullptr, static_assert, and thread_local. Valid C++ 2003 code using these identifiers is invalid in this International Standard. 2.14.2 Change: Type of integer literals Rationale: C99 compatibility. Effect on original feature: Certain integer literals larger than can be represented by long could change from an unsigned integer type to signed long long.
C.2.2
Clause 5: expressions
[diff.cpp03.expr]
5.6 Change: Specify rounding for results of integer / and % Rationale: Increase portability, C99 compatibility. Effect on original feature: Valid C++ 2003 code that uses integer division rounds the result toward 0 or toward negative infinity, whereas this International Standard always rounds the result toward 0.
C.2.3
Clause 7: declarations
[diff.cpp03.dcl.dcl]
7.1 Change: Remove auto as a storage class specifier Rationale: New feature. Effect on original feature: Valid C++ 2003 code that uses the keyword auto as a storage class specifier may be invalid in this International Standard. In this International Standard, auto indicates that the type of a variable is to be deduced from its initializer expression.
C.2.4
Clause 8: declarators
[diff.cpp03.dcl.decl]
8.5.4 Change: Narrowing restrictions in aggregate initializers Rationale: Catches bugs. Effect on original feature: Valid C++ 2003 code may fail to compile in this International Standard. For example, the following code is valid in C++ 2003 but invalid in this International Standard because double to int is a narrowing conversion: int x[] = { 2.0 };
C.2.5
Clause 12: special member functions
[diff.cpp03.special]
12.1, 12.4, 12.8 Change: Implicitly-declared special member functions are defined as deleted when the implicit definition would have been ill-formed. Rationale: Improves template argument deduction failure. Effect on original feature: A valid C++ 2003 program that uses one of these special member functions in a context where the definition is not required (e.g., in an expression that is not potentially evaluated) becomes ill-formed. § C.2.5
1193
c ISO/IEC
N3376
12.4 (destructors) Change: User-declared destructors have an implicit exception specification. Rationale: Clarification of destructor requirements. Effect on original feature: Valid C++ 2003 code may execute differently in this International Standard. In particular, destructors that throw exceptions will call std::terminate() (without calling std::unexpected()) if their exception specification is noexcept or noexcept(true). For a throwing virtual destructor of a derived class, std::terminate() can be avoided only if the base class virtual destructor has an exception specification that is not noexcept and not noexcept(true).
C.2.6
Clause 14: templates
[diff.cpp03.temp]
14.1 Change: Remove export Rationale: No implementation consensus. Effect on original feature: A valid C++ 2003 declaration containing export is ill-formed in this International Standard. 14.3 Change: Remove whitespace requirement for nested closing template right angle brackets Rationale: Considered a persistent but minor annoyance. Template aliases representing nonclass types would exacerbate whitespace issues. Effect on original feature: Change to semantics of well-defined expression. A valid C++ 2003 expression containing a right angle bracket (“>”) followed immediately by another right angle bracket may now be treated as closing two templates. For example, the following code is valid in C++ 2003 because “»” is a right-shift operator, but invalid in this International Standard because “»” closes two templates. template struct X { }; template struct Y { }; X< Y< 1 >> 2 > > x;
14.6.4.2 Change: Allow dependent calls of functions with internal linkage Rationale: Overly constrained, simplify overload resolution rules. Effect on original feature: A valid C++ 2003 program could get a different result than this International Standard.
C.2.7
Clause 17: library introduction
[diff.cpp03.library]
17 – 30 Change: New reserved identifiers Rationale: Required by new features. Effect on original feature: Valid C++ 2003 code that uses any identifiers added to the C++ standard library by this International Standard may fail to compile or produce different results in This International Standard. A comprehensive list of identifiers used by the C++ standard library can be found in the Index of Library Names in this International Standard. 17.6.1.2 Change: New headers Rationale: New functionality. Effect on original feature: The following C++ headers are new: <array>, , , , , , , , <mutex>, , , , <scoped_allocator>, <system_error>, , , , , , and . In addition the following C compatibility headers are new: , , , , , , , and <cuchar>. Valid C++ 2003 code that #includes headers with these names may be invalid in this International Standard.
§ C.2.7
1194
c ISO/IEC
N3376
17.6.3.2 Effect on original feature: Function swap moved to a different header Rationale: Remove dependency on for swap. Effect on original feature: Valid C++ 2003 code that has been compiled expecting swap to be in may have to instead include . 17.6.4.2.2 Change: New reserved namespace Rationale: New functionality. Effect on original feature: The global namespace posix is now reserved for standardization. Valid C++ 2003 code that uses a top-level namespace posix may be invalid in this International Standard. 17.6.5.3 Change: Additional restrictions on macro names Rationale: Avoid hard to diagnose or non-portable constructs. Effect on original feature: Names of attribute identifiers may not be used as macro names. Valid C++ 2003 code that defines override, final, carries_dependency, or noreturn as macros is invalid in this International Standard.
C.2.8
Clause 18: language support library
[diff.cpp03.language.support]
18.6.1.1 Change: Linking new and delete operators Rationale: The two throwing single-object signatures of operator new and operator delete are now specified to form the base functionality for the other operators. This clarifies that replacing just these two signatures changes others, even if they are not explicitly changed. Effect on original feature: Valid C++ 2003 code that replaces global new or delete operators may execute differently in this International Standard. For example, the following program should write "custom deallocation" twice, once for the single-object delete and once for the array delete. #include #include #include void* operator new(std::size_t size) throw(std::bad_alloc) { return std::malloc(size); } void operator delete(void* ptr) throw() { std::puts("custom deallocation"); std::free(ptr); } int main() { int* i = new int; delete i; int* a = new int[3]; delete [] a; return 0; }
// single-object delete // array delete
18.6.1.1 Change: operator new may throw exceptions other than std::bad_alloc Rationale: Consistent application of noexcept. Effect on original feature: Valid C++ 2003 code that assumes that global operator new only throws
§ C.2.8
1195
c ISO/IEC
N3376
std::bad_alloc may execute differently in this International Standard.
C.2.9
Clause 19: diagnostics library
[diff.cpp03.diagnostics]
19.4 Change: Thread-local error numbers Rationale: Support for new thread facilities. Effect on original feature: Valid but implementation-specific C++ 2003 code that relies on errno being the same across threads may change behavior in this International Standard.
C.2.10
Clause 20: general utilities library
[diff.cpp03.utilities]
20.6.4 Change: Minimal support for garbage-collected regions Rationale: Required by new feature. Effect on original feature: Valid C++ 2003 code, compiled without traceable pointer support, that interacts with newer C++ code using regions declared reachable may have different runtime behavior. 20.8.3, 20.8.4, 20.8.5, 20.8.6, 20.8.7, 20.8.8 Change: Standard function object types no longer derived from std::unary_function or std::binary_function Rationale: Superseded by new feature. Effect on original feature: Valid C++ 2003 code that depends on function object types being derived from unary_function or binary_function will execute differently in this International Standard.
C.2.11
Clause 21: strings library
[diff.cpp03.strings]
21.3 Change: basic_string requirements no longer allow reference-counted strings Rationale: Invalidation is subtly different with reference-counted strings. This change regularizes behavior for this International Standard. Effect on original feature: Valid C++ 2003 code may execute differently in this International Standard. 21.4.1 Change: Loosen basic_string invalidation rules Rationale: Allow small-string optimization. Effect on original feature: Valid C++ 2003 code may execute differently in this International Standard. Some const member functions, such as data and c_str, no longer invalidate iterators.
C.2.12
Clause 23: containers library
[diff.cpp03.containers]
23.2 Change: Complexity of size() member functions now constant Rationale: Lack of specification of complexity of size() resulted in divergent implementations with inconsistent performance characteristics. Effect on original feature: Some container implementations that conform to C++ 2003 may not conform to the specified size() requirements in this International Standard. Adjusting containers such as std::list to the stricter requirements may require incompatible changes. 23.2 Change: Requirements change: relaxation Rationale: Clarification. Effect on original feature: Valid C++ 2003 code that attempts to meet the specified container requirements may now be over-specified. Code that attempted to be portable across containers may need to be adjusted as follows: — not all containers provide size(); use empty() instead of size() == 0; — not all containers are empty after construction (array); — not all containers have constant complexity for swap() (array).
§ C.2.12
1196
c ISO/IEC
N3376
23.2 Change: Requirements change: default constructible Rationale: Clarification of container requirements. Effect on original feature: Valid C++ 2003 code that attempts to explicitly instantiate a container using a user-defined type with no default constructor may fail to compile. 23.2.3, 23.2.4 Change: Signature changes: from void return types Rationale: Old signature threw away useful information that may be expensive to recalculate. Effect on original feature: The following member functions have changed: — erase(iter) for set, multiset, map, multimap — erase(begin, end) for set, multiset, map, multimap — insert(pos, num, val) for vector, deque, list, forward_list — insert(pos, beg, end) for vector, deque, list, forward_list Valid C++ 2003 code that relies on these functions returning void (e.g., code that creates a pointer to member function that points to one of these functions) will fail to compile with this International Standard. 23.2.3, 23.2.4 Change: Signature changes: from iterator to const_iterator parameters Rationale: Overspecification. Effects: The signatures of the following member functions changed from taking an iterator to taking a const_iterator: — insert(iter, val) for vector, deque, list, set, multiset, map, multimap — insert(pos, beg, end) for vector, deque, list, forward_list — erase(iter) for set, multiset, map, multimap — erase(begin, end) for set, multiset, map, multimap — all forms of list::splice — all forms of list::merge Valid C++ 2003 code that uses these functions may fail to compile with this International Standard. 23.2.3, 23.2.4 Change: Signature changes: resize Rationale: Performance, compatibility with move semantics. Effect on original feature: For vector, deque, and list the fill value passed to resize is now passed by reference instead of by value, and an additional overload of resize has been added. Valid C++ 2003 code that uses this function may fail to compile with this International Standard.
C.2.13
Clause 25: algorithms library
[diff.cpp03.algorithms]
25.1 Change: Result state of inputs after application of some algorithms Rationale: Required by new feature. Effect on original feature: A valid C++ 2003 program may detect that an object with a valid but unspecified state has a different valid but unspecified state with this International Standard. For example,
§ C.2.13
1197
c ISO/IEC
N3376
std::remove and std::remove_if may leave the tail of the input sequence with a different set of values than previously.
C.2.14
Clause 26: numerics library
[diff.cpp03.numerics]
26.4 Change: Specified representation of complex numbers Rationale: Compatibility with C99. Effect on original feature: Valid C++ 2003 code that uses implementation-specific knowledge about the binary representation of the required template specializations of std::complex may not be compatible with this International Standard.
C.2.15
Clause 27: Input/output library
[diff.cpp03.input.output]
27.7.2.1.3, 27.7.3.4, 27.5.5.4 Change: Specify use of explicit in existing boolean conversion operators Rationale: Clarify intentions, avoid workarounds. Effect on original feature: Valid C++ 2003 code that relies on implicit boolean conversions will fail to compile with this International Standard. Such conversions occur in the following conditions: — passing a value to a function that takes an argument of type bool; — using operator== to compare to false or true; — returning a value from a function with a return type of bool; — initializing members of type bool via aggregate initialization; — initializing a const bool& which would bind to a temporary. 27.5.3.1.1 Change: Change base class of std::ios_base::failure Rationale: More detailed error messages. Effect on original feature: std::ios_base::failure is no longer derived directly from std::exception, but is now derived from std::system_error, which in turn is derived from std::runtime_error. Valid C++ 2003 code that assumes that std::ios_base::failure is derived directly from std::exception may execute differently in this International Standard. 27.5.3 Change: Flag types in std::ios_base are now bitmasks with values defined as constexpr static members Rationale: Required for new features. Effect on original feature: Valid C++ 2003 code that relies on std::ios_base flag types being represented as std::bitset or as an integer type may fail to compile with this International Standard. For example: #include int main() { int flag = std::ios_base::hex; std::cout.setf(flag); // error: setf does not take argument of type int return 0; }
C.3 1
2
C standard library
[diff.library]
This subclause summarizes the contents of the C++ standard library included from the Standard C library. It also summarizes the explicit changes in definitions, declarations, or behavior from the Standard C library noted in other subclauses (17.6.1.2, 18.2, 21.7). The C++ standard library provides 57 standard macros from the C library, as shown in Table 149.
§ C.3
1198
c ISO/IEC
N3376
Table 149 — Standard macros assert BUFSIZ CLOCKS_PER_SEC EDOM EILSEQ EOF ERANGE errno EXIT_FAILURE EXIT_SUCCESS FILENAME_MAX FOPEN_MAX
3
4
HUGE_VAL LC_ALL LC_COLLATE LC_CTYPE LC_MONETARY LC_NUMERIC LC_TIME L_tmpnam MB_CUR_MAX NULL NULL NULL
NULL NULL NULL offsetof RAND_MAX SEEK_CUR SEEK_END SEEK_SET setjmp SIGABRT SIGFPE SIGILL
SIGINT SIGSEGV SIGTERM SIG_DFL SIG_ERR SIG_IGN stderr stdin stdout TMP_MAX va_arg va_copy
va_end va_start WCHAR_MAX WCHAR_MIN WEOF WEOF _IOFBF _IOLBF _IONBF
The header names (enclosed in < and >) indicate that the macro may be defined in more than one header. All such definitions are equivalent (3.2). The C++ standard library provides 57 standard values from the C library, as shown in Table 150. Table 150 — Standard values CHAR_BIT CHAR_MAX CHAR_MIN DBL_DIG DBL_EPSILON DBL_MANT_DIG DBL_MAX DBL_MAX_10_EXP DBL_MAX_EXP DBL_MIN DBL_MIN_10_EXP DBL_MIN_EXP
5
FLT_DIG FLT_EPSILON FLT_MANT_DIG FLT_MAX FLT_MAX_10_EXP FLT_MAX_EXP FLT_MIN FLT_MIN_10_EXP FLT_MIN_EXP FLT_RADIX FLT_ROUNDS INT_MAX
INT_MIN LDBL_DIG LDBL_EPSILON LDBL_MANT_DIG LDBL_MAX LDBL_MAX_10_EXP LDBL_MAX_EXP LDBL_MIN LDBL_MIN_10_EXP LDBL_MIN_EXP LONG_MAX LONG_MIN
MB_LEN_MAX SCHAR_MAX SCHAR_MIN SHRT_MAX SHRT_MIN UCHAR_MAX UINT_MAX ULONG_MAX USRT_MAX
The C++ standard library provides 20 standard types from the C library, as shown in Table 151. Table 151 — Standard types clock_t div_t FILE fpos_t jmp_buf
6 7
ldiv_t mbstate_t ptrdiff_t sig_atomic_t size_t
size_t size_t size_t size_t time_t
va_list wctrans_t wctype_t wint_t wint_t
The C++ standard library provides 2 standard structs from the C library, as shown in Table 152. The C++ standard library provides 209 standard functions from the C library, as shown in Table 153.
§ C.3
1199
c ISO/IEC
N3376
Table 152 — Standard structs lconv
tm
Table 153 — Standard functions abort abs acos asctime asin atan atan2 atexit atof atoi atol bsearch btowc calloc ceil clearerr clock cos cosh ctime difftime div exit exp fabs fclose feof ferror fflush fgetc fgetpos fgets fgetwc fgetws floor
§ C.3
fmod fopen fprintf fputc fputs fputwc fputws fread free freopen frexp fscanf fseek fsetpos ftell fwide fwprintf fwrite fwscanf getc getchar getenv gets getwc getwchar gmtime isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace
isupper iswalnum iswalpha iswcntrl iswctype iswdigit iswgraph iswlower iswprint iswpunct iswspace iswupper iswxdigit isxdigit labs ldexp ldiv localeconv localtime log log10 longjmp malloc mblen mbrlen mbrtowc mbsinit mbsrtowcs mbstowcs mbtowc memchr memcmp memcpy memmove memset
mktime modf perror pow printf putc putchar puts putwc putwchar qsort raise rand realloc remove rename rewind scanf setbuf setlocale setvbuf signal sin sinh sprintf sqrt srand sscanf strcat strchr strcmp strcoll strcpy strcspn strerror
strftime strlen strncat strncmp strncpy strpbrk strrchr strspn strstr strtod strtok strtol strtoul strxfrm swprintf swscanf system tan tanh time tmpfile tmpnam tolower toupper towctrans towlower towupper ungetc ungetwc vfprintf vfwprintf vprintf vsprintf vswprintf vwprintf
wcrtomb wcscat wcschr wcscmp wcscoll wcscpy wcscspn wcsftime wcslen wcsncat wcsncmp wcsncpy wcspbrk wcsrchr wcsrtombs wcsspn wcsstr wcstod wcstok wcstol wcstombs wcstoul wcsxfrm wctob wctomb wctrans wctype wmemchr wmemcmp wmemcpy wmemmove wmemset wprintf wscanf
1200
c ISO/IEC
C.3.1 1
Modifications to headers
N3376
[diff.mods.to.headers]
For compatibility with the Standard C library, the C++ standard library provides the 18 C headers (D.5), but their use is deprecated in C++.
C.3.2
Modifications to definitions
[diff.mods.to.definitions]
Types char16_t and char32_t
[diff.char16]
C.3.2.1 1
The types char16_t and char32_t are distinct types rather than typedefs to existing integral types. C.3.2.2 Type wchar_t [diff.wchar.t]
1
wchar_t is a keyword in this International Standard (2.12). It does not appear as a type name defined in any of , , or (21.7). C.3.2.3 Header [diff.header.iso646.h]
1
The tokens and, and_eq, bitand, bitor, compl, not_eq, not, or, or_eq, xor, and xor_eq are keywords in this International Standard (2.12). They do not appear as macro names defined in . C.3.2.4 Macro NULL [diff.null]
1
The macro NULL, defined in any of , , , , , , or , is an implementation-defined C++ null pointer constant in this International Standard (18.2).
C.3.3 1
Modifications to declarations
[diff.mods.to.declarations]
Header : The following functions have different declarations: — strchr — strpbrk — strrchr — strstr — memchr 21.7 describes the changes.
C.3.4 1
Modifications to behavior
[diff.mods.to.behavior]
Header : The following functions have different behavior: — atexit — exit — abort
2
18.5 describes the changes. Header : The following functions have different behavior: — longjmp 18.10 describes the changes. C.3.4.1
Macro offsetof(type, member-designator)
[diff.offsetof]
1
The macro offsetof, defined in , accepts a restricted set of type arguments in this International Standard. 18.2 describes the change. C.3.4.2 Memory allocation functions [diff.malloc]
1
The functions calloc, malloc, and realloc are restricted in this International Standard. 20.6.13 describes the changes.
§ C.3.4.2
1201
c ISO/IEC
N3376
Annex D (normative) Compatibility features 1
2
This Clause describes features of the C++ Standard that are specified for compatibility with existing implementations. These are deprecated features, where deprecated is defined as: Normative for the current edition of the Standard, but not guaranteed to be part of the Standard in future revisions.
D.1 1
[depr.register]
Implicit declaration of copy functions
[depr.impldec]
Dynamic exception specifications
[depr.except.spec]
The use of dynamic-exception-specifications is deprecated.
D.5 1
register keyword
The implicit definition of a copy constructor as defaulted is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor. The implicit definition of a copy assignment operator as defaulted is deprecated if the class has a user-declared copy constructor or a user-declared destructor (12.4, 12.8). In a future revision of this International Standard, these implicit definitions could become deleted (8.4).
D.4 1
[depr.incr.bool]
The use of the register keyword as a storage-class-specifier (7.1.1) is deprecated.
D.3 1
Increment operator with bool operand
The use of an operand of type bool with the ++ operator is deprecated (see 5.3.2 and 5.2.6).
D.2 1
[depr]
C standard library headers
[depr.c.headers]
For compatibility with the C standard library and the C Unicode TR, the C++ standard library provides the 25 C headers, as shown in Table 154. Table 154 — C headers <errno.h>
2
3
<signal.h> <stdalign.h> <stdarg.h> <stdbool.h> <stddef.h> <stdint.h>
<stdio.h> <stdlib.h> <string.h>
<wchar.h> <wctype.h>
Every C header, each of which has a name of the form name.h, behaves as if each name placed in the standard library namespace by the corresponding cname header is placed within the global namespace scope. It is unspecified whether these names are first declared or defined within namespace scope (3.3.6) of the namespace std and are then injected into the global namespace scope by explicit using-declarations (7.3.3). [ Example: The header assuredly provides its declarations and definitions within the namespace std. It may also provide these names within the global namespace. The header <stdlib.h> assuredly provides the same declarations and definitions within the global namespace, much as in the C Standard. It may also provide these names within the namespace std. — end example ]
D.6 1
<math.h> <setjmp.h>
Old iostreams members
[depr.ios.members]
The following member names are in addition to names specified in Clause 27: § D.6
1202
c ISO/IEC
N3376
namespace std { class ios_base { public: typedef T1 io_state; typedef T2 open_mode; typedef T3 seek_dir; typedef implementation-defined streamoff; typedef implementation-defined streampos; // remainder unchanged }; } 2
3
4
5 6 7
The type io_state is a synonym for an integer type (indicated here as T1 ) that permits certain member functions to overload others on parameters of type iostate and provide the same behavior. The type open_mode is a synonym for an integer type (indicated here as T2 ) that permits certain member functions to overload others on parameters of type openmode and provide the same behavior. The type seek_dir is a synonym for an integer type (indicated here as T3 ) that permits certain member functions to overload others on parameters of type seekdir and provide the same behavior. The type streamoff is an implementation-defined type that satisfies the requirements of off_type in 27.2.2. The type streampos is an implementation-defined type that satisfies the requirements of pos_type in 27.2.2. An implementation may provide the following additional member function, which has the effect of calling sbumpc() (27.6.3.2.3): namespace std { template class basic_streambuf { public: void stossc(); // remainder unchanged }; }
8
An implementation may provide the following member functions that overload signatures specified in Clause 27: namespace std { template class basic_ios { public: void clear(io_state state); void setstate(io_state state); void exceptions(io_state); // remainder unchanged }; class ios_base { public: // remainder unchanged }; template class basic_streambuf { public: pos_type pubseekoff(off_type off, ios_base::seek_dir way, ios_base::open_mode which = ios_base::in | ios_base::out); pos_type pubseekpos(pos_type sp, ios_base::open_mode which); // remainder unchanged
§ D.6
1203
c ISO/IEC
N3376
}; template class basic_filebuf : public basic_streambuf { public: basic_filebuf* open (const char* s, ios_base::open_mode mode); // remainder unchanged }; template class basic_ifstream : public basic_istream { public: void open(const char* s, ios_base::open_mode mode); // remainder unchanged }; template class basic_ofstream : public basic_ostream { public: void open(const char* s, ios_base::open_mode mode); // remainder unchanged }; } 9
The effects of these functions is to call the corresponding member function specified in Clause 27.
D.7 1
char* streams
[depr.str.strstreams]
The header <strstream> defines three types that associate stream buffers with character array objects and assist reading and writing such objects.
D.7.1
Class strstreambuf
[depr.strstreambuf]
namespace std { class strstreambuf : public basic_streambuf { public: explicit strstreambuf(streamsize alsize_arg = 0); strstreambuf(void* (*palloc_arg)(size_t), void (*pfree_arg)(void*)); strstreambuf(char* gnext_arg, streamsize n, char* pbeg_arg = 0); strstreambuf(const char* gnext_arg, streamsize n); strstreambuf(signed char* gnext_arg, streamsize n, signed char* pbeg_arg = 0); strstreambuf(const signed char* gnext_arg, streamsize n); strstreambuf(unsigned char* gnext_arg, streamsize n, unsigned char* pbeg_arg = 0); strstreambuf(const unsigned char* gnext_arg, streamsize n); virtual ~strstreambuf(); void freeze(bool freezefl = true); char* str(); int pcount(); protected: virtual int_type overflow (int_type c = EOF); virtual int_type pbackfail(int_type c = EOF);
§ D.7.1
1204
c ISO/IEC
N3376
virtual int_type underflow(); virtual pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out); virtual pos_type seekpos(pos_type sp, ios_base::openmode which = ios_base::in | ios_base::out); virtual streambuf* setbuf(char* s, streamsize n); private: typedef T1 strstate; static const strstate allocated; static const strstate constant; static const strstate dynamic; static const strstate frozen; strstate strmode; streamsize alsize; void* (*palloc)(size_t); void (*pfree)(void*); };
// // // // // // // // //
exposition exposition exposition exposition exposition exposition exposition exposition exposition
only only only only only only only only only
} 1
2
The class strstreambuf associates the input sequence, and possibly the output sequence, with an object of some character array type, whose elements store arbitrary values. The array object has several attributes. [ Note: For the sake of exposition, these are represented as elements of a bitmask type (indicated here as T1) called strstate. The elements are: — allocated, set when a dynamic array object has been allocated, and hence should be freed by the destructor for the strstreambuf object; — constant, set when the array object has const elements, so the output sequence cannot be written; — dynamic, set when the array object is allocated (or reallocated) as necessary to hold a character sequence that can change in length; — frozen, set when the program has requested that the array object not be altered, reallocated, or freed.
3
— end note ] [ Note: For the sake of exposition, the maintained data is presented here as: — strstate strmode, the attributes of the array object associated with the strstreambuf object; — int alsize, the suggested minimum size for a dynamic array object; — void* (*palloc(size_t), points to the function to call to allocate a dynamic array object; — void (*pfree)(void*), points to the function to call to free a dynamic array object.
4
— end note ] Each object of class strstreambuf has a seekable area, delimited by the pointers seeklow and seekhigh. If gnext is a null pointer, the seekable area is undefined. Otherwise, seeklow equals gbeg and seekhigh is either pend, if pend is not a null pointer, or gend. D.7.1.1
strstreambuf constructors
[depr.strstreambuf.cons]
explicit strstreambuf(streamsize alsize_arg = 0); 1
Effects: Constructs an object of class strstreambuf, initializing the base class with streambuf(). The postconditions of this function are indicated in Table 155. § D.7.1.1
1205
c ISO/IEC
N3376
Table 155 — strstreambuf(streamsize) effects Element strmode alsize palloc pfree
Value dynamic alsize_arg a null pointer a null pointer
strstreambuf(void* (*palloc_arg)(size_t), void (*pfree_arg)(void*)); 2
Effects: Constructs an object of class strstreambuf, initializing the base class with streambuf(). The postconditions of this function are indicated in Table 156. Table 156 — strstreambuf(void* (*)(size_t), void (*)(void*)) effects Element strmode alsize palloc pfree
Value dynamic an unspecified value palloc_arg pfree_arg
strstreambuf(char* gnext_arg, streamsize n, char *pbeg_arg = 0); strstreambuf(signed char* gnext_arg, streamsize n, signed char *pbeg_arg = 0); strstreambuf(unsigned char* gnext_arg, streamsize n, unsigned char *pbeg_arg = 0); 3
Effects: Constructs an object of class strstreambuf, initializing the base class with streambuf(). The postconditions of this function are indicated in Table 157. Table 157 — strstreambuf(charT*, streamsize, charT*) effects Element strmode alsize palloc pfree
4
Value 0 an unspecified value a null pointer a null pointer
gnext_arg shall point to the first element of an array object whose number of elements N is determined as follows: — If n > 0, N is n. — If n == 0, N is std::strlen(gnext_arg). — If n < 0, N is INT_MAX.336 336) The function signature strlen(const char*) is declared in . (18.3).
§ D.7.1.1
(21.7).
The macro INT_MAX is defined in
1206
c ISO/IEC
5
N3376
If pbeg_arg is a null pointer, the function executes: setg(gnext_arg, gnext_arg, gnext_arg + N);
6
Otherwise, the function executes: setg(gnext_arg, gnext_arg, pbeg_arg); setp(pbeg_arg, pbeg_arg + N); strstreambuf(const char* gnext_arg, streamsize n); strstreambuf(const signed char* gnext_arg, streamsize n); strstreambuf(const unsigned char* gnext_arg, streamsize n);
7
Effects: Behaves the same as strstreambuf((char*)gnext_arg,n), except that the constructor also sets constant in strmode. virtual ~strstreambuf();
8
Effects: Destroys an object of class strstreambuf. The function frees the dynamically allocated array object only if strmode & allocated != 0 and strmode & frozen == 0. (D.7.1.3 describes how a dynamically allocated array object is freed.) D.7.1.2
Member functions
[depr.strstreambuf.members]
void freeze(bool freezefl = true); 1
Effects: If strmode & dynamic is non-zero, alters the freeze status of the dynamic array object as follows: — If freezefl is true, the function sets frozen in strmode. — Otherwise, it clears frozen in strmode. char* str();
2
Effects: Calls freeze(), then returns the beginning pointer for the input sequence, gbeg.
3
Remarks: The return value can be a null pointer. int pcount() const;
4
Effects: If the next pointer for the output sequence, pnext, is a null pointer, returns zero. Otherwise, returns the current effective length of the array object as the next pointer minus the beginning pointer for the output sequence, pnext - pbeg. D.7.1.3
strstreambuf overridden virtual functions
[depr.strstreambuf.virtuals]
int_type overflow(int_type c = EOF); 1
Effects: Appends the character designated by c to the output sequence, if possible, in one of two ways:
2
— If c != EOF and if either the output sequence has a write position available or the function makes a write position available (as described below), assigns c to *pnext++. Returns (unsigned char)c.
3
— If c == EOF, there is no character to append. Returns a value other than EOF. § D.7.1.3
1207
c ISO/IEC
N3376
4
Returns EOF to indicate failure.
5
Remarks: The function can alter the number of write positions available as a result of any call.
6
To make a write position available, the function reallocates (or initially allocates) an array object with a sufficient number of elements n to hold the current array object (if any), plus at least one additional write position. How many additional write positions are made available is otherwise unspecified.337 If palloc is not a null pointer, the function calls (*palloc)(n) to allocate the new dynamic array object. Otherwise, it evaluates the expression new charT[n]. In either case, if the allocation fails, the function returns EOF. Otherwise, it sets allocated in strmode.
7
To free a previously existing dynamic array object whose first element address is p: If pfree is not a null pointer, the function calls (*pfree)(p). Otherwise, it evaluates the expression delete[]p.
8
If strmode & dynamic == 0, or if strmode & frozen != 0, the function cannot extend the array (reallocate it with greater length) to make a write position available. int_type pbackfail(int_type c = EOF);
9
Puts back the character designated by c to the input sequence, if possible, in one of three ways:
10
— If c != EOF, if the input sequence has a putback position available, and if (char)c == gnext[-1], assigns gnext - 1 to gnext. Returns c.
11
— If c != EOF, if the input sequence has a putback position available, and if strmode & constant is zero, assigns c to *--gnext. Returns c.
12
— If c == EOF and if the input sequence has a putback position available, assigns gnext - 1 to gnext. Returns a value other than EOF.
13
Returns EOF to indicate failure.
14
Remarks: If the function can succeed in more than one of these ways, it is unspecified which way is chosen. The function can alter the number of putback positions available as a result of any call. int_type underflow();
15
Effects: Reads a character from the input sequence, if possible, without moving the stream position past it, as follows: — If the input sequence has a read position available, the function signals success by returning (unsigned char)*gnext.
16
— Otherwise, if the current write next pointer pnext is not a null pointer and is greater than the current read end pointer gend, makes a read position available by assigning to gend a value greater than gnext and no greater than pnext. Returns (unsigned char*)gnext.
17
Returns EOF to indicate failure.
18
Remarks: The function can alter the number of read positions available as a result of any call. 337) An implementation should consider alsize in making this decision.
§ D.7.1.3
1208
c ISO/IEC
N3376
pos_type seekoff(off_type off, seekdir way, openmode which = in | out); 19
Effects: Alters the stream position within one of the controlled sequences, if possible, as indicated in Table 158. Table 158 — seekoff positioning Conditions (which & ios::in) != 0 (which & ios::out) != 0 (which & (ios::in | ios::out)) == (ios::in | ios::out)) and way == either ios::beg or ios::end Otherwise
20
Result positions the input sequence positions the output sequence positions both the input and the output sequences
the positioning operation fails.
For a sequence to be positioned, if its next pointer is a null pointer, the positioning operation fails. Otherwise, the function determines newoff as indicated in Table 159. Table 159 — newoff values Condition way == ios::beg way == ios::cur way == ios::end If (newoff + off) < (seeklow - xbeg), or (seekhigh - xbeg) < (newoff + off)
newoff Value 0 the next pointer minus the beginning pointer (xnext - xbeg). seekhigh minus the beginning pointer (seekhigh - xbeg). the positioning operation fails
21
Otherwise, the function assigns xbeg + newoff + off to the next pointer xnext.
22
Returns: pos_type(newoff), constructed from the resultant offset newoff (of type off_type), that stores the resultant stream position, if possible. If the positioning operation fails, or if the constructed object cannot represent the resultant stream position, the return value is pos_type(off_type(-1)). pos_type seekpos(pos_type sp, ios_base::openmode which = ios_base::in | ios_base::out);
23
Effects: Alters the stream position within one of the controlled sequences, if possible, to correspond to the stream position stored in sp (as described below). — If (which & ios::in) != 0, positions the input sequence. — If (which & ios::out) != 0, positions the output sequence.
§ D.7.1.3
1209
c ISO/IEC
N3376
— If the function positions neither sequence, the positioning operation fails. For a sequence to be positioned, if its next pointer is a null pointer, the positioning operation fails. Otherwise, the function determines newoff from sp.offset():
24
— If newoff is an invalid stream position, has a negative value, or has a value greater than (seekhigh - seeklow), the positioning operation fails — Otherwise, the function adds newoff to the beginning pointer xbeg and stores the result in the next pointer xnext. 25
Returns: pos_type(newoff), constructed from the resultant offset newoff (of type off_type), that stores the resultant stream position, if possible. If the positioning operation fails, or if the constructed object cannot represent the resultant stream position, the return value is pos_type(off_type(-1)). streambuf* setbuf(char* s, streamsize n);
26
Effects: Implementation defined, except that setbuf(0, 0) has no effect.
D.7.2
Class istrstream
[depr.istrstream]
namespace std { class istrstream : public basic_istream { public: explicit istrstream(const char* s); explicit istrstream(char* s); istrstream(const char* s, streamsize n); istrstream(char* s, streamsize n); virtual ~istrstream(); strstreambuf* rdbuf() const; char *str(); private: strstreambuf sb; // exposition only }; } 1
The class istrstream supports the reading of objects of class strstreambuf. It supplies a strstreambuf object to control the associated array object. For the sake of exposition, the maintained data is presented here as: — sb, the strstreambuf object. D.7.2.1
istrstream constructors
[depr.istrstream.cons]
explicit istrstream(const char* s); explicit istrstream(char* s); 1
Effects: Constructs an object of class istrstream, initializing the base class with istream(&sb) and initializing sb with strstreambuf(s,0)). s shall designate the first element of an ntbs. istrstream(const char* s, streamsize n);
2
Effects: Constructs an object of class istrstream, initializing the base class with istream(&sb) and initializing sb with strstreambuf(s,n)). s shall designate the first element of an array whose length is n elements, and n shall be greater than zero.
§ D.7.2.1
1210
c ISO/IEC
D.7.2.2
Member functions
N3376
[depr.istrstream.members]
strstreambuf* rdbuf() const; 1
Returns: const_cast<strstreambuf*>(&sb). char* str();
2
Returns: rdbuf()->str().
D.7.3
Class ostrstream
[depr.ostrstream]
namespace std { class ostrstream : public basic_ostream { public: ostrstream(); ostrstream(char* s, int n, ios_base::openmode mode = ios_base::out); virtual ~ostrstream(); strstreambuf* rdbuf() const; void freeze(bool freezefl = true); char* str(); int pcount() const; private: strstreambuf sb; // exposition only }; } 1
The class ostrstream supports the writing of objects of class strstreambuf. It supplies a strstreambuf object to control the associated array object. For the sake of exposition, the maintained data is presented here as: — sb, the strstreambuf object. D.7.3.1
ostrstream constructors
[depr.ostrstream.cons]
ostrstream(); 1
Effects: Constructs an object of class ostrstream, initializing the base class with ostream(&sb) and initializing sb with strstreambuf()). ostrstream(char* s, int n, ios_base::openmode mode = ios_base::out);
2
Effects: Constructs an object of class ostrstream, initializing the base class with ostream(&sb), and initializing sb with one of two constructors: — If (mode & app) == 0, then s shall designate the first element of an array of n elements. The constructor is strstreambuf(s, n, s). — If (mode & app) != 0, then s shall designate the first element of an array of n elements that contains an ntbs whose first element is designated by s. The constructor is strstreambuf(s, n, s + std::strlen(s)).338 338) The function signature strlen(const char*) is declared in (21.7).
§ D.7.3.1
1211
c ISO/IEC
D.7.3.2
N3376
Member functions
[depr.ostrstream.members]
strstreambuf* rdbuf() const; 1
Returns: (strstreambuf*)&sb . void freeze(bool freezefl = true);
2
Effects: Calls rdbuf()->freeze(freezefl). char* str();
3
Returns: rdbuf()->str(). int pcount() const;
4
Returns: rdbuf()->pcount().
D.7.4
Class strstream
[depr.strstream]
namespace std { class strstream : public basic_iostream { public: // Types typedef char char_type; typedef typename char_traits::int_type int_type; typedef typename char_traits::pos_type pos_type; typedef typename char_traits::off_type off_type; // constructors/destructor strstream(); strstream(char* s, int n, ios_base::openmode mode = ios_base::in|ios_base::out); virtual ~strstream(); // Members: strstreambuf* rdbuf() const; void freeze(bool freezefl = true); int pcount() const; char* str(); private: strstreambuf sb; };
// exposition only
} 1
The class strstream supports reading and writing from objects of classs strstreambuf. It supplies a strstreambuf object to control the associated array object. For the sake of exposition, the maintained data is presented here as — sb, the strstreambuf object.
§ D.7.4
1212
c ISO/IEC
D.7.4.1
strstream constructors
N3376
[depr.strstream.cons]
strstream(); 1
Effects: Constructs an object of class strstream, initializing the base class with iostream(&sb). strstream(char* s, int n, ios_base::openmode mode = ios_base::in|ios_base::out);
2
Effects: Constructs an object of class strstream, initializing the base class with iostream(&sb) and initializing sb with one of the two constructors: — If (mode & app) == 0, then s shall designate the first element of an array of n elements. The constructor is strstreambuf(s,n,s). — If (mode & app) != 0, then s shall designate the first element of an array of n elements that contains an ntbs whose first element is designated by s. The constructor is strstreambuf(s,n,s + std::strlen(s)). D.7.4.2
strstream destructor
[depr.strstream.dest]
virtual ~strstream() 1
Effects: Destroys an object of class strstream. strstreambuf* rdbuf() const;
2
Returns: &sb. D.7.4.3
strstream operations
[depr.strstream.oper]
void freeze(bool freezefl = true); 1
Effects: Calls rdbuf()->freeze(freezefl). char* str();
2
Returns: rdbuf()->str(). int pcount() const;
3
Returns: rdbuf()->pcount().
D.8 D.8.1 1
Function objects Base
[depr.function.objects] [depr.base]
The class templates unary_function and binary_function are deprecated. A program shall not declare specializations of these templates. namespace std { template struct unary_function { typedef Arg argument_type; typedef Result result_type; }; }
§ D.8.1
1213
c ISO/IEC
N3376
namespace std { template struct binary_function { typedef Arg1 first_argument_type; typedef Arg2 second_argument_type; typedef Result result_type; }; }
D.8.2
Function adaptors
[depr.adaptors]
1
The adaptors ptr_fun, mem_fun, mem_fun_ref, and their corresponding return types are deprecated. [ Note: The function template bind 20.8.9.1 provides a better solution. — end note ] D.8.2.1 Adaptors for pointers to functions [depr.function.pointer.adaptors]
1
To allow pointers to (unary and binary) functions to work with function adaptors the library provides: template class pointer_to_unary_function : public unary_function { public: explicit pointer_to_unary_function(Result (*f)(Arg)); Result operator()(Arg x) const; };
2
operator() returns f(x). template pointer_to_unary_function ptr_fun(Result (*f)(Arg));
3
Returns: pointer_to_unary_function(f). template class pointer_to_binary_function : public binary_function { public: explicit pointer_to_binary_function(Result (*f)(Arg1, Arg2)); Result operator()(Arg1 x, Arg2 y) const; };
4
operator() returns f(x,y). template pointer_to_binary_function ptr_fun(Result (*f)(Arg1, Arg2));
5
Returns: pointer_to_binary_function(f).
6
[ Example: int compare(const char*, const char*); replace_if(v.begin(), v.end(), not1(bind2nd(ptr_fun(compare), "abc")), "def");
replaces each abc with def in sequence v. — end example ]
§ D.8.2.1
1214
c ISO/IEC
D.8.2.2 1
Adaptors for pointers to members
N3376
[depr.member.pointer.adaptors]
The purpose of the following is to provide the same facilities for pointer to members as those provided for pointers to functions in D.8.2.1. template class mem_fun_t : public unary_function { public: explicit mem_fun_t(S (T::*p)()); S operator()(T* p) const; };
2
mem_fun_t calls the member function it is initialized with given a pointer argument. template class mem_fun1_t : public binary_function { public: explicit mem_fun1_t(S (T::*p)(A)); S operator()(T* p, A x) const; };
3
mem_fun1_t calls the member function it is initialized with given a pointer argument and an additional argument of the appropriate type. template mem_fun_t<S,T> mem_fun(S (T::*f)()); template mem_fun1_t<S,T,A> mem_fun(S (T::*f)(A));
4
mem_fun(&X::f) returns an object through which X::f can be called given a pointer to an X followed by the argument required for f (if any). template class mem_fun_ref_t : public unary_function { public: explicit mem_fun_ref_t(S (T::*p)()); S operator()(T& p) const; };
5
mem_fun_ref_t calls the member function it is initialized with given a reference argument. template class mem_fun1_ref_t : public binary_function { public: explicit mem_fun1_ref_t(S (T::*p)(A)); S operator()(T& p, A x) const; };
6
mem_fun1_ref_t calls the member function it is initialized with given a reference argument and an additional argument of the appropriate type.
§ D.8.2.2
1215
c ISO/IEC
N3376
template mem_fun_ref_t<S,T> mem_fun_ref(S (T::*f)()); template mem_fun1_ref_t<S,T,A> mem_fun_ref(S (T::*f)(A)); 7
mem_fun_ref(&X::f) returns an object through which X::f can be called given a reference to an X followed by the argument required for f (if any). template class const_mem_fun_t : public unary_function { public: explicit const_mem_fun_t(S (T::*p)() const); S operator()(const T* p) const; };
8
const_mem_fun_t calls the member function it is initialized with given a pointer argument. template class const_mem_fun1_t : public binary_function { public: explicit const_mem_fun1_t(S (T::*p)(A) const); S operator()(const T* p, A x) const; };
9
const_mem_fun1_t calls the member function it is initialized with given a pointer argument and an additional argument of the appropriate type. template const_mem_fun_t<S,T> mem_fun(S (T::*f)() const); template const_mem_fun1_t<S,T,A> mem_fun(S (T::*f)(A) const);
10
mem_fun(&X::f) returns an object through which X::f can be called given a pointer to an X followed by the argument required for f (if any). template class const_mem_fun_ref_t : public unary_function { public: explicit const_mem_fun_ref_t(S (T::*p)() const); S operator()(const T& p) const; };
11
const_mem_fun_ref_t calls the member function it is initialized with given a reference argument. template class const_mem_fun1_ref_t : public binary_function { public: explicit const_mem_fun1_ref_t(S (T::*p)(A) const); S operator()(const T& p, A x) const; };
§ D.8.2.2
1216
c ISO/IEC
12
N3376
const_mem_fun1_ref_t calls the member function it is initialized with given a reference argument and an additional argument of the appropriate type. template const_mem_fun_ref_t<S,T> mem_fun_ref(S (T::*f)() const); template const_mem_fun1_ref_t<S,T,A> mem_fun_ref(S (T::*f)(A) const);
13
mem_fun_ref(&X::f) returns an object through which X::f can be called given a reference to an X followed by the argument required for f (if any).
D.9
Binders
[depr.lib.binders]
The binders binder1st, bind1st, binder2nd, and bind2nd are deprecated. [ Note: The function template bind (20.8.9) provides a better solution. — end note ]
D.9.1
Class template binder1st
[depr.lib.binder.1st]
template class binder1st : public unary_function { protected: Fn op; typename Fn::first_argument_type value; public: binder1st(const Fn& x, const typename Fn::first_argument_type& y); typename Fn::result_type operator()(const typename Fn::second_argument_type& x) const; typename Fn::result_type operator()(typename Fn::second_argument_type& x) const; }; 1
The constructor initializes op with x and value with y.
2
operator() returns op(value,x).
D.9.2
bind1st
[depr.lib.bind.1st]
template binder1st bind1st(const Fn& fn, const T& x); 1
Returns: binder1st(fn, typename Fn::first_argument_type(x)).
D.9.3
Class template binder2nd
[depr.lib.binder.2nd]
template class binder2nd : public unary_function { protected: Fn op; typename Fn::second_argument_type value; public: binder2nd(const Fn& x, const typename Fn::second_argument_type& y);
§ D.9.3
1217
c ISO/IEC
N3376
typename Fn::result_type operator()(const typename Fn::first_argument_type& x) const; typename Fn::result_type operator()(typename Fn::first_argument_type& x) const; }; 1
The constructor initializes op with x and value with y.
2
operator() returns op(x,value).
D.9.4
[depr.lib.bind.2nd]
bind2nd
template binder2nd bind2nd(const Fn& op, const T& x); 1
Returns: binder2nd(op, typename Fn::second_argument_type(x)).
2
[ Example: find_if(v.begin(), v.end(), bind2nd(greater(), 5));
finds the first integer in vector v greater than 5; find_if(v.begin(), v.end(), bind1st(greater(), 5));
finds the first integer in v less than 5. — end example ]
D.10
[depr.auto.ptr]
auto_ptr
The class template auto_ptr is deprecated. [ Note: The class template unique_ptr (20.7.1) provides a better solution. — end note ]
D.10.1 1
2
Class template auto_ptr
[auto.ptr]
The class template auto_ptr stores a pointer to an object obtained via new and deletes that object when it itself is destroyed (such as when leaving block scope 6.7). The class template auto_ptr_ref is for exposition only. An implementation is permitted to provide equivalent functionality without providing a template with this name. The template holds a reference to an auto_ptr. It is used by the auto_ptr conversions to allow auto_ptr objects to be passed to and returned from functions. namespace std { template struct auto_ptr_ref;
// exposition only
template class auto_ptr { public: typedef X element_type; // D.10.1.1 construct/copy/destroy: explicit auto_ptr(X* p =0) throw(); auto_ptr(auto_ptr&) throw(); template auto_ptr(auto_ptr&) throw(); auto_ptr& operator=(auto_ptr&) throw(); template auto_ptr& operator=(auto_ptr&) throw(); auto_ptr& operator=(auto_ptr_ref<X> r) throw(); ~auto_ptr() throw(); // X& X* X*
§ D.10.1
D.10.1.2 members: operator*() const throw(); operator->() const throw(); get() const throw();
1218
c ISO/IEC
N3376
X* release() throw(); void reset(X* p =0) throw(); // D.10.1.3 conversions: auto_ptr(auto_ptr_ref<X>) throw(); template operator auto_ptr_ref() throw(); template operator auto_ptr() throw(); }; template class auto_ptr { public: typedef void element_type; }; } 3
The class template auto_ptr provides a semantics of strict ownership. An auto_ptr owns the object it holds a pointer to. Copying an auto_ptr copies the pointer and transfers ownership to the destination. If more than one auto_ptr owns the same object at the same time the behavior of the program is undefined. [ Note: The uses of auto_ptr include providing temporary exception-safety for dynamically allocated memory, passing ownership of dynamically allocated memory to a function, and returning dynamically allocated memory from a function. Instances of auto_ptr meet the requirements of MoveConstructible and MoveAssignable, but do not meet the requirements of CopyConstructible and CopyAssignable. — end note ] D.10.1.1 auto_ptr constructors [auto.ptr.cons] explicit auto_ptr(X* p =0) throw();
1
Postconditions: *this holds the pointer p. auto_ptr(auto_ptr& a) throw();
2
Effects: Calls a.release().
3
Postconditions: *this holds the pointer returned from a.release(). template auto_ptr(auto_ptr& a) throw();
4
Requires: Y* can be implicitly converted to X*.
5
Effects: Calls a.release().
6
Postconditions: *this holds the pointer returned from a.release(). auto_ptr& operator=(auto_ptr& a) throw();
7
Requires: The expression delete get() is well formed.
8
Effects: reset(a.release()).
9
Returns: *this. template auto_ptr& operator=(auto_ptr& a) throw();
10
Requires: Y* can be implicitly converted to X*. The expression delete get() is well formed.
11
Effects: reset(a.release()).
12
Returns: *this. § D.10.1.1
1219
c ISO/IEC
N3376
~auto_ptr() throw(); 13
Requires: The expression delete get() is well formed.
14
Effects: delete get(). D.10.1.2
auto_ptr members
[auto.ptr.members]
X& operator*() const throw(); 1
Requires: get() != 0
2
Returns: *get() X* operator->() const throw();
3
Returns: get() X* get() const throw();
4
Returns: The pointer *this holds. X* release() throw();
5
Returns: get()
6
Postcondition: *this holds the null pointer. void reset(X* p=0) throw();
7
Effects: If get() != p then delete get().
8
Postconditions: *this holds the pointer p. D.10.1.3
auto_ptr conversions
[auto.ptr.conv]
auto_ptr(auto_ptr_ref<X> r) throw(); 1
Effects: Calls p.release() for the auto_ptr p that r holds.
2
Postconditions: *this holds the pointer returned from release(). template operator auto_ptr_ref() throw();
3
Returns: An auto_ptr_ref that holds *this. template operator auto_ptr() throw();
4
Effects: Calls release().
5
Returns: An auto_ptr that holds the pointer returned from release(). auto_ptr& operator=(auto_ptr_ref<X> r) throw()
6
Effects: Calls reset(p.release()) for the auto_ptr p that r holds a reference to.
7
Returns: *this § D.10.1.3
1220
c ISO/IEC
D.11 D.11.1
Violating exception-specifications Type unexpected_handler
N3376
[exception.unexpected] [unexpected.handler]
typedef void (*unexpected_handler)(); 1
The type of a handler function to be called by unexpected() when a function attempts to throw an exception not listed in its dynamic-exception-specification.
2
Required behavior: An unexpected_handler shall not return. See also 15.5.2.
3
Default behavior: The implementation’s default unexpected_handler calls std::terminate().
D.11.2
set_unexpected
[set.unexpected]
unexpected_handler set_unexpected(unexpected_handler f) noexcept; 1
Effects: Establishes the function designated by f as the current unexpected_handler.
2
Remark: It is unspecified whether a null pointer value designates the default unexpected_handler.
3
Returns: The previous unexpected_handler.
D.11.3
get_unexpected
[get.unexpected]
unexpected_handler get_unexpected() noexcept; 1
Returns: The current unexpected_handler. [ Note: This may be a null pointer value. — end note ]
D.11.4
unexpected
[unexpected]
[[noreturn]] void unexpected(); 1
Remarks: Called by the implementation when a function exits via an exception not allowed by its exception-specification (15.5.2), in effect after evaluating the throw-expression (D.11.1). May also be called directly by the program.
2
Effects: Calls the current unexpected_handler function. [ Note: A default unexpected_handler is always considered a callable handler in this context. — end note ]
§ D.11.4
1221
c ISO/IEC
N3376
Annex E (normative) Universal character names for identifier characters [charname] E.1
Ranges of characters allowed
[charname.allowed]
00A8, 00AA, 00AD, 00AF, 00B2-00B5, 00B7-00BA, 00BC-00BE, 00C0-00D6, 00D8-00F6, 00F8-00FF 0100-167F, 1681-180D, 180F-1FFF 200B-200D, 202A-202E, 203F-2040, 2054, 2060-206F 2070-218F, 2460-24FF, 2776-2793, 2C00-2DFF, 2E80-2FFF 3004-3007, 3021-302F, 3031-303F 3040-D7FF F900-FD3D, FD40-FDCF, FDF0-FE44, FE47-FFFD 10000-1FFFD, 20000-2FFFD, 30000-3FFFD, 40000-4FFFD, 50000-5FFFD, 60000-6FFFD, 70000-7FFFD, 80000-8FFFD, 90000-9FFFD, A0000-AFFFD, B0000-BFFFD, C0000-CFFFD, D0000-DFFFD, E0000-EFFFD
E.2
Ranges of characters disallowed initially
[charname.disallowed]
0300-036F, 1DC0-1DFF, 20D0-20FF, FE20-FE2F
§ E.2
1222
c ISO/IEC
N3376
Annex F (informative) Cross references
[xref]
This annex lists each section label and the corresponding section number, in alphabetical order by label. All of the section labels are the same as in the 2003 standard, except: — labels that begin with lib. in the 2003 standard have had the lib. removed so that they do not all appear in the same part of this list. For example, in the 2003 standard, the non-modifying sequence algorithms were found in a section with the label [lib.alg.nonmodifying]. The label for that section is now [alg.nonmodifying]. — the label for Annex B has been changed from [limits] to [implimits]. The label [limits] refers to section 18.3.2. A accumulate 26.7.2 adjacent.difference 26.7.5 adjustfield.manip 27.5.6.2 alg.adjacent.find 25.2.8 alg.all_of 25.2.1 alg.any_of 25.2.2 alg.binary.search 25.4.3 alg.c.library 25.5 alg.copy 25.3.1 alg.count 25.2.9 alg.equal 25.2.11 alg.fill 25.3.6 alg.find 25.2.5 alg.find.end 25.2.6 alg.find.first.of 25.2.7 alg.foreach 25.2.4 alg.generate 25.3.7 alg.heap.operations 25.4.6 alg.is_permutation 25.2.12 alg.lex.comparison 25.4.8 alg.merge 25.4.4 alg.min.max 25.4.7 alg.modifying.operations 25.3 alg.move 25.3.2 alg.none_of 25.2.3 alg.nonmodifying 25.2 alg.nth.element 25.4.2 alg.partitions 25.3.13 alg.permutation.generators 25.4.9 alg.random.shuffle 25.3.12 alg.remove 25.3.8 alg.replace 25.3.5 Cross references
alg.reverse 25.3.10 alg.rotate 25.3.11 alg.search 25.2.13 alg.set.operations 25.4.5 alg.sort 25.4.1 alg.sorting 25.4 alg.swap 25.3.3 alg.transform 25.3.4 alg.unique 25.3.9 algorithm.stable 17.6.5.7 algorithms 25 algorithms.general 25.1 alloc.errors 18.6.2 allocator.adaptor 20.12 allocator.adaptor.cnstr 20.12.3 allocator.adaptor.members 20.12.4 allocator.adaptor.syn 20.12.1 allocator.adaptor.types 20.12.2 allocator.globals 20.6.9.2 allocator.members 20.6.9.1 allocator.requirements 17.6.3.5 allocator.tag 20.6.6 allocator.traits 20.6.8 allocator.traits.members 20.6.8.2 allocator.traits.types 20.6.8.1 allocator.uses 20.6.7 allocator.uses.construction 20.6.7.2 allocator.uses.trait 20.6.7.1 alt.headers 17.6.4.4 arithmetic.operations 20.8.4 array 23.3.2 array.cons 23.3.2.2 array.data 23.3.2.5 1223
c ISO/IEC
array.fill 23.3.2.6 array.overview 23.3.2.1 array.size 23.3.2.4 array.special 23.3.2.3 array.swap 23.3.2.7 array.tuple 23.3.2.9 array.zero 23.3.2.8 assertions 19.3 associative 23.4 associative.general 23.4.1 associative.map.syn 23.4.2 associative.reqmts 23.2.4 associative.reqmts.except 23.2.4.1 associative.set.syn 23.4.3 atomics 29 atomics.fences 29.8 atomics.flag 29.7 atomics.general 29.1 atomics.lockfree 29.4 atomics.order 29.3 atomics.syn 29.2 atomics.types.generic 29.5 atomics.types.operations 29.6 atomics.types.operations.arith 29.6.3 atomics.types.operations.general 29.6.1 atomics.types.operations.pointer 29.6.4 atomics.types.operations.req 29.6.5 atomics.types.operations.templ 29.6.2 auto.ptr D.10.1 auto.ptr.cons D.10.1.1 auto.ptr.conv D.10.1.3 auto.ptr.members D.10.1.2 B back.insert.iter.cons 24.5.2.2.1 back.insert.iter.op* 24.5.2.2.3 back.insert.iter.op++ 24.5.2.2.4 back.insert.iter.op= 24.5.2.2.2 back.insert.iter.ops 24.5.2.2 back.insert.iterator 24.5.2.1 back.inserter 24.5.2.2.5 bad.alloc 18.6.2.1 bad.cast 18.7.2 bad.exception 18.8.2 bad.typeid 18.7.3 basefield.manip 27.5.6.3 basic 3 basic.align 3.11 basic.compound 3.9.2 basic.def 3.1 basic.def.odr 3.2 Cross references
N3376
basic.fundamental 3.9.1 basic.funscope 3.3.5 basic.ios.cons 27.5.5.2 basic.ios.members 27.5.5.3 basic.life 3.8 basic.link 3.5 basic.lookup 3.4 basic.lookup.argdep 3.4.2 basic.lookup.classref 3.4.5 basic.lookup.elab 3.4.4 basic.lookup.qual 3.4.3 basic.lookup.udir 3.4.6 basic.lookup.unqual 3.4.1 basic.lval 3.10 basic.namespace 7.3 basic.scope 3.3 basic.scope.class 3.3.7 basic.scope.declarative 3.3.1 basic.scope.enum 3.3.8 basic.scope.hiding 3.3.10 basic.scope.local 3.3.3 basic.scope.namespace 3.3.6 basic.scope.pdecl 3.3.2 basic.scope.proto 3.3.4 basic.scope.temp 3.3.9 basic.start 3.6 basic.start.init 3.6.2 basic.start.main 3.6.1 basic.start.term 3.6.3 basic.stc 3.7 basic.stc.auto 3.7.3 basic.stc.dynamic 3.7.4 basic.stc.dynamic.allocation 3.7.4.1 basic.stc.dynamic.deallocation 3.7.4.2 basic.stc.dynamic.safety 3.7.4.3 basic.stc.inherit 3.7.5 basic.stc.static 3.7.1 basic.stc.thread 3.7.2 basic.string 21.4 basic.string.hash 21.6 basic.type.qualifier 3.9.3 basic.types 3.9 bidirectional.iterators 24.2.6 binary.search 25.4.3.4 bind 20.8.9 bitmask.types 17.5.2.1.3 bitset.cons 20.5.1 bitset.hash 20.5.3 bitset.members 20.5.2 bitset.operators 20.5.4 bitwise.operations 20.8.7 1224
c ISO/IEC
byte.strings
N3376
17.5.2.1.4.1
C c.files 27.9.2 c.limits 18.3.3 c.locales 22.6 c.malloc 20.6.13 c.math 26.8 c.strings 21.7 category.collate 22.4.4 category.ctype 22.4.1 category.messages 22.4.7 category.monetary 22.4.6 category.numeric 22.4.2 category.time 22.4.5 ccmplx 26.4.10 cfenv 26.3 cfenv.syn 26.3.1 char.traits 21.2 char.traits.require 21.2.1 char.traits.specializations 21.2.3 char.traits.specializations.char 21.2.3.1 char.traits.specializations.char16_t 21.2.3.2 char.traits.specializations.char32_t 21.2.3.3 char.traits.specializations.wchar.t 21.2.3.4 char.traits.typedefs 21.2.2 character.seq 17.5.2.1.4 charname E charname.allowed E.1 charname.disallowed E.2 class 9 class.abstract 10.4 class.access 11 class.access.base 11.2 class.access.nest 11.7 class.access.spec 11.1 class.access.virt 11.5 class.base.init 12.6.2 class.bit 9.6 class.cdtor 12.7 class.conv 12.3 class.conv.ctor 12.3.1 class.conv.fct 12.3.2 class.copy 12.8 class.ctor 12.1 class.derived 10 class.dtor 12.4 class.expl.init 12.6.1 class.free 12.5 class.friend 11.3 class.gslice 26.6.6 Cross references
class.gslice.overview 26.6.6.1 class.inhctor 12.9 class.init 12.6 class.local 9.8 class.mem 9.2 class.member.lookup 10.2 class.mfct 9.3 class.mfct.non-static 9.3.1 class.mi 10.1 class.name 9.1 class.nest 9.7 class.nested.type 9.9 class.paths 11.6 class.protected 11.4 class.qual 3.4.3.1 class.slice 26.6.4 class.slice.overview 26.6.4.1 class.static 9.4 class.static.data 9.4.2 class.static.mfct 9.4.1 class.temporary 12.2 class.this 9.3.2 class.union 9.5 class.virtual 10.3 classification 22.3.3.1 cmplx.over 26.4.9 comparisons 20.8.5 complex 26.4.2 complex.member.ops 26.4.5 complex.members 26.4.4 complex.numbers 26.4 complex.ops 26.4.6 complex.special 26.4.3 complex.syn 26.4.1 complex.transcendentals 26.4.8 complex.value.ops 26.4.7 compliance 17.6.1.3 conforming 17.6.5 conforming.overview 17.6.5.1 cons.slice 26.6.4.2 constexpr.functions 17.6.5.6 constraints 17.6.4 constraints.overview 17.6.4.1 container.adaptors 23.6 container.adaptors.general 23.6.1 container.requirements 23.2 container.requirements.dataraces 23.2.2 container.requirements.general 23.2.1 containers 23 containers.general 23.1 contents 17.6.1.1 1225
c ISO/IEC
conv 4 conv.array 4.2 conv.bool 4.12 conv.double 4.8 conv.fpint 4.9 conv.fpprom 4.6 conv.func 4.3 conv.integral 4.7 conv.lval 4.1 conv.mem 4.11 conv.prom 4.5 conv.ptr 4.10 conv.qual 4.4 conv.rank 4.13 conventions 17.5.2 conversions 22.3.3.2 conversions.buffer 22.3.3.2.3 conversions.character 22.3.3.2.1 conversions.string 22.3.3.2.2 cpp 16 cpp.concat 16.3.3 cpp.cond 16.1 cpp.error 16.5 cpp.include 16.2 cpp.line 16.4 cpp.null 16.7 cpp.pragma 16.6 cpp.pragma.op 16.9 cpp.predefined 16.8 cpp.replace 16.3 cpp.rescan 16.3.4 cpp.scope 16.3.5 cpp.stringize 16.3.2 cpp.subst 16.3.1 cstdint 18.4 cstdint.syn 18.4.1 D date.time 20.11.8 dcl.align 7.6.2 dcl.ambig.res 8.2 dcl.array 8.3.4 dcl.asm 7.4 dcl.attr 7.6 dcl.attr.depend 7.6.4 dcl.attr.grammar 7.6.1 dcl.attr.noreturn 7.6.3 dcl.constexpr 7.1.5 dcl.dcl 7 dcl.decl 8 dcl.enum 7.2 Cross references
N3376
dcl.fct 8.3.5 dcl.fct.def 8.4 dcl.fct.def.default 8.4.2 dcl.fct.def.delete 8.4.3 dcl.fct.def.general 8.4.1 dcl.fct.default 8.3.6 dcl.fct.spec 7.1.2 dcl.friend 7.1.4 dcl.init 8.5 dcl.init.aggr 8.5.1 dcl.init.list 8.5.4 dcl.init.ref 8.5.3 dcl.init.string 8.5.2 dcl.link 7.5 dcl.meaning 8.3 dcl.mptr 8.3.3 dcl.name 8.1 dcl.ptr 8.3.1 dcl.ref 8.3.2 dcl.spec 7.1 dcl.spec.auto 7.1.6.4 dcl.stc 7.1.1 dcl.type 7.1.6 dcl.type.cv 7.1.6.1 dcl.type.elab 7.1.6.3 dcl.type.simple 7.1.6.2 dcl.typedef 7.1.3 declval 20.2.4 default.allocator 20.6.9 definitions 17.3 defns.additional 17.4 defns.arbitrary.stream defns.argument defns.argument.macro defns.argument.templ defns.argument.throw defns.block defns.blocked defns.character defns.character.container defns.comparison defns.component defns.cond.supp defns.deadlock defns.default.behavior.func defns.default.behavior.impl defns.diagnostic defns.dynamic.type defns.dynamic.type.prvalue defns.handler defns.ill.formed 1226
c ISO/IEC
defns.impl.defined defns.impl.limits defns.iostream.templates defns.locale.specific defns.modifier defns.move.assign defns.move.constr defns.multibyte defns.ntcts defns.obj.state defns.observer defns.parameter defns.parameter.macro defns.parameter.templ defns.regex.collating.element defns.regex.finite.state.machine defns.regex.format.specifier defns.regex.matched defns.regex.primary.equivalence.class defns.regex.regular.expression defns.regex.subexpression defns.replacement defns.repositional.stream defns.required.behavior defns.reserved.function defns.signature defns.signature.member defns.signature.member.spec defns.signature.member.templ defns.signature.spec defns.signature.templ defns.stable defns.static.type defns.traits defns.unblock defns.undefined defns.unspecified defns.valid defns.well.formed denorm.style 18.3.2.6 depr D depr.adaptors D.8.2 depr.auto.ptr D.10 depr.base D.8.1 depr.c.headers D.5 depr.except.spec D.4 depr.function.objects D.8 depr.function.pointer.adaptors D.8.2.1 depr.impldec D.3 depr.incr.bool D.1 depr.ios.members D.6 Cross references
N3376
depr.istrstream D.7.2 depr.istrstream.cons D.7.2.1 depr.istrstream.members D.7.2.2 depr.lib.bind.1st D.9.2 depr.lib.bind.2nd D.9.4 depr.lib.binder.1st D.9.1 depr.lib.binder.2nd D.9.3 depr.lib.binders D.9 depr.member.pointer.adaptors D.8.2.2 depr.ostrstream D.7.3 depr.ostrstream.cons D.7.3.1 depr.ostrstream.members D.7.3.2 depr.register D.2 depr.str.strstreams D.7 depr.strstream D.7.4 depr.strstream.cons D.7.4.1 depr.strstream.dest D.7.4.2 depr.strstream.oper D.7.4.3 depr.strstreambuf D.7.1 depr.strstreambuf.cons D.7.1.1 depr.strstreambuf.members D.7.1.2 depr.strstreambuf.virtuals D.7.1.3 deque 23.3.3 deque.capacity 23.3.3.3 deque.cons 23.3.3.2 deque.modifiers 23.3.3.4 deque.overview 23.3.3.1 deque.special 23.3.3.5 derivation 17.6.5.11 derived.classes 17.6.4.5 description 17.5 diagnostics 19 diagnostics.general 19.1 diff C diff.basic C.1.2 diff.char16 C.3.2.1 diff.class C.1.8 diff.conv C.1.3 diff.cpp C.1.10 diff.cpp03 C.2 diff.cpp03.algorithms C.2.13 diff.cpp03.containers C.2.12 diff.cpp03.dcl.dcl C.2.3 diff.cpp03.dcl.decl C.2.4 diff.cpp03.diagnostics C.2.9 diff.cpp03.expr C.2.2 diff.cpp03.input.output C.2.15 diff.cpp03.language.support C.2.8 diff.cpp03.lex C.2.1 diff.cpp03.library C.2.7 diff.cpp03.numerics C.2.14 1227
c ISO/IEC
diff.cpp03.special C.2.5 diff.cpp03.strings C.2.11 diff.cpp03.temp C.2.6 diff.cpp03.utilities C.2.10 diff.dcl C.1.6 diff.decl C.1.7 diff.expr C.1.4 diff.header.iso646.h C.3.2.3 diff.iso C.1 diff.lex C.1.1 diff.library C.3 diff.malloc C.3.4.2 diff.mods.to.behavior C.3.4 diff.mods.to.declarations C.3.3 diff.mods.to.definitions C.3.2 diff.mods.to.headers C.3.1 diff.null C.3.2.4 diff.offsetof C.3.4.1 diff.special C.1.9 diff.stat C.1.5 diff.wchar.t C.3.2.2 domain.error 19.2.2 E enumerated.types 17.5.2.1.2 equal.range 25.4.3.3 errno 19.4 error.reporting 27.5.6.5 except 15 except.ctor 15.2 except.handle 15.3 except.nested 18.8.6 except.spec 15.4 except.special 15.5 except.terminate 15.5.1 except.throw 15.1 except.uncaught 15.5.3 except.unexpected 15.5.2 exception 18.8.1 exception.terminate 18.8.3 exception.unexpected D.11 expr 5 expr.add 5.7 expr.alignof 5.3.6 expr.ass 5.17 expr.bit.and 5.11 expr.call 5.2.2 expr.cast 5.4 expr.comma 5.18 expr.cond 5.16 expr.const 5.19 Cross references
N3376
expr.const.cast 5.2.11 expr.delete 5.3.5 expr.dynamic.cast 5.2.7 expr.eq 5.10 expr.log.and 5.14 expr.log.or 5.15 expr.mptr.oper 5.5 expr.mul 5.6 expr.new 5.3.4 expr.or 5.13 expr.post 5.2 expr.post.incr 5.2.6 expr.pre.incr 5.3.2 expr.prim 5.1 expr.prim.general 5.1.1 expr.prim.lambda 5.1.2 expr.pseudo 5.2.4 expr.ref 5.2.5 expr.reinterpret.cast 5.2.10 expr.rel 5.9 expr.shift 5.8 expr.sizeof 5.3.3 expr.static.cast 5.2.9 expr.sub 5.2.1 expr.type.conv 5.2.3 expr.typeid 5.2.8 expr.unary 5.3 expr.unary.noexcept 5.3.7 expr.unary.op 5.3.1 expr.xor 5.12 ext.manip 27.7.5 extern.names 17.6.4.3.3 extern.types 17.6.4.3.4 F facet.ctype.char.dtor 22.4.1.3.1 facet.ctype.char.members 22.4.1.3.2 facet.ctype.char.statics 22.4.1.3.3 facet.ctype.char.virtuals 22.4.1.3.4 facet.ctype.special 22.4.1.3 facet.num.get.members 22.4.2.1.1 facet.num.get.virtuals 22.4.2.1.2 facet.num.put.members 22.4.2.2.1 facet.num.put.virtuals 22.4.2.2.2 facet.numpunct 22.4.3 facet.numpunct.members 22.4.3.1.1 facet.numpunct.virtuals 22.4.3.1.2 facets.examples 22.4.8 file.streams 27.9 filebuf 27.9.1.1 filebuf.assign 27.9.1.3 1228
c ISO/IEC
filebuf.cons 27.9.1.2 filebuf.members 27.9.1.4 filebuf.virtuals 27.9.1.5 floatfield.manip 27.5.6.4 fmtflags.manip 27.5.6.1 fmtflags.state 27.5.3.2 forward 20.2.3 forward.iterators 24.2.5 forwardlist 23.3.4 forwardlist.access 23.3.4.4 forwardlist.cons 23.3.4.2 forwardlist.iter 23.3.4.3 forwardlist.modifiers 23.3.4.5 forwardlist.ops 23.3.4.6 forwardlist.overview 23.3.4.1 forwardlist.spec 23.3.4.7 fpos 27.5.4 fpos.members 27.5.4.1 fpos.operations 27.5.4.2 front.insert.iter.cons 24.5.2.4.1 front.insert.iter.op* 24.5.2.4.3 front.insert.iter.op++ 24.5.2.4.4 front.insert.iter.op= 24.5.2.4.2 front.insert.iter.ops 24.5.2.4 front.insert.iterator 24.5.2.3 front.inserter 24.5.2.4.5 fstream 27.9.1.14 fstream.assign 27.9.1.16 fstream.cons 27.9.1.15 fstream.members 27.9.1.17 fstreams 27.9.1 func.bind 20.8.9.1 func.bind.bind 20.8.9.1.3 func.bind.isbind 20.8.9.1.1 func.bind.place 20.8.9.1.4 func.def 20.8.1 func.memfn 20.8.10 func.require 20.8.2 func.wrap 20.8.11 func.wrap.badcall 20.8.11.1 func.wrap.badcall.const 20.8.11.1.1 func.wrap.func 20.8.11.2 func.wrap.func.alg 20.8.11.2.7 func.wrap.func.cap 20.8.11.2.3 func.wrap.func.con 20.8.11.2.1 func.wrap.func.inv 20.8.11.2.4 func.wrap.func.mod 20.8.11.2.2 func.wrap.func.nullptr 20.8.11.2.6 func.wrap.func.targ 20.8.11.2.5 function.objects 20.8 functions.within.classes 17.5.2.2 Cross references
N3376
futures 30.6 futures.async 30.6.8 futures.errors 30.6.2 futures.future_error 30.6.3 futures.overview 30.6.1 futures.promise 30.6.5 futures.shared_future 30.6.7 futures.state 30.6.4 futures.task 30.6.9 futures.task.members 30.6.9.1 futures.task.nonmembers 30.6.9.2 futures.unique_future 30.6.6 G get.new.handler 18.6.2.5 get.terminate 18.8.3.3 get.unexpected D.11.3 global.functions 17.6.5.4 global.names 17.6.4.3.2 gram A gram.basic A.3 gram.class A.8 gram.cpp A.14 gram.dcl A.6 gram.decl A.7 gram.derived A.9 gram.except A.13 gram.expr A.4 gram.key A.1 gram.lex A.2 gram.over A.11 gram.special A.10 gram.stmt A.5 gram.temp A.12 gslice.access 26.6.6.3 gslice.array.assign 26.6.7.2 gslice.array.comp.assign 26.6.7.3 gslice.array.fill 26.6.7.4 gslice.cons 26.6.6.2 H handler.functions 17.6.4.7 hash.requirements 17.6.3.4 headers 17.6.1.2 I ifstream 27.9.1.6 ifstream.assign 27.9.1.8 ifstream.cons 27.9.1.7 ifstream.members 27.9.1.9 implimits B 1229
c ISO/IEC
includes 25.4.5.1 indirect.array.assign 26.6.9.2 indirect.array.comp.assign 26.6.9.3 indirect.array.fill 26.6.9.4 inner.product 26.7.3 input.iterators 24.2.3 input.output 27 input.output.general 27.1 input.streams 27.7.2 insert.iter.cons 24.5.2.6.1 insert.iter.op* 24.5.2.6.3 insert.iter.op++ 24.5.2.6.4 insert.iter.op= 24.5.2.6.2 insert.iter.ops 24.5.2.6 insert.iterator 24.5.2.5 insert.iterators 24.5.2 inserter 24.5.2.6.5 intro 1 intro.ack 1.11 intro.compliance 1.4 intro.defs 1.3 intro.execution 1.9 intro.memory 1.7 intro.multithread 1.10 intro.object 1.8 intro.refs 1.2 intro.scope 1.1 intro.structure 1.5 invalid.argument 19.2.3 ios 27.5.5 ios.base 27.5.3 ios.base.callback 27.5.3.6 ios.base.cons 27.5.3.7 ios.base.locales 27.5.3.3 ios.base.storage 27.5.3.5 ios.members.static 27.5.3.4 ios.overview 27.5.5.1 ios.types 27.5.3.1 ios::failure 27.5.3.1.1 ios::fmtflags 27.5.3.1.2 ios::Init 27.5.3.1.6 ios::iostate 27.5.3.1.3 ios::openmode 27.5.3.1.4 ios::seekdir 27.5.3.1.5 iostate.flags 27.5.5.4 iostream.assign 27.7.2.5.3 iostream.cons 27.7.2.5.1 iostream.dest 27.7.2.5.2 iostream.format 27.7 iostream.format.overview 27.7.1 iostream.forward 27.3 Cross references
N3376
iostream.limits.imbue 27.2.1 iostream.objects 27.4 iostream.objects.overview 27.4.1 iostreamclass 27.7.2.5 iostreams.base 27.5 iostreams.base.overview 27.5.1 iostreams.limits.pos 27.2.2 iostreams.requirements 27.2 iostreams.threadsafety 27.2.3 is.heap 25.4.6.5 is.sorted 25.4.1.5 istream 27.7.2.1 istream.assign 27.7.2.1.2 istream.cons 27.7.2.1.1 istream.formatted 27.7.2.2 istream.formatted.arithmetic 27.7.2.2.2 istream.formatted.reqmts 27.7.2.2.1 istream.iterator 24.6.1 istream.iterator.cons 24.6.1.1 istream.iterator.ops 24.6.1.2 istream.manip 27.7.2.4 istream.rvalue 27.7.2.6 istream.unformatted 27.7.2.3 istream::extractors 27.7.2.2.3 istream::sentry 27.7.2.1.3 istreambuf.iterator 24.6.3 istreambuf.iterator.cons 24.6.3.2 istreambuf.iterator::equal 24.6.3.5 istreambuf.iterator::op!= 24.6.3.7 istreambuf.iterator::op* 24.6.3.3 istreambuf.iterator::op++ 24.6.3.4 istreambuf.iterator::op== 24.6.3.6 istreambuf.iterator::proxy 24.6.3.1 istringstream 27.8.3 istringstream.assign 27.8.3.2 istringstream.cons 27.8.3.1 istringstream.members 27.8.3.3 iterator.basic 24.4.2 iterator.iterators 24.2.2 iterator.operations 24.4.4 iterator.primitives 24.4 iterator.range 24.7 iterator.requirements 24.2 iterator.requirements.general 24.2.1 iterator.synopsis 24.3 iterator.traits 24.4.1 iterators 24 iterators.general 24.1 J K 1230
c ISO/IEC
L length.error 19.2.4 lex 2 lex.bool 2.14.6 lex.ccon 2.14.3 lex.charset 2.3 lex.comment 2.8 lex.digraph 2.6 lex.ext 2.14.8 lex.fcon 2.14.4 lex.header 2.9 lex.icon 2.14.2 lex.key 2.12 lex.literal 2.14 lex.literal.kinds 2.14.1 lex.name 2.11 lex.nullptr 2.14.7 lex.operators 2.13 lex.phases 2.2 lex.ppnumber 2.10 lex.pptoken 2.5 lex.separate 2.1 lex.string 2.14.5 lex.token 2.7 lex.trigraph 2.4 lib.types.movedfrom 17.6.5.15 library 17 library.c 17.2 library.general 17.1 limits 18.3.2 limits.numeric 18.3.2.1 limits.syn 18.3.2.2 list 23.3.5 list.capacity 23.3.5.3 list.cons 23.3.5.2 list.modifiers 23.3.5.4 list.ops 23.3.5.5 list.overview 23.3.5.1 list.special 23.3.5.6 locale 22.3.1 locale.categories 22.4 locale.category 22.3.1.1.1 locale.codecvt 22.4.1.4 locale.codecvt.byname 22.4.1.5 locale.codecvt.members 22.4.1.4.1 locale.codecvt.virtuals 22.4.1.4.2 locale.collate 22.4.4.1 locale.collate.byname 22.4.4.2 locale.collate.members 22.4.4.1.1 locale.collate.virtuals 22.4.4.1.2 locale.cons 22.3.1.2 Cross references
N3376
locale.convenience 22.3.3 locale.ctype 22.4.1.1 locale.ctype.byname 22.4.1.2 locale.ctype.members 22.4.1.1.1 locale.ctype.virtuals 22.4.1.1.2 locale.facet 22.3.1.1.2 locale.global.templates 22.3.2 locale.id 22.3.1.1.3 locale.members 22.3.1.3 locale.messages 22.4.7.1 locale.messages.byname 22.4.7.2 locale.messages.members 22.4.7.1.1 locale.messages.virtuals 22.4.7.1.2 locale.money.get 22.4.6.1 locale.money.get.members 22.4.6.1.1 locale.money.get.virtuals 22.4.6.1.2 locale.money.put 22.4.6.2 locale.money.put.members 22.4.6.2.1 locale.money.put.virtuals 22.4.6.2.2 locale.moneypunct 22.4.6.3 locale.moneypunct.byname 22.4.6.4 locale.moneypunct.members 22.4.6.3.1 locale.moneypunct.virtuals 22.4.6.3.2 locale.nm.put 22.4.2.2 locale.num.get 22.4.2.1 locale.numpunct 22.4.3.1 locale.numpunct.byname 22.4.3.2 locale.operators 22.3.1.4 locale.statics 22.3.1.5 locale.stdcvt 22.5 locale.syn 22.2 locale.time.get 22.4.5.1 locale.time.get.byname 22.4.5.2 locale.time.get.members 22.4.5.1.1 locale.time.get.virtuals 22.4.5.1.2 locale.time.put 22.4.5.3 locale.time.put.byname 22.4.5.4 locale.time.put.members 22.4.5.3.1 locale.time.put.virtuals 22.4.5.3.2 locale.types 22.3.1.1 locales 22.3 localization 22 localization.general 22.1 logic.error 19.2.1 logical.operations 20.8.6 lower.bound 25.4.3.1 M macro.names 17.6.4.3.1 make.heap 25.4.6.3 map 23.4.4 1231
c ISO/IEC
map.access 23.4.4.3 map.cons 23.4.4.2 map.modifiers 23.4.4.4 map.ops 23.4.4.5 map.overview 23.4.4.1 map.special 23.4.4.6 mask.array.assign 26.6.8.2 mask.array.comp.assign 26.6.8.3 mask.array.fill 26.6.8.4 member.functions 17.6.5.5 memory 20.6 memory.general 20.6.1 memory.syn 20.6.2 meta 20.9 meta.help 20.9.3 meta.rel 20.9.6 meta.rqmts 20.9.1 meta.trans 20.9.7 meta.trans.arr 20.9.7.4 meta.trans.cv 20.9.7.1 meta.trans.other 20.9.7.6 meta.trans.ptr 20.9.7.5 meta.trans.ref 20.9.7.2 meta.trans.sign 20.9.7.3 meta.type.synop 20.9.2 meta.unary 20.9.4 meta.unary.cat 20.9.4.1 meta.unary.comp 20.9.4.2 meta.unary.prop 20.9.4.3 meta.unary.prop.query 20.9.5 mismatch 25.2.10 move.iter.nonmember 24.5.3.3.14 move.iter.op.+ 24.5.3.3.8 move.iter.op.+= 24.5.3.3.9 move.iter.op.- 24.5.3.3.10 move.iter.op.-= 24.5.3.3.11 move.iter.op.comp 24.5.3.3.13 move.iter.op.const 24.5.3.3.1 move.iter.op.conv 24.5.3.3.3 move.iter.op.decr 24.5.3.3.7 move.iter.op.incr 24.5.3.3.6 move.iter.op.index 24.5.3.3.12 move.iter.op.ref 24.5.3.3.5 move.iter.op.star 24.5.3.3.4 move.iter.op= 24.5.3.3.2 move.iter.ops 24.5.3.3 move.iter.requirements 24.5.3.2 move.iterator 24.5.3.1 move.iterators 24.5.3 multibyte.strings 17.5.2.1.4.2 multimap 23.4.5 Cross references
N3376
multimap.cons 23.4.5.2 multimap.modifiers 23.4.5.3 multimap.ops 23.4.5.4 multimap.overview 23.4.5.1 multimap.special 23.4.5.5 multiset 23.4.7 multiset.cons 23.4.7.2 multiset.overview 23.4.7.1 multiset.special 23.4.7.3 N namespace.alias 7.3.2 namespace.constraints 17.6.4.2 namespace.def 7.3.1 namespace.memdef 7.3.1.2 namespace.posix 17.6.4.2.2 namespace.qual 3.4.3.2 namespace.std 17.6.4.2.1 namespace.udecl 7.3.3 namespace.udir 7.3.4 namespace.unnamed 7.3.1.1 narrow.stream.objects 27.4.2 negators 20.8.8 new.badlength 18.6.2.2 new.delete 18.6.1 new.delete.array 18.6.1.2 new.delete.dataraces 18.6.1.4 new.delete.placement 18.6.1.3 new.delete.single 18.6.1.1 new.handler 18.6.2.3 nullablepointer.requirements 17.6.3.3 numarray 26.6 numeric.iota 26.7.6 numeric.limits 18.3.2.3 numeric.limits.members 18.3.2.4 numeric.ops 26.7 numeric.ops.overview 26.7.1 numeric.requirements 26.2 numeric.special 18.3.2.7 numerics 26 numerics.general 26.1 O objects.within.classes 17.5.2.3 ofstream 27.9.1.10 ofstream.assign 27.9.1.12 ofstream.cons 27.9.1.11 ofstream.members 27.9.1.13 operators 20.2.1 organization 17.6.1 ostream 27.7.3.1 1232
c ISO/IEC
ostream.assign 27.7.3.3 ostream.cons 27.7.3.2 ostream.formatted 27.7.3.6 ostream.formatted.reqmts 27.7.3.6.1 ostream.inserters 27.7.3.6.3 ostream.inserters.arithmetic 27.7.3.6.2 ostream.inserters.character 27.7.3.6.4 ostream.iterator 24.6.2 ostream.iterator.cons.des 24.6.2.1 ostream.iterator.ops 24.6.2.2 ostream.manip 27.7.3.8 ostream.rvalue 27.7.3.9 ostream.seeks 27.7.3.5 ostream.unformatted 27.7.3.7 ostream::sentry 27.7.3.4 ostreambuf.iter.cons 24.6.4.1 ostreambuf.iter.ops 24.6.4.2 ostreambuf.iterator 24.6.4 ostringstream 27.8.4 ostringstream.assign 27.8.4.2 ostringstream.cons 27.8.4.1 ostringstream.members 27.8.4.3 out.of.range 19.2.5 output.iterators 24.2.4 output.streams 27.7.3 over 13 over.ass 13.5.3 over.best.ics 13.3.3.1 over.binary 13.5.2 over.built 13.6 over.call 13.5.4 over.call.func 13.3.1.1.1 over.call.object 13.3.1.1.2 over.dcl 13.2 over.ics.ellipsis 13.3.3.1.3 over.ics.list 13.3.3.1.5 over.ics.rank 13.3.3.2 over.ics.ref 13.3.3.1.4 over.ics.scs 13.3.3.1.1 over.ics.user 13.3.3.1.2 over.inc 13.5.7 over.literal 13.5.8 over.load 13.1 over.match 13.3 over.match.best 13.3.3 over.match.call 13.3.1.1 over.match.conv 13.3.1.5 over.match.copy 13.3.1.4 over.match.ctor 13.3.1.3 over.match.funcs 13.3.1 over.match.list 13.3.1.7 Cross references
N3376
over.match.oper 13.3.1.2 over.match.ref 13.3.1.6 over.match.viable 13.3.2 over.oper 13.5 over.over 13.4 over.ref 13.5.6 over.sub 13.5.5 over.unary 13.5.1 overflow.error 19.2.8 P pair.astuple 20.3.4 pair.piecewise 20.3.5 pairs 20.3 pairs.general 20.3.1 pairs.pair 20.3.2 pairs.spec 20.3.3 partial.sort 25.4.1.3 partial.sort.copy 25.4.1.4 partial.sum 26.7.4 pointer.traits 20.6.3 pointer.traits.functions 20.6.3.2 pointer.traits.types 20.6.3.1 pop.heap 25.4.6.2 predef.iterators 24.5 priority.queue 23.6.4 priqueue.cons 23.6.4.1 priqueue.cons.alloc 23.6.4.2 priqueue.members 23.6.4.3 priqueue.special 23.6.4.4 propagation 18.8.5 protection.within.classes 17.6.5.10 ptr.align 20.6.5 push.heap 25.4.6.1 Q queue 23.6.3 queue.cons 23.6.3.2 queue.cons.alloc 23.6.3.3 queue.defn 23.6.3.1 queue.ops 23.6.3.4 queue.special 23.6.3.5 queue.syn 23.6.2 R rand 26.5 rand.adapt 26.5.4 rand.adapt.disc 26.5.4.2 rand.adapt.general 26.5.4.1 rand.adapt.ibits 26.5.4.3 rand.adapt.shuf 26.5.4.4 1233
c ISO/IEC
rand.device 26.5.6 rand.dist 26.5.8 rand.dist.bern 26.5.8.3 rand.dist.bern.bernoulli 26.5.8.3.1 rand.dist.bern.bin 26.5.8.3.2 rand.dist.bern.geo 26.5.8.3.3 rand.dist.bern.negbin 26.5.8.3.4 rand.dist.general 26.5.8.1 rand.dist.norm 26.5.8.5 rand.dist.norm.cauchy 26.5.8.5.4 rand.dist.norm.chisq 26.5.8.5.3 rand.dist.norm.f 26.5.8.5.5 rand.dist.norm.lognormal 26.5.8.5.2 rand.dist.norm.normal 26.5.8.5.1 rand.dist.norm.t 26.5.8.5.6 rand.dist.pois 26.5.8.4 rand.dist.pois.exp 26.5.8.4.2 rand.dist.pois.extreme 26.5.8.4.5 rand.dist.pois.gamma 26.5.8.4.3 rand.dist.pois.poisson 26.5.8.4.1 rand.dist.pois.weibull 26.5.8.4.4 rand.dist.samp 26.5.8.6 rand.dist.samp.discrete 26.5.8.6.1 rand.dist.samp.pconst 26.5.8.6.2 rand.dist.samp.plinear 26.5.8.6.3 rand.dist.uni 26.5.8.2 rand.dist.uni.int 26.5.8.2.1 rand.dist.uni.real 26.5.8.2.2 rand.eng 26.5.3 rand.eng.lcong 26.5.3.1 rand.eng.mers 26.5.3.2 rand.eng.sub 26.5.3.3 rand.predef 26.5.5 rand.req 26.5.1 rand.req.adapt 26.5.1.5 rand.req.dist 26.5.1.6 rand.req.eng 26.5.1.4 rand.req.genl 26.5.1.1 rand.req.seedseq 26.5.1.2 rand.req.urng 26.5.1.3 rand.synopsis 26.5.2 rand.util 26.5.7 rand.util.canonical 26.5.7.2 rand.util.seedseq 26.5.7.1 random.access.iterators 24.2.7 range.error 19.2.7 ratio 20.10 ratio.arithmetic 20.10.4 ratio.comparison 20.10.5 ratio.general 20.10.1 ratio.ratio 20.10.3 Cross references
N3376
ratio.si 20.10.6 ratio.syn 20.10.2 re 28 re.alg 28.11 re.alg.match 28.11.2 re.alg.replace 28.11.4 re.alg.search 28.11.3 re.badexp 28.6 re.const 28.5 re.def 28.2 re.err 28.5.3 re.except 28.11.1 re.general 28.1 re.grammar 28.13 re.iter 28.12 re.matchflag 28.5.2 re.regex 28.8 re.regex.assign 28.8.3 re.regex.const 28.8.1 re.regex.construct 28.8.2 re.regex.locale 28.8.5 re.regex.nmswap 28.8.7.1 re.regex.nonmemb 28.8.7 re.regex.operations 28.8.4 re.regex.swap 28.8.6 re.regiter 28.12.1 re.regiter.cnstr 28.12.1.1 re.regiter.comp 28.12.1.2 re.regiter.deref 28.12.1.3 re.regiter.incr 28.12.1.4 re.req 28.3 re.results 28.10 re.results.acc 28.10.4 re.results.all 28.10.6 re.results.const 28.10.1 re.results.form 28.10.5 re.results.nonmember 28.10.8 re.results.size 28.10.3 re.results.state 28.10.2 re.results.swap 28.10.7 re.submatch 28.9 re.submatch.members 28.9.1 re.submatch.op 28.9.2 re.syn 28.4 re.synopt 28.5.1 re.tokiter 28.12.2 re.tokiter.cnstr 28.12.2.1 re.tokiter.comp 28.12.2.2 re.tokiter.deref 28.12.2.3 re.tokiter.incr 28.12.2.4 re.traits 28.7 1234
c ISO/IEC
N3376
reentrancy 17.6.5.8 refwrap 20.8.3 refwrap.access 20.8.3.3 refwrap.assign 20.8.3.2 refwrap.const 20.8.3.1 refwrap.helpers 20.8.3.5 refwrap.invoke 20.8.3.4 replacement.functions 17.6.4.6 requirements 17.6 res.on.arguments 17.6.4.9 res.on.data.races 17.6.5.9 res.on.exception.handling 17.6.5.12 res.on.functions 17.6.4.8 res.on.headers 17.6.5.2 res.on.macro.definitions 17.6.5.3 res.on.objects 17.6.4.10 res.on.pointer.storage 17.6.5.13 res.on.required 17.6.4.11 reserved.names 17.6.4.3 reverse.iter.cons 24.5.1.3.1 reverse.iter.conv 24.5.1.3.3 reverse.iter.op!= 24.5.1.3.15 reverse.iter.op+ 24.5.1.3.8 reverse.iter.op++ 24.5.1.3.6 reverse.iter.op+= 24.5.1.3.9 reverse.iter.op- 24.5.1.3.10 reverse.iter.op-= 24.5.1.3.11 reverse.iter.op.star 24.5.1.3.4 reverse.iter.op< 24.5.1.3.14 reverse.iter.op 24.5.1.3.16 reverse.iter.op>= 24.5.1.3.17 reverse.iter.opdiff 24.5.1.3.19 reverse.iter.opindex 24.5.1.3.12 reverse.iter.opref 24.5.1.3.5 reverse.iter.ops 24.5.1.3 reverse.iter.opsum 24.5.1.3.20 reverse.iter.op-- 24.5.1.3.7 reverse.iter.requirements 24.5.1.2 reverse.iterator 24.5.1.1 reverse.iterators 24.5.1 round.style 18.3.2.5 runtime.error 19.2.6 S scoped.adaptor.operators sequence.reqmts 23.2.3 sequences 23.3 sequences.general 23.3.1 Cross references
20.12.5
set 23.4.6 set.cons 23.4.6.2 set.difference 25.4.5.4 set.intersection 25.4.5.3 set.new.handler 18.6.2.4 set.overview 23.4.6.1 set.special 23.4.6.3 set.symmetric.difference 25.4.5.5 set.terminate 18.8.3.2 set.unexpected D.11.2 set.union 25.4.5.2 slice.access 26.6.4.3 slice.arr.assign 26.6.5.2 slice.arr.comp.assign 26.6.5.3 slice.arr.fill 26.6.5.4 smartptr 20.7 sort 25.4.1.1 sort.heap 25.4.6.4 special 12 specialized.addressof 20.6.12.1 specialized.algorithms 20.6.12 stable.sort 25.4.1.2 stack 23.6.5 stack.cons 23.6.5.3 stack.cons.alloc 23.6.5.4 stack.defn 23.6.5.2 stack.ops 23.6.5.5 stack.special 23.6.5.6 stack.syn 23.6.5.1 std.exceptions 19.2 std.ios.manip 27.5.6 std.iterator.tags 24.4.3 std.manip 27.7.4 stmt.ambig 6.8 stmt.block 6.3 stmt.break 6.6.1 stmt.cont 6.6.2 stmt.dcl 6.7 stmt.do 6.5.2 stmt.expr 6.2 stmt.for 6.5.3 stmt.goto 6.6.4 stmt.if 6.4.1 stmt.iter 6.5 stmt.jump 6.6 stmt.label 6.1 stmt.ranged 6.5.4 stmt.return 6.6.3 stmt.select 6.4 stmt.stmt 6 stmt.switch 6.4.2 1235
c ISO/IEC
stmt.while 6.5.1 storage.iterator 20.6.10 stream.buffers 27.6 stream.buffers.overview 27.6.1 stream.iterators 24.6 stream.types 27.5.2 streambuf 27.6.3 streambuf.assign 27.6.3.3.1 streambuf.buffer 27.6.3.2.2 streambuf.cons 27.6.3.1 streambuf.get.area 27.6.3.3.2 streambuf.locales 27.6.3.2.1 streambuf.members 27.6.3.2 streambuf.protected 27.6.3.3 streambuf.pub.get 27.6.3.2.3 streambuf.pub.pback 27.6.3.2.4 streambuf.pub.put 27.6.3.2.5 streambuf.put.area 27.6.3.3.3 streambuf.reqts 27.6.2 streambuf.virt.buffer 27.6.3.4.2 streambuf.virt.get 27.6.3.4.3 streambuf.virt.locales 27.6.3.4.1 streambuf.virt.pback 27.6.3.4.4 streambuf.virt.put 27.6.3.4.5 streambuf.virtuals 27.6.3.4 string.access 21.4.5 string.accessors 21.4.7.1 string.capacity 21.4.4 string.classes 21.3 string.cons 21.4.2 string.conversions 21.5 string.io 21.4.8.9 string.iterators 21.4.3 string.modifiers 21.4.6 string.nonmembers 21.4.8 string.ops 21.4.7 string.require 21.4.1 string.special 21.4.8.8 string.streams 27.8 string.streams.overview 27.8.1 string::append 21.4.6.2 string::assign 21.4.6.3 string::compare 21.4.7.9 string::copy 21.4.6.7 string::erase 21.4.6.5 string::find 21.4.7.2 string::find.first.not.of 21.4.7.6 string::find.first.of 21.4.7.4 string::find.last.not.of 21.4.7.7 string::find.last.of 21.4.7.5 string::insert 21.4.6.4 Cross references
N3376
string::op!= 21.4.8.3 string::op+ 21.4.8.1 string::op+= 21.4.6.1 string::op< 21.4.8.4 string::op 21.4.8.5 string::op>= 21.4.8.7 string::operator== 21.4.8.2 string::replace 21.4.6.6 string::rfind 21.4.7.3 string::substr 21.4.7.8 string::swap 21.4.6.8 stringbuf 27.8.2 stringbuf.assign 27.8.2.2 stringbuf.cons 27.8.2.1 stringbuf.members 27.8.2.3 stringbuf.virtuals 27.8.2.4 strings 21 strings.general 21.1 stringstream 27.8.5 stringstream.assign 27.8.6.1 stringstream.cons 27.8.6 stringstream.members 27.8.7 structure 17.5.1 structure.elements 17.5.1.1 structure.requirements 17.5.1.3 structure.see.also 17.5.1.5 structure.specifications 17.5.1.4 structure.summary 17.5.1.2 support.dynamic 18.6 support.exception 18.8 support.general 18.1 support.initlist 18.9 support.initlist.access 18.9.2 support.initlist.cons 18.9.1 support.initlist.range 18.9.3 support.limits 18.3 support.limits.general 18.3.1 support.rtti 18.7 support.runtime 18.10 support.start.term 18.5 support.types 18.2 swappable.requirements 17.6.3.2 syntax 1.6 syserr 19.5 syserr.compare 19.5.4 syserr.errcat 19.5.1 syserr.errcat.derived 19.5.1.4 syserr.errcat.nonvirtuals 19.5.1.3 syserr.errcat.objects 19.5.1.5 syserr.errcat.overview 19.5.1.1 1236
c ISO/IEC
syserr.errcat.virtuals 19.5.1.2 syserr.errcode 19.5.2 syserr.errcode.constructors 19.5.2.2 syserr.errcode.modifiers 19.5.2.3 syserr.errcode.nonmembers 19.5.2.5 syserr.errcode.observers 19.5.2.4 syserr.errcode.overview 19.5.2.1 syserr.errcondition 19.5.3 syserr.errcondition.constructors 19.5.3.2 syserr.errcondition.modifiers 19.5.3.3 syserr.errcondition.nonmembers 19.5.3.5 syserr.errcondition.observers 19.5.3.4 syserr.errcondition.overview 19.5.3.1 syserr.hash 19.5.5 syserr.syserr 19.5.6 syserr.syserr.members 19.5.6.2 syserr.syserr.overview 19.5.6.1 T temp 14 temp.alias 14.5.7 temp.arg 14.3 temp.arg.explicit 14.8.1 temp.arg.nontype 14.3.2 temp.arg.template 14.3.3 temp.arg.type 14.3.1 temp.class 14.5.1 temp.class.order 14.5.5.2 temp.class.spec 14.5.5 temp.class.spec.match 14.5.5.1 temp.class.spec.mfunc 14.5.5.3 temp.decls 14.5 temp.deduct 14.8.2 temp.deduct.call 14.8.2.1 temp.deduct.conv 14.8.2.3 temp.deduct.decl 14.8.2.6 temp.deduct.funcaddr 14.8.2.2 temp.deduct.partial 14.8.2.4 temp.deduct.type 14.8.2.5 temp.dep 14.6.2 temp.dep.candidate 14.6.4.2 temp.dep.constexpr 14.6.2.3 temp.dep.expr 14.6.2.2 temp.dep.res 14.6.4 temp.dep.temp 14.6.2.4 temp.dep.type 14.6.2.1 temp.expl.spec 14.7.3 temp.explicit 14.7.2 temp.fct 14.5.6 temp.fct.spec 14.8 temp.friend 14.5.4 Cross references
N3376
temp.func.order 14.5.6.2 temp.inject 14.6.5 temp.inst 14.7.1 temp.local 14.6.1 temp.mem 14.5.2 temp.mem.class 14.5.1.2 temp.mem.enum 14.5.1.4 temp.mem.func 14.5.1.1 temp.names 14.2 temp.nondep 14.6.3 temp.over 14.8.3 temp.over.link 14.5.6.1 temp.param 14.1 temp.point 14.6.4.1 temp.res 14.6 temp.spec 14.7 temp.static 14.5.1.3 temp.type 14.4 temp.variadic 14.5.3 template.bitset 20.5 template.gslice.array 26.6.7 template.gslice.array.overview 26.6.7.1 template.indirect.array 26.6.9 template.indirect.array.overview 26.6.9.1 template.mask.array 26.6.8 template.mask.array.overview 26.6.8.1 template.slice.array 26.6.5 template.slice.array.overview 26.6.5.1 template.valarray 26.6.2 template.valarray.overview 26.6.2.1 temporary.buffer 20.6.11 terminate 18.8.3.4 terminate.handler 18.8.3.1 thread 30 thread.condition 30.5 thread.condition.condvar 30.5.1 thread.condition.condvarany 30.5.2 thread.decaycopy 30.2.6 thread.general 30.1 thread.lock 30.4.2 thread.lock.algorithm 30.4.3 thread.lock.guard 30.4.2.1 thread.lock.unique 30.4.2.2 thread.lock.unique.cons 30.4.2.2.1 thread.lock.unique.locking 30.4.2.2.2 thread.lock.unique.mod 30.4.2.2.3 thread.lock.unique.obs 30.4.2.2.4 thread.mutex 30.4 thread.mutex.class 30.4.1.2.1 thread.mutex.recursive 30.4.1.2.2 thread.mutex.requirements 30.4.1 1237
c ISO/IEC
thread.mutex.requirements.general 30.4.1.1 thread.mutex.requirements.mutex 30.4.1.2 thread.once 30.4.4 thread.once.callonce 30.4.4.2 thread.once.onceflag 30.4.4.1 thread.req 30.2 thread.req.exception 30.2.2 thread.req.lockable 30.2.5 thread.req.lockable.basic 30.2.5.2 thread.req.lockable.general 30.2.5.1 thread.req.lockable.req 30.2.5.3 thread.req.lockable.timed 30.2.5.4 thread.req.native 30.2.3 thread.req.paramname 30.2.1 thread.req.timing 30.2.4 thread.thread.algorithm 30.3.1.7 thread.thread.assign 30.3.1.4 thread.thread.class 30.3.1 thread.thread.constr 30.3.1.2 thread.thread.destr 30.3.1.3 thread.thread.id 30.3.1.1 thread.thread.member 30.3.1.5 thread.thread.static 30.3.1.6 thread.thread.this 30.3.2 thread.threads 30.3 thread.timedmutex.class 30.4.1.3.1 thread.timedmutex.recursive 30.4.1.3.2 thread.timedmutex.requirements 30.4.1.3 time 20.11 time.clock 20.11.7 time.clock.hires 20.11.7.3 time.clock.req 20.11.3 time.clock.steady 20.11.7.2 time.clock.system 20.11.7.1 time.duration 20.11.5 time.duration.arithmetic 20.11.5.3 time.duration.cast 20.11.5.7 time.duration.comparisons 20.11.5.6 time.duration.cons 20.11.5.1 time.duration.nonmember 20.11.5.5 time.duration.observer 20.11.5.2 time.duration.special 20.11.5.4 time.general 20.11.1 time.point 20.11.6 time.point.arithmetic 20.11.6.3 time.point.cast 20.11.6.7 time.point.comparisons 20.11.6.6 time.point.cons 20.11.6.1 time.point.nonmember 20.11.6.5 time.point.observer 20.11.6.2 time.point.special 20.11.6.4 Cross references
N3376
time.syn 20.11.2 time.traits 20.11.4 time.traits.duration_values 20.11.4.2 time.traits.is_fp 20.11.4.1 time.traits.specializations 20.11.4.3 tuple 20.4 tuple.assign 20.4.2.2 tuple.cnstr 20.4.2.1 tuple.creation 20.4.2.4 tuple.elem 20.4.2.6 tuple.general 20.4.1 tuple.helper 20.4.2.5 tuple.rel 20.4.2.7 tuple.special 20.4.2.9 tuple.swap 20.4.2.3 tuple.traits 20.4.2.8 tuple.tuple 20.4.2 type.descriptions 17.5.2.1 type.descriptions.general 17.5.2.1.1 type.index 20.13 type.index.hash 20.13.4 type.index.members 20.13.3 type.index.overview 20.13.2 type.index.synopsis 20.13.1 type.info 18.7.1 U uncaught 18.8.4 underflow.error 19.2.9 unexpected D.11.4 unexpected.handler D.11.1 uninitialized.copy 20.6.12.2 uninitialized.fill 20.6.12.3 uninitialized.fill.n 20.6.12.4 unique.ptr 20.7.1 unique.ptr.dltr 20.7.1.1 unique.ptr.dltr.dflt 20.7.1.1.2 unique.ptr.dltr.dflt1 20.7.1.1.3 unique.ptr.dltr.general 20.7.1.1.1 unique.ptr.runtime 20.7.1.3 unique.ptr.runtime.ctor 20.7.1.3.1 unique.ptr.runtime.modifiers 20.7.1.3.3 unique.ptr.runtime.observers 20.7.1.3.2 unique.ptr.single 20.7.1.2 unique.ptr.single.asgn 20.7.1.2.3 unique.ptr.single.ctor 20.7.1.2.1 unique.ptr.single.dtor 20.7.1.2.2 unique.ptr.single.modifiers 20.7.1.2.5 unique.ptr.single.observers 20.7.1.2.4 unique.ptr.special 20.7.1.4 unord 23.5 1238
c ISO/IEC
unord.general 23.5.1 unord.hash 20.8.12 unord.map 23.5.4 unord.map.cnstr 23.5.4.2 unord.map.elem 23.5.4.3 unord.map.modifiers 23.5.4.4 unord.map.overview 23.5.4.1 unord.map.swap 23.5.4.5 unord.map.syn 23.5.2 unord.multimap 23.5.5 unord.multimap.cnstr 23.5.5.2 unord.multimap.modifiers 23.5.5.3 unord.multimap.overview 23.5.5.1 unord.multimap.swap 23.5.5.4 unord.multiset 23.5.7 unord.multiset.cnstr 23.5.7.2 unord.multiset.overview 23.5.7.1 unord.multiset.swap 23.5.7.3 unord.req 23.2.5 unord.req.except 23.2.5.1 unord.set 23.5.6 unord.set.cnstr 23.5.6.2 unord.set.overview 23.5.6.1 unord.set.swap 23.5.6.3 unord.set.syn 23.5.3 upper.bound 25.4.3.2 using 17.6.2 using.headers 17.6.2.2 using.linkage 17.6.2.3 using.overview 17.6.2.1 usrlit.suffix 17.6.4.3.5 util.dynamic.safety 20.6.4 util.smartptr 20.7.2 util.smartptr.enab 20.7.2.4 util.smartptr.getdeleter 20.7.2.2.10 util.smartptr.hash 20.7.2.6 util.smartptr.ownerless 20.7.2.3.7 util.smartptr.shared 20.7.2.2 util.smartptr.shared.assign 20.7.2.2.3 util.smartptr.shared.atomic 20.7.2.5 util.smartptr.shared.cast 20.7.2.2.9 util.smartptr.shared.cmp 20.7.2.2.7 util.smartptr.shared.const 20.7.2.2.1 util.smartptr.shared.create 20.7.2.2.6 util.smartptr.shared.dest 20.7.2.2.2 util.smartptr.shared.io 20.7.2.2.11 util.smartptr.shared.mod 20.7.2.2.4 util.smartptr.shared.obs 20.7.2.2.5 util.smartptr.shared.spec 20.7.2.2.8
Cross references
N3376
util.smartptr.weak 20.7.2.3 util.smartptr.weak.assign 20.7.2.3.3 util.smartptr.weak.const 20.7.2.3.1 util.smartptr.weak.dest 20.7.2.3.2 util.smartptr.weak.mod 20.7.2.3.4 util.smartptr.weak.obs 20.7.2.3.5 util.smartptr.weak.spec 20.7.2.3.6 util.smartptr.weakptr 20.7.2.1 utilities 20 utilities.general 20.1 utility 20.2 utility.arg.requirements 17.6.3.1 utility.requirements 17.6.3 utility.swap 20.2.2 V valarray.access 26.6.2.4 valarray.assign 26.6.2.3 valarray.binary 26.6.3.1 valarray.cassign 26.6.2.7 valarray.comparison 26.6.3.2 valarray.cons 26.6.2.2 valarray.members 26.6.2.8 valarray.nonmembers 26.6.3 valarray.range 26.6.10 valarray.special 26.6.3.4 valarray.sub 26.6.2.5 valarray.syn 26.6.1 valarray.transcend 26.6.3.3 valarray.unary 26.6.2.6 value.error.codes 17.6.5.14 vector 23.3.6 vector.bool 23.3.7 vector.capacity 23.3.6.3 vector.cons 23.3.6.2 vector.data 23.3.6.4 vector.modifiers 23.3.6.5 vector.overview 23.3.6.1 vector.special 23.3.6.6 W wide.stream.objects X xref
27.4.3
F
Y Z
1239
c ISO/IEC
N3376
Index !, see operator, logical negation !=, see inequality operator (), see operator, function call, see declarator, function *, see operator, indirection, see multiplication operator, see declarator, pointer +, see operator, unary plus, see addition operator ++, see operator, increment ,, see comma operator -, see operator, unary minus, see subtraction operator ->, see operator, class member access ->*, see pointer to member operator --, see operator, decrement ., see operator, class member access .*, see pointer to member operator ..., see ellipsis /, see division operator : field declaration, 215 label specifier, 124 ::, see scope resolution operator ::*, see declarator, pointer to member , see right shift operator ?:, see conditional expression operator [], see operator, subscripting, see declarator, array ¨...¨, see preprocessing directives, source-file inclusion # operator, 391, 392 ## operator, 392 #define, 391 #elif, 388 #else, 389 #endif, 389 #error, see preprocessing directives, error
#if, 388, 422 #ifdef, 389 #ifndef, 389 #include, 389, 409 #line, see preprocessing directives, line control #pragma, see preprocessing directives, pragma #undef, 393, 419 %, see remainder operator &, see operator, address-of, see bitwise AND operator, see declarator, reference &&, see logical AND operator ˆ, see bitwise exclusive OR operator _ _ DATE _ _, 396 _ _ FILE _ _, 396 _ _ LINE _ _, 396 _ _ STDC _ _, 396 implementation-defined, 396 _ _ STDCPP_STRICT_POINTER_SAFETY _ _, 397 implementation-defined, 397 _ _ STDCPP_THREADS _ _, 397 implementation-defined, 397 _ _ STDC_HOSTED _ _, 396 implementation-defined, 396 _ _ STDC_ISO_10646 _ _, 397 implementation-defined, 397 _ _ STDC_MB_MIGHT_NEQ_WC _ _, 396 implementation-defined, 396 _ _ STDC_VERSION _ _, 396 implementation-defined, 396 _ _ TIME _ _, 396 _ _ VA_ARGS _ _, 391 _ _cplusplus, 396 \, see backslash {} block statement, 124 class declaration, 204 class definition, 204 enum declaration, 149 initializer list, 193 ~, see destructor _, see character, underscore |, see bitwise inclusive OR operator ||, see logical OR operator ~, see operator, one’s complement 0, see also zero, null
Cross references
1240
c ISO/IEC
null character, 29 string terminator, 29 abort, 62, 129 abstract-declarator, 173, 1176 abstract-pack-declarator, 173, 1176 access control, 231–241 base class, 233 base class member, 219 class member, 96 default, 231 default argument, 232 friend function, 236 member name, 231 multiple access, 240 nested class, 240 overloading and, 276 private, 231 protected, 231, 239 public, 231 union default member, 204 using-declaration and, 161 virtual function, 240 access-specifier, 219, 1178 access control anonymous union, 215 member function and, 242 overloading resolution and, 223 access specifier, 232, 233 addition operator, 113 additive-expression, 113, 1169 address, 73, 116 address of member function unspecified, 422 aggregate, 193 aggregate initialization, 193 algorithm stable, 401, 423 alias namespace, 156 alias template, 331 alias-declaration, 133, 1171 alignment extended, 76 fundamental, 76 alignment-specifier, 167, 1174 alignment requirement implementation-defined, 76 allocation alignment storage, 108 implementation defined bit-field, 216 Cross references
N3376
unspecified, 209 allocation functions, 63 allowing an exception, see exception handling, allowing an exception alternative token, see token, alternative ambiguity base class member, 222 class conversion, 224 declaration type, 135 declaration versus cast, 174 declaration versus expression, 131 function declaration, 191 member access, 222 overloaded function, 276 parentheses and, 107 Amendment 1, 419 and-expression, 116, 1169 appertain, 168 argc, 59 argument, 2, 421, 422, 458 access checking and default, 232 binding of default, 185 evaluation of default, 185, 186 example of default, 184, 185 function call expression, 2 function-like macro, 2 overloaded operator and default, 296 reference, 94 scope of default, 186 template, 308 template instantiation, 2 throw expression, 2 type checking of default, 185 arguments implementation-defined order of evaluation of function, 186 argument and name hiding default, 186 argument and virtual function default, 186 argument list empty, 181 variable, 181 argument passing, 94 reference and, 196 argument substitution, see macro, argument substitution argument type unknown, 181 argv, 59 arithmetic 1241
c ISO/IEC
pointer, 113 unsigned, 71 array, 181 bound, 179 const, 73 delete, 110 multidimensional, 180 new, 107 overloading and pointer versus, 274 sizeof, 105 storage of, 180 array as aggregate, 731 contiguous storage, 731 initialization, 731, 733 tuple interface to, 733 zero sized, 733 array size default, 179 arrow operator, see operator, class member access as-if rule, 8 asm implementation-defined, 164 asm-definition, 164, 1174 assembler, 164 , 409 assignment and lvalue, 119 conversion by, 119 copy, see assignment operator, copy move, see assignment operator, move, 400 reference, 196 assignment operator copy, 242, 265–267 hidden, 266 implicitly declared, 265 implicitly defined, 267 inaccessible, 267 trivial, 266 virtual bases and, 267 move, 242, 265–267 hidden, 266 implicitly declared, 265 implicitly defined, 267 inaccessible, 267 trivial, 266 virtual bases and, 267 overloaded, 297 assignment-expression, 119, 1170 assignment-operator, 119, 1170 associative containers Cross references
N3376
exception safety, 719 requirements, 719 unordered, see unordered associative containers asynchronous provider, 1147 asynchronous return object, 1147 atexit, 61 atomic operations, see operation, atomic attribute, 167–171 alignment, 169 carries dependency, 170 noreturn, 170 syntax and semantics, 167 attribute, 168, 1174 attribute-argument-clause, 168, 1175 attribute-declaration, 133, 1171 attribute-list, 168, 1174 attribute-namespace, 168, 1175 attribute-scoped-token, 168, 1175 attribute-specifier, 167, 1174 attribute-specifier-seq, 167, 1174 attribute-token, 168, 1175 automatic storage duration, 63 awk, 1059 backslash character, 26 bad_alloc, 108 bad_cast, 98 bad_exception, 386 bad_typeid, 99 bad_typeid::what implementation-defined, 447 balanced-token, 168, 1175 balanced-token-seq, 168, 1175 base class overloading and, 275 base class subobject, 7 base-clause, 219, 1177 base-specifier, 219, 1178 base-specifier-list, 219, 1178 base-type-specifier, 219, 1178 BaseCharacteristic, 559 base class, 219, 220 direct, 219 indirect, 219 private, 233 protected, 233 public, 233 base class virtual, see virtual base class basic_ios::failure argument implementation-defined, 981 1242
c ISO/IEC
begin unordered associative containers, 727 behavior conditionally-supported, 2, 5 default, 400, 404 implementation-defined, 3, 8 locale-specific, 3 observable, 8, 9 on receipt of signal, 8 required, 401, 404 undefined, 4, 5, 8 unspecified, 4, 8 Ben, 276 Bernoulli distributions, 913–916 bernoulli_distribution discrete probability function, 913 binary function, 544 binary operator overloaded, 297 BinaryTypeTrait, 559 binary operator interpretation of, 297 bind directly, 198 binding reference, 197 binomial_distribution discrete probability function, 914 bit-field, 215 address of, 216 alignment of, 216 implementation-defined sign of, 216 implementation defined alignment of, 216 type of, 216 unnamed, 216 zero width of, 216 block, 399 initialization in, 130 block scope, 39 block statement, see statement, compound block-declaration, 133, 1171 block structure, 130 body function, 187 Boolean, 216 Boolean literal, 29 boolean literal, see literal, boolean boolean-literal, 29, 1166 Boolean type, 72 bound arguments, 552 bound, of array, 179 brace-or-equal-initializer, 190, 1176 Cross references
N3376
braced-init-list, 190, 1177 bucket unordered associative containers, 727 bucket_count unordered associative containers, 727 bucket_size unordered associative containers, 727 buckets, 720 byte, 6, 105 C linkage to, 165 standard, 1 standard library, 1 Unicode TR, 1 c-char, 25, 1164 c-char-sequence, 25, 1164 call operator function, 296 pseudo destructor, 96 call signature, 543 call wrapper, 543, 544 forwarding, 544 simple, 544 type, 543 Callable, 555 callable object, 543, 555 callable type, 543 capture, 88, 1167 capture-default, 88, 1167 capture-list, 88, 1167 captured, 90 by copy, 91 by reference, 91 carries a dependency, 12 carry subtract_with_carry_engine, 901 , 409 cast base class, 100 const, 102, 111 derived class, 100 dynamic, 97, 446 construction and, 261 destruction and, 261 integer to pointer, 101 lvalue, 99, 101 pointer-to-function, 101 pointer-to-member, 101, 102 pointer to integer, 101 reference, 99, 102 1243
c ISO/IEC
reinterpret, 101, 111 integer to pointer, 101 lvalue, 101 pointer to integer, 101 pointer-to-function, 101 pointer-to-member, 102 reference, 102 static, 99, 111 lvalue, 99 reference, 99 undefined pointer-to-function, 101 cast-expression, 111, 1169 casting, 95 catch, 377 cauchy_distribution probability density function, 923 cbegin unordered associative containers, 727 cend unordered associative containers, 727 , 419 char implementation-defined sign of, 71 char-like object, 601 char-like type, 601 char16_t, 25 char16_t character, 25 char32_t, 25 char32_t character, 25 char_class_type regular expression traits, 1050 character, 399 decimal-point, 406 multibyte, 3 signed, 71 source file, 16 underscore, 419 in identifier, 22 character literal, see literal, character character set, 17–18 basic execution, 6 basic source, 16, 17 character string literal, 392 character-literal, 25, 1164 character string, 28 checking point of error, 333 syntax, 333 chi_squared_distribution probability density function, 923 class, 72, 204–218 Cross references
N3376
abstract, 229 base, 420, 424 cast to incomplete, 112 constructor and abstract, 230 definition, 34 derived, 424 linkage of, 56 linkage specification, 166 member function, see member function, class pointer to abstract, 230 polymorphic, 225 scope of enumerator, 152 standard-layout, 205 trivial, 204 unnamed, 139 class-head, 204, 1177 class-head-name, 204, 1177 class-key, 204, 1177 class-name, 204, 1177 class-or-decltype, 219, 1178 class-specifier, 204, 1177 class-virt-specifier, 204, 1177 class local, see local class class name, 173 elaborated, 148, 206, 207 point of declaration, 207 scope of, 206 typedef, 139, 207 class nested, see nested class class object assignment to, 119 const, 74 member, 209 sizeof, 105 class object copy, see copy constructor class object initialization, see constructor clear unordered associative containers, 726 , 406 closure object, 88 closure type, 88 collating element, 1049 comment, 19–20 /* */, 20 //, 20 comparison pointer, 115, 116 pointer to function, 115, 116 undefined pointer, 114, 115 unspecified pointer, 115 void* pointer, 115 1244
c ISO/IEC
compatible, see exception specification, compatible compilation separate, 16 compiler control line, see preprocessing directives complete object, 7 complete object of, 7 completely defined, 208 component, 399 compound-statement, 124, 1170 concatenation macro argument, see ## string, 28 condition, 125, 1170 conditions rules for, 125 conditional-expression throw-expression in, 117 conditional-expression, 117, 1170 conditionally-supported behavior seebehavior, conditionally-supported, 1 conflict, 11 conformance requirements, 5, 8 class templates, 5 classes, 5 general, 5 library, 5 method of description, 5 consistency linkage, 136 linkage specification, 166 type declaration, 58 const, 73 constructor and, 212, 243 destructor and, 212, 249 linkage of, 56, 136 overloading and, 275 const_cast, see cast, const const_local_iterator, 721 unordered associative containers, 721 constant, 23, 85 enumeration, 150 null pointer, 80, 81 constant iterator, 804 constant-expression, 120, 1170 constexpr function, 140 construction, 259–261 dynamic cast and, 261 member access, 259 move, 400 pointer to member or base, 259 Cross references
N3376
typeid operator, 261 virtual function call, 260 constructor, 242 address of, 244 array of class objects and, 254 converting, 247 copy, 242, 245, 261–264, 406 elision, 267 implicitly declared, 263 implicitly defined, 264 inaccessible, 267 trivial, 264 default, 242, 243 exception handling, see exception handling, constructors and destructors explicit call, 244 implicitly called, 243 implicitly defined, 243 inheritance of, 243 inheriting, 269–272 move, 242, 261–264 elision, 267 implicitly declared, 263 implicitly defined, 264 inaccessible, 267 trivial, 264 non-trivial, 243 random number distribution requirement, 894 random number engine requirement, 891 type of, 244 union, 214 unspecified argument to, 108 constructor, conversion by, see conversion, userdefined constructor, default, see default constructor const-object undefined change to, 144 context non-deduced, 368 contextually converted to bool, see conversion, contextual continue and handler, 377 and try block, 377 control line, see preprocessing directives control-line, 387, 1180 conventions, 404 lexical, 16–31 conversion argument, 181 array-to-pointer, 78 1245
c ISO/IEC
bool, 80 boolean, 81 class, 246 contextual, 77 derived-to-base, 287 floating point, 80 floating to integral, 80 function-to-pointer, 78 implementation defined pointer integer, 101 implicit, 77, 246 implicit user-defined, 246 inheritance of user-defined, 249 integer rank, 81 integral, 80 integral to floating, 80 lvalue-to-rvalue, 78, 1186 narrowing, 202 overload resolution and pointer, 295 overload resolution and, 284 pointer, 80 pointer to member, 81 void*, 81 qualification, 78–79 return type, 130 standard, 77–82 static user-defined, 249 to signed, 80 to unsigned, 80 type of, 248 user-defined, 246–248 usual arithmetic, 84 virtual user-defined, 249 conversion operator, see conversion, user defined conversion rank, 288 conversion-declarator, 248, 1178 conversion-function-id, 248, 1178 conversion-type-id, 248, 1178 conversion explicit type, see casting conversion function, see conversion, user-defined copy class object, see constructor, copy; assignment, copy copy constructor random number engine requirement, 891 copy elision, see constructor, copy, elision; constructor, move, elision copy-initialization, 192 CopyInsertable into X, 707 count unordered associative containers, 727 , 181 Cross references
N3376
, 106, 114 , 436 , 62, 408 , 406 ctor-initializer, 255, 1178 <cuchar>, 419 cv-qualifier, 73 cv-qualifier, 173, 1175 cv-qualifier-seq, 173, 1175 , 419 , 419 d-char, 27, 1166 d-char-sequence, 27, 1166 DAG multiple inheritance, 221, 222 non-virtual base class, 222 virtual base class, 221, 222 data race, 14 data member, see member deadlock, 400 deallocation, see delete deallocation functions, 63 decay, see conversion, array to pointer; conversion, function to pointer DECAY_COPY, 1118 decimal-literal, 23, 1164 decl-specifier, 134, 1172 decl-specifier-seq, 135, 1172 declaration, 32, 133–171 array, 179 asm, 164 bit-field, 215 class name, 33 constant pointer, 176 default argument, 184–187 definition versus, 32 ellipsis in function, 94, 181 enumerator point of, 38 extern, 33 extern reference, 196 forward, 137 forward class, 206 function, 33, 181 local class, 217 member, 207 multiple, 58 name, 32 opaque enum, 33 overloaded, 273 overloaded name and friend, 237 1246
c ISO/IEC
parameter, 33, 181 parentheses in, 174, 176 pointer, 176 reference, 177 register, 135 static member, 33 storage class, 135 type, 175 typedef, 33 typedef as type, 138 declaration, 133, 1171 declaration-seq, 133, 1171 declaration-statement, 130, 1171 declaration hiding, see name hiding declarative region, 37 declarator, 33, 134, 172–203 array, 179 function, 180–184 meaning of, 175–187 multidimensional array, 180 pointer, 176 pointer to member, 178 reference, 177 declarator, 172, 1175 declarator-id, 173, 1176 decltype-specifier, 145, 1173 decrement operator overloaded, see overloading, decrement operator default access control, see access control, default default constructor random number distribution requirement, 894 seed sequence requirement, 889 default-initialization, 191 default-inserted, 707 defaulted, 188 DefaultInsertable into X, 707 default argument overload resolution and, 284 default initializers overloading and, 275 deferred function, 1157 definition, 33 alternate, 420 class, 204, 208 class name as type, 206 constructor, 187 declaration as, 134 function, 187–190 deleted, 189 explicitly-defaulted, 188 Cross references
N3376
local class, 217 member function, 210 namespace, 152 nested class, 216 pure virtual function, 229 scope of class, 206 static member, 213 virtual function, 228 definitions, 2–5 delete, 63, 109, 110, 252 array, 110 destructor and, 110, 250 object, 110 operator, 420 overloading and, 64 type of, 252 undefined, 110 delete-expression, 109, 1169 deleter, 513 dependency-ordered before, 12 deprecated features, 97, 105 dereferencing, see also indirection derivation, see inheritance derived class most, see most derived class derived object most, see most derived object derived class, 219–230 destruction, 259–261 dynamic cast and, 261 member access, 259 pointer to member or base, 259 typeid operator, 261 virtual function call, 260 destructor, 249, 406 default, 249 exception handling, see exception handling, constructors and destructors explicit call, 250, 251 implicit call, 250 implicitly defined, 250 non-trivial, 249 program termination and, 250 pure virtual, 250 union, 214 virtual, 250 diagnosable rules, 5 diagnostic message, see message, diagnostic digit, 21, 1163 digit-sequence, 27, 1165 digraph, see token, alternative, 20 1247
c ISO/IEC
directed acyclic graph, see DAG directive, preprocessing, see preprocessing directives discard random number engine requirement, 891 discard_block_engine generation algorithm, 903 state, 903 textual representation, 904 transition algorithm, 903 discarded-value expression, 84 discrete probability function bernoulli_distribution, 913 binomial_distribution, 914 discrete_distribution, 926 geometric_distribution, 915 negative_binomial_distribution, 915 poisson_distribution, 916 uniform_int_distribution, 911 discrete_distribution discrete probability function, 926 weights, 926 distribution, see random number distribution dominance virtual base class, 224 dot operator, see operator, class member access dynamic binding, see virtual function dynamic initialization, 59 dynamic type, see type, dynamic dynamic-exception-specification, 382, 1180 dynamic_cast, see cast, dynamic ECMA-262, 1 ECMAScript, 1059, 1094 egrep, 1059 elaborated-type-specifier, 148, 1173 elaborated type specifier, see class name, elaborated elif-group, 387, 1180 elif-groups, 387, 1180 elision copy, see constructor, copy, elision; constructor, move, elision copy constructor, see constructor, copy, elision move constructor, see constructor, move, elision ellipsis conversion sequence, 94, 288 overload resolution and, 284 else-group, 387, 1180 Cross references
N3376
EmplaceConstructible into X from args, 707 empty future object, 1152 empty shared_future object, 1154 empty-declaration, 133, 1171 encoding multibyte, 29 encoding-prefix, 27, 1165 end unordered associative containers, 727 end-of-file, 497 endif-line, 387, 1180 engine, see random number engine engine adaptor, see random number engine adaptor engines with predefined parameters default_random_engine, 907 knuth_b, 907 minstd_rand, 906 minstd_rand0, 906 mt19937, 906 mt19937_64, 906 ranlux24, 907 ranlux24_base, 906 ranlux48, 907 ranlux48_base, 906 entity, 32 enum, 73 overloading and, 274 type of, 149, 150 underlying type, 150 enum-base, 150, 1173 enum-head, 149, 1173 enum-key, 150, 1173 enum-name, 149, 1173 enum-specifier, 149, 1173 enumeration, 149, 150 linkage of, 56 scoped, 150 unscoped, 150 enumeration scope, 41 enumeration type conversion to, 100 static_cast conversion to, 100 enumerator definition, 34 value of, 150 enumerator, 150, 1173 enumerator-definition, 150, 1173 enumerator-list, 150, 1173 enum name 1248
c ISO/IEC
typedef, 139 environment program, 59 epoch, 580 equal_range unordered associative containers, 727 equality-expression, 116, 1169 equivalence template type, 314 type, 138, 206 equivalent-key group, 720 equivalent parameter declarations, 274 overloading and, 274 Erasable from X, 707 erase unordered associative containers, 726 escape-sequence, 25, 1165 escape character, see backslash escape sequence undefined, 26 Evaluation, 10 evaluation order of argument, 95 unspecified order of, 10, 60 unspecified order of argument, 95 unspecified order of function call, 95 example array, 179 class definition, 209 const, 176 constant pointer, 176 constructor, 244 constructor and initialization, 254 declaration, 33, 183 declarator, 173 definition, 33 delete, 252 derived class, 219 destructor and delete, 253 ellipsis, 181 enumeration, 151 explicit destructor call, 251 explicit qualification, 223 friend, 207 friend function, 236 function declaration, 182 function definition, 187 linkage consistency, 136 local class, 217 member function, 211, 236 nested type name, 218 Cross references
N3376
nested class, 216 nested class definition, 217, 240 nested class forward declaration, 217 pointer to member, 178 pure virtual function, 230 scope of delete, 253 scope resolution operator, 223 static member, 213 subscripting, 179 typedef, 138 type name, 173 unnamed parameter, 187 variable parameter list, 181 virtual function, 227, 228 exception arithmetic, 83 undefined arithmetic, 83 <exception>, 447 exception handling, 377–386 allowing an exception, 383 constructors and destructors, 380 exception object, 379 constructor, 379 destructor, 379 function try block, 378 goto, 377 handler, 377, 379–382, 424 array in, 380 incomplete type in, 380 match, 380–382 pointer to function in, 380 rvalue reference in, 380 memory, 379 nearest handler, 379 rethrow, 379, 380 rethrowing, 379 switch, 377 terminate() called, 379, 380, 383 throwing, 378, 379 try block, 377 unexpected() called, 383 exception object, see exception handling, exception object exception specification, 382–385 compatible, 382 incomplete type and, 382 noexcept constant expression and, 382 virtual function and, 383 exception-declaration, 377, 1179 exception-specification, 382, 1180 1249
c ISO/IEC
exception::what message implementation-defined, 448 exclusive-or-expression, 117, 1169 execution agent, 1116 exit, 59, 61, 129 explicit-instantiation, 349, 1179 explicit-specialization, 351, 1179 explicitly captured, 90 explicit type conversion, see casting exponent-part, 26, 1165 exponential_distribution probability density function, 917 expression, 83–123 additive operators, 113 alignof, 110 assignment and compound assignment, 119 bitwise AND, 116 bitwise exclusive OR, 117 bitwise inclusive OR, 117 cast, 95, 111–112 class member access, 96 comma, 120 conditional operator, 117 constant, 120 const cast, 102 decrement, 97, 105 delete, 109 dynamic cast, 97 equality operators, 116 function call, 93 increment, 97, 105 lambda, 88–93 left-shift-operator, 114 logical AND, 117 logical OR, 117 multiplicative operators, 113 new, 106 noexcept, 110 order of evaluation of, 9 parenthesized, 86 pointer-to-member, 112 pointer to member constant, 104 postfix, 93–104 primary, 85–93 pseudo-destructor call, 96 reference, 83 reinterpret cast, 101 relational operators, 114 right-shift-operator, 114 rvalue reference, 83 sizeof, 105 Cross references
N3376
static cast, 99 type identification, 99 unary, 104–111 unary operator, 104 expression, 120, 1170 expression-list, 93, 1168 expression-statement, 124, 1170 extended alignment, 76 extended integer type, 71 extended signed integer type, 71 extended unsigned integer type, 71 extension-namespace-definition, 153, 1174 extern, 135 linkage of, 136 extern "C", 409, 419 extern "C++", 409, 419 external linkage, 56 extreme_value_distribution probability density function, 920 file, source, see source file final overrider, 225 find unordered associative containers, 726 finite state machine, 1049 fisher_f_distribution probability density function, 924 floating literal, see literal, floating floating-literal, 26, 1165 floating-point literal, see literal, floating floating-suffix, 27, 1165 floating point type, 72 implementation-defined, 72 for scope of declaration in, 128 for-init-statement, 126, 1171 for-range-declaration, 126, 1171 for-range-initializer, 126, 1171 formal argument, see parameter format specifier, 1049 forwarding call wrapper, 544 fractional-constant, 26, 1165 free store, 252 freestanding implementation, 5 free store, see also new, delete friend virtual and, 228 access specifier and, 238 class access and, 236 inheritance and, 238 local class and, 238 1250
c ISO/IEC
template and, 321 friend function access and, 236 inline, 237 linkage of, 237 member function and, 236 friend function nested class, 217 full-expression, 9 function, see also friend function; member function; inline function; virtual function, 181 allocation, 63, 107 comparison, 399 conversion, 248 deallocation, 64, 110, 252 definition, 34 global, 419, 422 handler, 400 linkage specification overloaded, 166 modifier, 400 observer, 401 operator, 296 overload resolution and, 277 plain old, 454 pointer to member, 112 replacement, 401 reserved, 401 viable, 277 virtual member, 420, 422 function invocation substitution, 141 function object, 539 binders, 550–552 mem_fn, 552–553 reference_wrapper, 544 type, 539 wrapper, 553–558 function pointer type, 73 function try block, see exception handling, function try block function, overloaded, see overloading function, virtual, see virtual function function-definition, 187, 1176 function-like macro, see macro, function-like function-specifier, 137, 1172 function-try-block, 377, 1179 functions candidate, 344 function argument, see argument function call, 94 recursive, 95 undefined, 101 Cross references
N3376
function call operator overloaded, 297 function parameter, see parameter function prototype, 39 function return, see return function return type, see return type fundamental alignment, 76 fundamental type destructor and, 251 fundamental type conversion, see conversion, userdefined future shared state, 1147 gamma_distribution probability density function, 918 generate seed sequence requirement, 889 generated destructor, see destructor, default generation algorithm discard_block_engine, 903 independent_bits_engine, 904 linear_congruential_engine, 899 mersenne_twister_engine, 900 shuffle_order_engine, 905 subtract_with_carry_engine, 901 geometric_distribution discrete probability function, 915 global, 40 global namespace, 40 global namespace scope, 40 global scope, 40 glvalue, 74 goto and handler, 377 and try block, 377 initialization and, 130 grammar regular expression, 1094 grep, 1059 group, 387, 1180 group-part, 387, 1180 h-char, 20, 1163 h-char-sequence, 20, 1163 handler, see exception handling, handler handler, 377, 1179 handler-seq, 377, 1179 happens before, 13 hash instantiation restrictions, 558 1251
c ISO/IEC
N3376
hash code, 720 hash function, 720 hash tables, see unordered associative containers hash_function unordered associative containers, 724 hasher unordered associative containers, 721 header C, 419, 422, 1202 C library, 409 C++ library, 407 name, 20–21 header-name, 20, 1163 hex-quad, 17, 1162 hexadecimal-digit, 23, 1164 hexadecimal-escape-sequence, 25, 1165 hexadecimal-literal, 23, 1164 hiding, see name hiding high-order bit, 6 hosted implementation, 5
non-static member function and, 278 inclusion conditional, see preprocessing directive, conditional inclusion source file, see preprocessing directives, sourcefile inclusion inclusive-or-expression, 117, 1169 incomplete, 113 increment bool, 97, 105 increment operator overloaded, see overloading, increment operator independent_bits_engine generation algorithm, 904 state, 904 textual representation, 905 transition algorithm, 904 indeterminately sequenced, 10 indirection, 104 inheritance, 219 id init-declarator, 172, 1175 qualified, 87 init-declarator-list, 172, 1175 id-expression, 86 initialization, 59, 190–203 id-expression, 85, 1166 aggregate, 193 identifier, 21–22, 86, 134 array, 193 identifier, 21, 1163 array of class objects, 195, 254 identifier-list, 388, 1181 automatic, 130, 131 identifier-nondigit, 21, 1163 automatic object, 190 if-group, 387, 1180 base class, 255, 256 if-section, 387, 1180 character array, 196 ill-formed program, see program, ill-formed character array, 196 immolation class member, 191 self, 354 class object, see also constructor, 193, 253– implementation 259 freestanding, 408 const, 144, 193 hosted, 408 const member, 256 implementation limits, see limits, implementation constant, 59 implementation-defined, 419, 427, 439, 444, 446– constructor and, 253, 254 449, 652, 974, 1027, 1201 copy, 192 implementation-defined behavior, see behavior, implemendefault, 190 tation-defined default constructor and, 253 implementation-dependent, 1000 definition and, 134 implementation-generated, 33 direct, 192 implicit object parameter, 277 dynamic, 59 implicitly captured, 90 explicit, 254 implicitly-declared default constructor, see conjump past, 130 structor, default, 243 list-initialization, 198–203 implicit conversion, see conversion, implicit local static, 131 implied object argument, 277 member, 255 implicit conversion sequences, 278 member function call during, 258 Cross references
1252
c ISO/IEC
member object, 256 order of, 59, 220 order of base class, 257 order of member, 257 order of virtual base class, 257 overloaded assignment and, 254 parameter, 94 reference, 178, 196 reference member, 256 run-time, 59 static and thread, 59 static member, 213 static object, 59 static object, 190 union, 195, 215 virtual base class, 264 initializer base class, 187 member, 187 pack expansion, 259 scope of member, 258 temporary and declarator, 245 initializer, 190, 1176 initializer-clause, 190, 1176 initializer-list, 190, 1177 initializer-list constructor seed sequence requirement, 889 , 452 injected-class-name, 204 inline, 422 inline linkage of, 56 inline function, 137 insert unordered associative containers, 725, 726 instantiation explicit, 349 point of, 343 template implicit, 346 instantiation units, 17 integer literal, see literal, integer integer representation, 65 integer-literal, 23, 1164 integer-suffix, 23, 1164 integer type, 72 integral type, 72 sizeof, 71 inter-thread happens before, 12 internal linkage, 56 interval boundaries piecewise_constant_distribution, 928 Cross references
N3376
piecewise_linear_distribution, 930 invocation macro, 391 isctype regular expression traits, 1051 iteration-statement, 126, 129, 1170 Jessie, 247 jump-statement, 129, 1171 key_eq unordered associative containers, 724 key_equal unordered associative containers, 721 key_type unordered associative containers, 720 keyword, 22 label, 130 case, 124, 126 default, 124, 126 scope of, 39, 124 labeled-statement, 124, 1170 lambda-capture, 88, 1167 lambda-declarator, 88, 1167 lambda-expression, 88, 1167 lambda-introducer, 88, 145, 1167 lattice, see DAG, subobject layout bit-field, 216 class object, 209, 220 layout-compatible type, 151 layout-compatible type, 71 left shift undefined, 114 left shift operator, 114 lexical conventions, see conventions, lexical library C standard, 399, 406, 407, 409, 1198, 1201, 1202 C++ standard, 398, 420, 421, 424 library clauses, 6 lifetime, 66 limits implementation, 3 , 427 line splicing, 16 linear_congruential_engine generation algorithm, 899 modulus, 899 state, 899 1253
c ISO/IEC
textual representation, 899 transition algorithm, 899 linkage, 32, 56–58 const and, 56 external, 56, 409, 419 implementation-defined object, 167 inline and, 56 internal, 56 no, 56, 57 static and, 56 linkage specification, see specification, linkage linkage-specification, 165, 1174 literal, 23–31, 85 base of integer, 24 boolean, 29 char16_t, 25 char32_t, 25 character, 25 constant, 23 decimal, 24 double, 27 float, 27 floating, 26, 27 hexadecimal, 24 char, 26 integer, 23, 24 long, 24 long double, 27 multicharacter, 25 implementation-defined value of, 25 narrow-character, 25 octal, 24 pointer, 29 string, 27, 28 char16_t, 28 char32_t, 28 implementation-defined, 28 narrow, 28 type of, 28 undefined change to, 28 wide, 28 type of character, 25 type of floating point, 27 type of integer, 24 unsigned, 24 user defined, 30 literal, 23, 1164 literal type, 70 literal-operator-id, 299, 1178 load_factor unordered associative containers, 728 Cross references
N3376
local lambda expression, 90 local variable, 39 local_iterator, 721 unordered associative containers, 721 locale, 1049, 1050, 1052, 1059 locale-specific behavior, see behavior, locale-specific local class friend, 238 member function in, 210 scope of, 217 local scope, see block scope local variable destruction of, 129, 130 logical-and-expression, 117, 1169 logical-or-expression, 117, 1170 lognormal_distribution probability density function, 922 long typedef and, 135 long-long-suffix, 24, 1164 long-suffix, 24, 1164 lookup argument-dependent, 46 class member, 54 class member, 49 elaborated type specifier, 54 member name, 222 name, 32, 42–56 namespace aliases and, 56 namespace member, 50 qualified name, 48–54 template name, 331 unqualified name, 43 using-directives and, 56 lookup_classname regular expression traits, 1096 lookup_classname regular expression traits, 1051 lookup_collatename regular expression traits, 1051 low-order bit, 6 lowercase, 406 lparen, 388, 1181 lvalue, 74, 1186 lvalue reference, 72, 177 macro argument substitution, 391 function-like, 390, 391 arguments, 391 masking, 422 1254
c ISO/IEC
name, 391 object-like, 390, 391 pragma operator, 397 predefined, 396 replacement, 390–395 replacement list, 390 rescanning and replacement, 393 scope of definition, 393 main(), 58 implementation-defined linkage of, 59 implementation-defined parameters to, 59 parameters to, 59 return from, 59, 61 match_results as sequence, 1077 matched, 1049 max random number distribution requirement, 894 uniform random number generator requirement, 890 max_bucket_count unordered associative containers, 727 max_load_factor unordered associative containers, 728 mean normal_distribution, 921 poisson_distribution, 916 mem-initializer, 255, 1178 mem-initializer-id, 255, 1178 mem-initializer-list, 255, 1178 member class static, 62 enumerator, 152 static, 212 template and static, 317 member access operator overloaded, 298 member function call undefined, 211 class, 210 const, 212 constructor and, 244 destructor and, 250 friend, 237 inline, 210 local class, 218 nested class, 240 nonstatic, 211 overload resolution and, 277 static, 212, 213 this, 212 Cross references
N3376
union, 214 volatile, 212 member names, 39 member subobject, 7 member-declaration, 208, 1177 member-declarator, 208, 1177 member-declarator-list, 208, 1177 member-specification, 207, 1177 members, 39 member data static, 213 member pointer to, see pointer to member memory location, 6 memory model, 6–7 memory management, see also new, delete mersenne_twister_engine generation algorithm, 900 state, 900 textual representation, 901 transition algorithm, 900 message diagnostic, 2, 5 min random number distribution requirement, 894 uniform random number generator requirement, 890 modification order, 11 most derived class, 7 most derived object, 7 bit-field, 7 zero size subobject, 7 move class object, see constructor, move; assignment, move MoveInsertable into X, 707 multi-pass guarantee, 807 multibyte character, see character, multibyte multicharacter literal, see literal, multicharacter multiple threads, see threads, multiple multiple inheritance, 219, 220 virtual and, 228 multiplicative-expression, 113, 1169 mutable, 135 mutable iterator, 804 mutex types, 1124 name, 21, 32, 86 address of cv-qualified, 104 dependent, 337, 343 elaborated enum, 148 1255
c ISO/IEC
global, 40 length of, 21 macro, see macro, name point of declaration, 37 predefined macro, see macro, predefined qualified, 48 reserved, 419 scope of, 37 unqualified, 43 name hiding function, 276 overloading versus, 276 using-declaration and, 160 named-namespace-definition, 153, 1174 namespace, 407, 1202 alias, 156 definition, 152 global, 419 member definition, 154 unnamed, 154 namespace-alias, 156, 1174 namespace-alias-definition, 156, 1174 namespace-body, 153, 1174 namespace-definition, 153, 1174 namespace-name, 152, 1174 namespaces, 152–164 name class, see class name name hiding, 37, 42, 87, 130 class definition, 206 user-defined conversion and, 247 name space label, 124 narrowing conversion, 202 NDEBUG, 409 negative_binomial_distribution discrete probability function, 915 nested-name-specifier, 87, 1167 nested class local class, 218 scope of, 216 , 439 new, 63, 106, 107 array of class objects and, 108 constructor and, 108 default constructor and, 108 exception and, 109 initialization and, 108 operator, 420 scoping and, 106 storage allocation, 106 type of, 252 Cross references
N3376
unspecified constructor and, 108 unspecified order of evaluation, 108 new-declarator, 106, 1168 new-expression, 106, 1168 new-initializer, 106, 1169 new-line, 388, 1181 new-placement, 106, 1168 new-type-id, 106, 1168 new_handler, 64 no linkage, 56 noexcept-expression, 110, 1169 noexcept-specification, 382, 1180 non-directive, 388, 1180 non-throwing, 384 nondigit, 21, 1163 nonzero-digit, 23, 1164 noptr-abstract-declarator, 173, 1176 noptr-abstract-pack-declarator, 173, 1176 noptr-declarator, 172, 1175 noptr-new-declarator, 106, 1169 normal distributions, 921–926 normal_distribution mean, 921 probability density function, 921 standard deviation, 921 normative references, see references, normative notation syntax, 6 notify_all_at_thread_exit, 1137 NTBS, 406, 1036, 1210, 1211 static, 406 NTCTS, 401 NTMBS, 406 static, 406 number hex, 26 octal, 26 numeric_limits, 427 numeric_limits, 72 object, see also object model, 7, 32 byte copying and, 69 complete, 7 definition, 34 delete, 110 destructor static, 61 destructor and placement of, 251 linkage specification, 167 local static, 62 undefined deleted, 64 unnamed, 244 1256
c ISO/IEC
object expression, 96 object model, 7 object pointer type, 73 object representation, 69 object type, 7, 70 object, exception, see exception handling, exception object object-like macro, see macro, object-like object class, see also class object object lifetime, 66–69 object temporary, see temporary object type, 70 observable behavior, see behavior, observable octal-digit, 23, 1164 octal-escape-sequence, 25, 1165 octal-literal, 23, 1164 odr-used, 34 one-definition rule, 34–36 opaque-enum-declaration, 150, 1173 operation atomic, 11–14 operator, 22–23, 296 *=, 119 +=, 105, 119 -=, 119 /=, 119 =, 119 %=, 119 &=, 119 ˆ=, 119 |=, 119 additive, 113 address-of, 104 assignment, 119, 406 bitwise, 116 bitwise AND, 116 bitwise exclusive OR, 117 bitwise inclusive OR, 117 cast, 104, 173 class member access, 96 comma, 120 conditional expression, 117 copy assignment, see assignment, copy decrement, 97, 104, 105 division, 113 equality, 116 function call, 93, 296 greater than, 115 greater than or equal to, 115 increment, 97, 104, 105 Cross references
N3376
indirection, 104 inequality, 116 less than, 115 less than or equal to, 115 logical AND, 117 logical negation, 104, 105 logical OR, 117 move assignment, see assignment, move multiplication, 113 multiplicative, 113 one’s complement, 104, 105 overloaded, 83, 296 pointer to member, 112 pragma, see macro, pragma operator precedence of, 9 relational, 114 remainder, 113 scope resolution, 87, 107, 210, 219, 229 side effects and comma, 120 side effects and logical AND, 117 side effects and logical OR, 117 sizeof, 104, 105 subscripting, 93, 296 unary, 104 unary minus, 104, 105 unary plus, 104, 105 operator, 296, 1178 operator delete, see also delete, 107, 110, 252 operator new, see also new, 107 operator overloading, see overloading, operator operator!= random number distribution requirement, 895 random number engine requirement, 891 operator() random number distribution requirement, 894 random number engine requirement, 891 uniform random number generator requirement, 890 operator-function-id, 296, 1178 operator> random number distribution requirement, 895 random number engine requirement, 892 operator , see delete operator left shift, see left shift operator operator right shift, see right shift operator 1257
c ISO/IEC
operator use scope resolution, 213 optimization of temporary, see elimination of temporary order of evaluation in expression, see expression, order of evaluation of ordering function template partial, 329 order of execution base class constructor, 244 base class destructor, 250 constructor and static objects, 255 constructor and array, 253 destructor, 250 destructor and array, 250 member constructor, 244 member destructor, 250 original-namespace-definition, 153, 1174 original-namespace-name, 153, 1174 over-aligned type, 76 overflow, 83 undefined, 83 overloaded function, see overloading overloaded operator, see overloading, operator overloadedfunction address of, 294 overloaded function address of, 105 overloaded operator inheritance of, 296 overloading, 181, 206, 273–302, 327 access control and, 276 address of overloaded function, 294 argument lists, 277–284 assignment operator, 297 binary operator, 297 built-in operators and, 299 candidate functions, 277–284 declaration matching, 275 declarations, 273 example of, 273 function call operator, 297 member access operator, 298 operator, 296–299 prohibited, 273 resolution, 276–294 best viable function, 284–296 contexts, 277 function call syntax, 278–280 function template, 374 implicit conversions and, 286–294 Cross references
N3376
initialization, 282–284 operators, 280 scoping ambiguity, 223 template, 329 template name, 331 viable functions, 284–296 subscripting operator, 297 unary operator, 296 user-defined literal, 299 using directive and, 164 using-declaration and, 161 overloads floating point, 887 overrider final, 225 own, 513 pair tuple interface to, 476 param random number distribution requirement, 894 seed sequence requirement, 889 param_type random number distribution requirement, 894 parameter, 3 catch clause, 3 function, 3 function-like macro, 3 reference, 177 scope of, 39 template, 3, 33 void, 181 parameter declaration, 33 parameter-declaration, 181, 1176 parameter-declaration-clause, 181, 1176 parameter-declaration-list, 181, 1176 parameterized type, see template parameters macro, 391 parameters-and-qualifiers, 172, 1175 parameter list variable, 94, 181 period, 406 phases of translation, see translation, phases piecewise construction, 478 piecewise_constant_distribution interval boundaries, 928 probability density function, 928 weights, 928 piecewise_linear_distribution interval boundaries, 930 1258
c ISO/IEC
probability density function, 930 weights at boundaries, 930 placement syntax new, 108 pm-expression, 112, 1169 POD class, 205 POD struct, 205 POD union, 205 POF, 454 point of declaration, 37 pointer, see also void* safely-derived, 65 to traceable object, 424 to traceable object, 65 zero, 80 pointer literal, see literal, pointer pointer, integer representation of safely-derived, 65 pointer-literal, 29, 1166 pointer to member, 73, 112 Poisson distributions, 916–921 poisson_distribution discrete probability function, 916 mean, 916 POSIX, 1 extended regular expressions, 1059 regular expressions, 1059 postfix-expression, 93, 1168 postfix ++ and -overloading, 298 postfix ++, 97 postfix --, 97 potential results, 34 potential scope, 37 potentially evaluated, 34 pp-number, 21, 1163 pp-tokens, 388, 1181 precedence of operator, see operator, precedence of prefix L, 25, 28 prefix ++ and -overloading, 298 prefix ++, 105 prefix --, 105 preprocessing directive, 387 conditional inclusion, 388 preprocessing directives, 387–397 error, 395 header inclusion, 389 line control, 395 Cross references
N3376
macro replacement, see macro, replacement null, 396 pragma, 396 source-file inclusion, 389 preprocessing-file, 387, 1180 preprocessing-op-or-punc, 23, 1163 preprocessing-token, 19, 1162 primary equivalence class, 1050 primary-expression, 85, 1166 private, see access control, private probability density function cauchy_distribution, 923 chi_squared_distribution, 923 exponential_distribution, 917 extreme_value_distribution, 920 fisher_f_distribution, 924 gamma_distribution, 918 lognormal_distribution, 922 normal_distribution, 921 piecewise_constant_distribution, 928 piecewise_linear_distribution, 930 student_t_distribution, 925 uniform_real_distribution, 912 weibull_distribution, 919 program, 56 ill-formed, 3 start, 58–61 termination, 61–62 well-formed, 5, 8 program execution, 8–11 abstract machine, 8 as-if rule, see as-if rule promotion bool to int, 80 floating point, 80 integral, 79 protected, see access control, protected protection, see access control, 424 prvalue, 75 pseudo-destructor-name, 96 pseudo-destructor-name, 93, 1168 ptr-abstract-declarator, 173, 1176 ptr-declarator, 172, 1175 ptr-operator, 173, 1175 ptrdiff_t, 114 implementation defined type of, 114 public, see access control, public punctuator, 22–23 pure-specifier, 208, 1177 q-char, 21, 1163 1259
c ISO/IEC
q-char-sequence, 21, 1163 qualification explicit, 48 qualified-id, 87, 1167 qualified-namespace-specifier, 156, 1174 r-char, 27, 1166 r-char-sequence, 27, 1165 random number distribution bernoulli_distribution, 913 binomial_distribution, 914 chi_squared_distribution, 923 discrete_distribution, 926 exponential_distribution, 917 extreme_value_distribution, 920 fisher_f_distribution, 924 gamma_distribution, 918 geometric_distribution, 915 lognormal_distribution, 922 negative_binomial_distribution, 915 normal_distribution, 921 piecewise_constant_distribution, 928 piecewise_linear_distribution, 930 poisson_distribution, 916 requirements, 893–896 student_t_distribution, 925 uniform_int_distribution, 911 uniform_real_distribution, 912 random number distributions Bernoulli, 913–916 normal, 921–926 Poisson, 916–921 sampling, 926–931 uniform, 911–913 random number engine linear_congruential_engine, 899 mersenne_twister_engine, 900 requirements, 890–892 subtract_with_carry_engine, 901 with predefined parameters, 906–907 random number engine adaptor discard_block_engine, 903 independent_bits_engine, 904 shuffle_order_engine, 905 with predefined parameters, 906–907 random number generation, 887–931 distributions, 911–931 engines, 898–906 predefined engines and adaptors, 906–907 requirements, 888–896 synopsis, 896–898 Cross references
N3376
utilities, 908–911 random number generator, see uniform random number generator random_device implementation leeway, 907 raw string literal, 28 raw-string, 27, 1165 reaching scope, 90 ready, 1077, 1148 redefinition typedef, 138 ref-qualifier, 173, 1175 reference, 72 assignment to, 119 call by, 94 lvalue, 72 null, 178 rvalue, 72 sizeof, 105 reference collapsing, 178 reference-compatible, 197 reference-related, 197 references normative, 1 regex_iterator end-of-sequence, 1089 regex_token_iterator end-of-sequence, 1091 regex_traits specializations, 1063 region declarative, 32, 37 register, 135 regular expression, 1049–1096 grammar, 1094 matched, 1049 requirements, 1050 regular expression traits, 1094 char_class_type, 1050 isctype, 1051 lookup_classname, 1096 lookup_classname, 1051 lookup_collatename, 1051 requirements, 1050, 1063 transform, 1095 transform, 1051 transform_primary, 1096 transform_primary, 1051 translate, 1095 translate, 1050 translate_nocase, 1095 1260
c ISO/IEC
translate_nocase, 1051 rehash unordered associative containers, 728 reinterpret_cast, see cast, reinterpret relational-expression, 115, 1169 relaxed pointer safety, 65 release sequence, 12 remainder operator, see remainder operator replacement macro, see macro, replacement replacement-list, 388, 1181 representation object, 69 value, 69 requirements, 402 Allocator, 413 container, 702, 720, 731, 733, 1077 not required for unordered associated containers, 719 CopyAssignable, 410 CopyConstructible, 410 DefaultConstructible, 410 Destructible, 410 EqualityComparable, 410 Hash, 413 iterator, 804 LessThanComparable, 410 MoveAssignable, 410 MoveConstructible, 410 NullablePointer, 413 numeric type, 875 random number distribution, 893–896 random number engine, 890–892 regular expression traits, 1050, 1063 seed sequence, 888–889 sequence, 1077 uniform random number generator, 889–890 unordered associative container, 720 reraise, see exception handling, rethrow rescanning and replacement, see macro, rescanning and replacement reserved identifier, 22 reset, 513 reset random number distribution requirement, 894 resolution, see overloading, resolution restriction, 421, 422, 424 address of bit-field, 216 anonymous union, 215 bit-field, 216 constructor, 243, 244 Cross references
N3376
destructor, 249 extern, 136 local class, 218 operator overloading, 296 overloading, 296 pointer to bit-field, 216 reference, 178 register, 135 static, 136 static member local class, 214 union, 214 result_type entity characterization based on, 887 result_type random number distribution requirement, 894 seed sequence requirement, 889 uniform random number generator requirement, 890 rethrow, see exception handling, rethrow return, 129, 130 and handler, 377 and try block, 377 constructor and, 130 reference and, 196 return statement, see return return type, 182 overloading and, 273 right shift implementation defined, 114 right shift operator, 114 rounding, 80 rvalue, 74 lvalue conversion to, see conversion, lvalue to rvalue lvalue conversion to, 1186 rvalue reference, 72, 177 s-char, 27, 1165 s-char-sequence, 27, 1165 safely-derived pointer, 65 integer representation, 65 sampling distributions, 926–931 scalar type, 70 scope, 1, 32, 37–42, 134 anonymous union at namespace, 215 block, 39 class, 40 declarations and, 37–39 destructor and exit from, 129 enumeration, 41 exception declaration, 39 1261
c ISO/IEC
function, 39 function prototype, 39 global, 40 global namespace, 40 iteration-statement, 127 macro definition, see macro, scope of definition namespace, 39 name lookup and, 42–56 overloading and, 275 potential, 37 selection-statement, 125 template parameter, 41 scope name hiding and, 42 scope resolution operator, 49 seed random number engine requirement, 891 seed sequence, 888 requirements, 888–889 selection-statement, 125, 1170 semantics class member, 96 separate compilation, see compilation, separate separate translation, see compilation, separate sequence ambiguous conversion, 287 implicit conversion, 286 standard conversion, 77 sequence constructor seed sequence requirement, 889 Sequenced before, 10 sequencing operator, see comma operator setlocale, 406 shared state, see future, shared state shift-expression, 114, 1169 shift operator, see left shift operator, right shift operator short typedef and, 135 shuffle_order_engine generation algorithm, 905 state, 905 textual representation, 906 transition algorithm, 905 side effects, 8, 10–14, 117, 124, 245, 257, 267, 393, 424 visible, 13 visible sequence of, 13 sign, 27, 1165 signal, 8 signature, 3, 4 Cross references
N3376
signed typedef and, 135 signed integer type, 71 simple call wrapper, 544 simple-declaration, 133, 1171 simple-escape-sequence, 25, 1165 simple-template-id, 307, 1179 simple-type-specifier, 145, 1173 size seed sequence requirement, 889 size_t, 106 smart pointers, 523–539 source file, 16, 409, 420 source file character, see character, source file space white, 19 specialization class template, 308 class template partial, 323 template, 345 template explicit, 351 special member function, see constructor, destructor, inline function, user-defined conversion, virtual function specification linkage, 164–167 extern, 165 implementation-defined, 165 nesting, 165 template argument, 357 specifications C standard library exception, 424 C++, 424 implementation-defined exception, 424 specifier, 134–149 friend, 424 constexpr, 139 constructor, 140, 141 function, 140 cv-qualifier, 144 declaration, 134 explicit, 138 friend, 139 function, 137 inline, 137 missing storage class, 136 static, 135 storage class, 135 type, see type specifier typedef, 138 virtual, 137 1262
c ISO/IEC
specifier access, see access specifier stable algorithm, 401, 423 stack unwinding see exception handling, constructors and destructors, 380 standard structure of, 5–6 standard deviation normal_distribution, 921 standard-layout types, 70 standard-layout class, 205 standard-layout struct, 205 standard-layout union, 205 standard integer type, 71 standard signed integer type, 71 standard unsigned integer type, 71 start program, 59 startup program, 409, 420 state discard_block_engine, 903 independent_bits_engine, 904 linear_congruential_engine, 899 mersenne_twister_engine, 900 object, 400 shuffle_order_engine, 905 subtract_with_carry_engine, 901 statement, 124–132 continue in for, 128 break, 129 compound, 124 continue, 129 declaration, 130 declaration in if, 125 declaration in switch, 125 declaration in for, 128 declaration in switch, 126 declaration in while, 127 do, 126, 127 empty, 124 expression, 124 for, 126, 128 goto, 124, 129, 130 if, 125, 126 iteration, 126–129 jump, 129 labeled, 124 null, 124 for, 128 selection, 125–126 Cross references
N3376
switch, 125, 126, 129 while, 126, 127 statement, 124, 1170 statement-seq, 124, 1170 static, 135 destruction of local, 131 linkage of, 56, 136 overloading and, 273 static initialization, 59 static storage duration, 62 static type, see type, static static_assert, 134 static_assert-declaration, 133, 1171 static_cast, see cast, static <stddef.h>, 25, 28 <stdexcept>, 456 storage-class-specifier, 135, 1172 storage class, 32 storage duration, 62–66 automatic, 62, 63 class member, 66 dynamic, 62–65, 106 local object, 63 register, 63 static, 62 thread, 62 storage management, see new, delete stream arbitrary-positional, 399 repositional, 401 streambuf implementation-defined, 962 strict pointer safety, 65 string distinct, 28 null-terminated byte, 406 null-terminated character type, 401 null-terminated multibyte, 406 sizeof, 29 type of, 28 string literal, see literal, string string-literal, 27, 1165 stringize, see # struct standard-layout, 205 struct class versus, 204 structure, 204 structure tag, see class name student_t_distribution probability density function, 925 1263
c ISO/IEC
sub-expression, 1050 subobject, see also object model, 7 subscripting operator overloaded, 297 subsequence rule overloading, 292 subtract_with_carry_engine carry, 901 generation algorithm, 901 state, 901 textual representation, 902 transition algorithm, 901 subtraction implementation defined pointer, 114 subtraction operator, 113 suffix E, 27 e, 27 F, 27 f, 27 L, 24, 27 l, 24, 27 U, 24 u, 24 summary x C++ 2003, 1192 compatibility with ISO C, 1184 swappable, 412 swappable with, 411 switch and handler, 377 and try block, 377 synchronize with, 12 synonym, 156 type name as, 138 syntax class member, 96 target object, 543 template, 303–376 definition of, 303 function, 356 member function, 316 primary, 323 template, 303 template parameter, 33 template-argument, 307, 1179 template-argument-list, 307, 1179 template-declaration, 303, 1178 template-id, 307, 1179 template-name, 307, 1179 Cross references
N3376
template-parameter, 304, 1179 template-parameter-list, 303, 1179 template name linkage of, 303 template parameter scope, 41 temporary, 244 constructor for, 245 destruction of, 245 destructor for, 245 elimination of, 244, 267 implementation-defined generation of, 244 order of destruction of, 245 terminate(), 385, 386 called, 379, 380, 383, 385 termination program, 59, 62 terminology pointer, 73 text-line, 387, 1180 textual representation discard_block_engine, 904 independent_bits_engine, 905 shuffle_order_engine, 906 subtract_with_carry_engine, 902 this, 85, 212 type of, 212 this pointer, see this thread, 11 thread of execution, 11 thread storage duration, 62 thread, blocked, 399 thread_local, 135 threads multiple, 11–14 throw, 377 throw-expression, 377, 1179 throwing, see exception handling, throwing timed mutex types, 1127 token, 20 alternative, 20 preprocessing, 19 token, 20, 1163 traceable pointer object, 65, 424 trailing-return-type, 172, 1175 trailing-type-specifier, 143, 1172 trailing-type-specifier-seq, 143, 1172 traits, 401 transfer ownership, 513 transform regular expression traits, 1095 transform 1264
c ISO/IEC
regular expression traits, 1051 transform_primaryl regular expression traits, 1096 transform_primary regular expression traits, 1095 transform_primaryl regular expression traits, 1051 TransformationTrait, 559 transition algorithm discard_block_engine, 903 independent_bits_engine, 904 linear_congruential_engine, 899 mersenne_twister_engine, 900 shuffle_order_engine, 905 subtract_with_carry_engine, 901 translate regular expression traits, 1095 translate regular expression traits, 1050 translate_nocase regular expression traits, 1095 translate_nocase regular expression traits, 1051 translation phases, 16–17 separate, see compilation, separate translation unit, 16 translation units, 56 translation-unit, 56, 1166 translation unit, 56 name and, 32 trigraph sequence, 16, 18 trivial types, 70 trivially copyable class, 204 trivially copyable types, 70 trivial class, 204 trivial class type, 108 trivial type, 108 truncation, 80 try, 377 try block, see exception handling, try block try-block, 377, 1179 tuple and pair, 476 type, 32, 69–74 arithmetic, 72 array, 72, 181 bitmask, 405 Boolean, 71 char, 71 char16_t, 72 Cross references
N3376
char32_t, 72 character, 71 character container, 399 class and, 204 compound, 72 const, 143 destination, 192 double, 72 dynamic, 2 enumerated, 73, 404, 405 enumeration underlying, 151 example of incomplete, 70 extended integer, 71 extended signed integer, 71 extended unsigned integer, 71 float, 72 floating point, 71 function, 72, 180, 181 fundamental, 71 sizeof, 71 incomplete, 34, 35, 38, 69, 78, 93–97, 99, 104– 106, 110, 119, 219 int, 71 integral, 71 long, 71 long double, 72 long long, 71 multi-level mixed pointer and pointer to member, 79 multi-level pointer to member, 79 over-aligned, 76 POD, 70 pointer, 72 polymorphic, 225 short, 71 signed char, 71 signed integer, 71 standard integer, 71 standard signed integer, 71 standard unsigned integer, 71 static, 4 trivially copyable, 69 underlying wchar_t, 72 unsigned, 71 unsigned char, 71 unsigned int, 71 unsigned long, 71 unsigned long long, 71 unsigned short, 71 unsigned integer, 71 void, 72 1265
c ISO/IEC
volatile, 143 wchar_t, 72 type generator, see template type specifier auto, 148 const, 144 elaborated, 148 simple, 145 volatile, 144 type-id, 173, 1176 type-id-list, 382, 1180 type-name, 145, 1173 type-parameter, 304, 1179 type-specifier bool, 145 wchar_t, 145 type-specifier, 143, 1172 type-specifier-seq, 143, 1172 type_info, 99 typedef function, 182 typedef overloading and, 274 typedef-name, 138, 1172 typeid, 99 construction and, 261 destruction and, 261 , 445 typename, 148 typename-specifier, 332, 1179 types implementation-defined, 404 implementation-defined exception, 424 type checking argument, 94 type conversion, explicit, see casting type name, 173 nested, 218 scope of, 218 type pun, 102 type specifier auto, 145 char, 145 char16_t, 145 char32_t, 145 decltype, 145, 147 double, 145 elaborated, 54 enum, 148 float, 145 int, 145 Cross references
N3376
long, 145 short, 145 signed, 145 unsigned, 145 void, 145 volatile, 145 ud-suffix, 30, 1166 unary function, 544 unary operator overloaded, 296 unary-expression, 104, 1168 unary-operator, 104, 1168 UnaryTypeTrait, 559 unary operator interpretation of, 296 unblock, 401 uncaught_exception(), 386 undefined, 401, 419–421, 936, 938, 941–944, 948, 952, 976 undefined behavior, see behavior, undefined, 832 underlying type, 72 unevaluated operand, 84 unexpected(), 384, 386 called, 383 Unicode required set, 397 uniform distributions, 911–913 uniform random number generator requirements, 889–890 uniform_int_distribution discrete probability function, 911 uniform_real_distribution probability density function, 912 union standard-layout, 205 union, 73, 214 class versus, 204 anonymous, 215 global anonymous, 215 unique pointer, 513 unit translation, 409, 419 universal character name, 16 universal-character-name, 18, 1162 unnamed-namespace-definition, 153, 1174 unordered associative containers, 719–793 begin, 727 bucket, 727 bucket_count, 727 bucket_size, 727 cbegin, 727 1266
c ISO/IEC
cend, 727 clear, 726 complexity, 719 const_local_iterator, 721 count, 727 end, 727 equal_range, 727 equality function, 720 equivalent keys, 720, 784, 790 erase, 726 exception safety, 729 find, 726 hash function, 720 hash_function, 724 hasher, 721 insert, 725, 726 iterator invalidation, 729 iterators, 728 key_eq, 724 key_equal, 721 key_type, 720 lack of comparison operators, 719 load_factor, 728 local_iterator, 721 max_bucket_count, 727 max_load_factor, 728 rehash, 728 requirements, 719, 720, 729 unique keys, 720, 779, 787 unordered_map element access, 783 unique keys, 779 unordered_multimap equivalent keys, 784 unordered_multiset equivalent keys, 790 unordered_set unique keys, 787 unqualified-id, 85, 1167 unsequenced, 10 unsigned typedef and, 135 unsigned-suffix, 24, 1164 unsigned integer type, 71 unspecified, 440, 441, 445, 862, 1026, 1206, 1208 unspecified behavior, see behavior, unspecified, 942 unwinding stack, 380 uppercase, 406, 419 user-defined literal, see literal, user defined overloaded, 299 Cross references
N3376
user-defined-character-literal, 30, 1166 user-defined-floating-literal, 30, 1166 user-defined-integer-literal, 30, 1166 user-defined-literal, 30, 1166 user-defined-string-literal, 30, 1166 user-provided, 188 Uses-allocator construction, 505 using-declaration, 156–162 using-declaration, 156, 1174 using-directive, 162–164 using-directive, 162, 1174 usual arithmetic conversions, see conversion, usual arithmetic valid, 37 valid but unspecified state, 401 value, 69 call by, 94 null member pointer, 81 null pointer, 80 undefined unrepresentable integral, 80 value category, 75 value computation, 10–11, 13, 14, 97, 108, 117, 119, 120, 245 value representation, 69 value-initialization, 191 variable, 32 indeterminate uninitialized, 190 virt-specifier, 208, 1177 virt-specifier-seq, 208, 1177 virtual base class, 221 virtual function, 225–229 pure, 229, 230 virtual function call, 229 constructor and, 260 destructor and, 260 undefined pure, 230 visibility, 42 visible, 42 void* type, 73 void&, 177 volatile, 73 constructor and, 212, 243 destructor and, 212, 249 implementation-defined, 145 overloading and, 275 waiting function, 1147 wchar_t, 25, 28, 641 implementation-defined, 72 1267
c ISO/IEC
N3376
weak result type, 543 weibull_distribution probability density function, 919 weights discrete_distribution, 926 piecewise_constant_distribution, 928 weights at boundaries piecewise_linear_distribution, 930 well-formed program, see program, well-formed white space, 20 wide-character, 25 X(X&), see copy constructor xvalue, 74 zero division by undefined, 83 remainder undefined, 83 undefined division by, 113 zero-initialization, 190
Cross references
1268
c ISO/IEC
N3376
Index of grammar productions The first page number for each entry is the page in the general text where the grammar production is defined. The second page number is the corresponding page in the Grammar summary (Annex A). abstract-declarator, 173, 1176 abstract-pack-declarator, 173, 1176 access-specifier, 219, 1178 additive-expression, 113, 1169 alias-declaration, 133, 1171 alignment-specifier, 167, 1174 and-expression, 116, 1169 asm-definition, 164, 1174 assignment-expression, 119, 1170 assignment-operator, 119, 1170 attribute, 168, 1174 attribute-argument-clause, 168, 1175 attribute-declaration, 133, 1171 attribute-list, 168, 1174 attribute-namespace, 168, 1175 attribute-scoped-token, 168, 1175 attribute-specifier, 167, 1174 attribute-specifier-seq, 167, 1174 attribute-token, 168, 1175 balanced-token, 168, 1175 balanced-token-seq, 168, 1175 base-clause, 219, 1177 base-specifier, 219, 1178 base-specifier-list, 219, 1178 base-type-specifier, 219, 1178 block-declaration, 133, 1171 boolean-literal, 29, 1166 brace-or-equal-initializer, 190, 1176 braced-init-list, 190, 1177 c-char, 25, 1164 c-char-sequence, 25, 1164 capture, 88, 1167 capture-default, 88, 1167 capture-list, 88, 1167 cast-expression, 111, 1169 character-literal, 25, 1164 class-head, 204, 1177 class-head-name, 204, 1177 class-key, 204, 1177 class-name, 204, 1177 class-or-decltype, 219, 1178 Cross references
class-specifier, 204, 1177 class-virt-specifier, 204, 1177 compound-statement, 124, 1170 condition, 125, 1170 conditional-expression, 117, 1170 constant-expression, 120, 1170 control-line, 387, 1180 conversion-declarator, 248, 1178 conversion-function-id, 248, 1178 conversion-type-id, 248, 1178 ctor-initializer, 255, 1178 cv-qualifier, 173, 1175 cv-qualifier-seq, 173, 1175 d-char, 27, 1166 d-char-sequence, 27, 1166 decimal-literal, 23, 1164 decl-specifier, 134, 1172 decl-specifier-seq, 135, 1172 declaration, 133, 1171 declaration-seq, 133, 1171 declaration-statement, 130, 1171 declarator, 172, 1175 declarator-id, 173, 1176 decltype-specifier, 145, 1173 delete-expression, 109, 1169 digit, 21, 1163 digit-sequence, 27, 1165 dynamic-exception-specification, 382, 1180 elaborated-type-specifier, 148, 1173 elif-group, 387, 1180 elif-groups, 387, 1180 else-group, 387, 1180 empty-declaration, 133, 1171 encoding-prefix, 27, 1165 endif-line, 387, 1180 enum-base, 150, 1173 enum-head, 149, 1173 enum-key, 150, 1173 enum-name, 149, 1173 enum-specifier, 149, 1173 enumerator, 150, 1173 1269
c ISO/IEC
enumerator-definition, 150, 1173 enumerator-list, 150, 1173 equality-expression, 116, 1169 escape-sequence, 25, 1165 exception-declaration, 377, 1179 exception-specification, 382, 1180 exclusive-or-expression, 117, 1169 explicit-instantiation, 349, 1179 explicit-specialization, 351, 1179 exponent-part, 26, 1165 expression, 120, 1170 expression-list, 93, 1168 expression-statement, 124, 1170 extension-namespace-definition, 153, 1174 floating-literal, 26, 1165 floating-suffix, 27, 1165 for-init-statement, 126, 1171 for-range-declaration, 126, 1171 for-range-initializer, 126, 1171 fractional-constant, 26, 1165 function-definition, 187, 1176 function-specifier, 137, 1172 function-try-block, 377, 1179 group, 387, 1180 group-part, 387, 1180 h-char, 20, 1163 h-char-sequence, 20, 1163 handler, 377, 1179 handler-seq, 377, 1179 header-name, 20, 1163 hex-quad, 17, 1162 hexadecimal-digit, 23, 1164 hexadecimal-escape-sequence, 25, 1165 hexadecimal-literal, 23, 1164 id-expression, 85, 1166 identifier, 21, 1163 identifier-list, 388, 1181 identifier-nondigit, 21, 1163 if-group, 387, 1180 if-section, 387, 1180 inclusive-or-expression, 117, 1169 init-declarator, 172, 1175 init-declarator-list, 172, 1175 initializer, 190, 1176 initializer-clause, 190, 1176 initializer-list, 190, 1177 integer-literal, 23, 1164 Cross references
N3376
integer-suffix, 23, 1164 iteration-statement, 126, 1170 jump-statement, 129, 1171 labeled-statement, 124, 1170 lambda-capture, 88, 1167 lambda-declarator, 88, 1167 lambda-expression, 88, 1167 lambda-introducer, 88, 1167 linkage-specification, 165, 1174 literal, 23, 1164 literal-operator-id, 299, 1178 logical-and-expression, 117, 1169 logical-or-expression, 117, 1170 long-long-suffix, 24, 1164 long-suffix, 24, 1164 lparen, 388, 1181 mem-initializer, 255, 1178 mem-initializer-id, 255, 1178 mem-initializer-list, 255, 1178 member-declaration, 208, 1177 member-declarator, 208, 1177 member-declarator-list, 208, 1177 member-specification, 207, 1177 multiplicative-expression, 113, 1169 named-namespace-definition, 153, 1174 namespace-alias, 156, 1174 namespace-alias-definition, 156, 1174 namespace-body, 153, 1174 namespace-definition, 153, 1174 namespace-name, 152, 1174 nested-name-specifier, 87, 1167 new-declarator, 106, 1168 new-expression, 106, 1168 new-initializer, 106, 1169 new-line, 388, 1181 new-placement, 106, 1168 new-type-id, 106, 1168 noexcept-expression, 110, 1169 noexcept-specification, 382, 1180 non-directive, 388, 1180 nondigit, 21, 1163 nonzero-digit, 23, 1164 noptr-abstract-declarator, 173, 1176 noptr-abstract-pack-declarator, 173, 1176 noptr-declarator, 172, 1175 noptr-new-declarator, 106, 1169 octal-digit, 23, 1164 1270
c ISO/IEC
octal-escape-sequence, 25, 1165 octal-literal, 23, 1164 opaque-enum-declaration, 150, 1173 operator, 296, 1178 operator-function-id, 296, 1178 original-namespace-definition, 153, 1174 original-namespace-name, 153, 1174 parameter-declaration, 181, 1176 parameter-declaration-clause, 181, 1176 parameter-declaration-list, 181, 1176 parameters-and-qualifiers, 172, 1175 pm-expression, 112, 1169 pointer-literal, 29, 1166 postfix-expression, 93, 1168 pp-number, 21, 1163 pp-tokens, 388, 1181 preprocessing-file, 387, 1180 preprocessing-op-or-punc, 23, 1163 preprocessing-token, 19, 1162 primary-expression, 85, 1166 pseudo-destructor-name, 93, 1168 ptr-abstract-declarator, 173, 1176 ptr-declarator, 172, 1175 ptr-operator, 173, 1175 pure-specifier, 208, 1177 q-char, 21, 1163 q-char-sequence, 21, 1163 qualified-id, 87, 1167 qualified-namespace-specifier, 156, 1174 r-char, 27, 1166 r-char-sequence, 27, 1165 raw-string, 27, 1165 ref-qualifier, 173, 1175 relational-expression, 115, 1169 replacement-list, 388, 1181 s-char, 27, 1165 s-char-sequence, 27, 1165 selection-statement, 125, 1170 shift-expression, 114, 1169 sign, 27, 1165 simple-declaration, 133, 1171 simple-escape-sequence, 25, 1165 simple-template-id, 307, 1179 simple-type-specifier, 145, 1173 statement, 124, 1170 statement-seq, 124, 1170 static_assert-declaration, 133, 1171 Cross references
N3376
storage-class-specifier, 135, 1172 string-literal, 27, 1165 template-argument, 307, 1179 template-argument-list, 307, 1179 template-declaration, 303, 1178 template-id, 307, 1179 template-name, 307, 1179 template-parameter, 304, 1179 template-parameter-list, 303, 1179 text-line, 387, 1180 throw-expression, 377, 1179 token, 20, 1163 trailing-return-type, 172, 1175 trailing-type-specifier, 143, 1172 trailing-type-specifier-seq, 143, 1172 translation-unit, 56, 1166 try-block, 377, 1179 type-id, 173, 1176 type-id-list, 382, 1180 type-name, 145, 1173 type-parameter, 304, 1179 type-specifier, 143, 1172 type-specifier-seq, 143, 1172 typedef-name, 138, 1172 typename-specifier, 332, 1179 ud-suffix, 30, 1166 unary-expression, 104, 1168 unary-operator, 104, 1168 universal-character-name, 18, 1162 unnamed-namespace-definition, 153, 1174 unqualified-id, 85, 1167 unsigned-suffix, 24, 1164 user-defined-character-literal, 30, 1166 user-defined-floating-literal, 30, 1166 user-defined-integer-literal, 30, 1166 user-defined-literal, 30, 1166 user-defined-string-literal, 30, 1166 using-declaration, 156, 1174 using-directive, 162, 1174 virt-specifier, 208, 1177 virt-specifier-seq, 208, 1177
1271
c ISO/IEC
N3376
Index of library names <scoped_allocator>, 593 _Exit, 438 __alignas_is_defined, 454 __bool_true_false_are_defined, 453, 454 _1, 552 a cauchy_distribution, 924 extreme_value_distribution, 920 uniform_int_distribution, 912 uniform_real_distribution, 913 weibull_distribution, 920 abort, 62, 129, 408, 438, 444, 449 abs, 945, 957 complex, 884 accumulate, 954 acos, 945, 957 complex, 885 acosh, 957 complex, 885 address allocator, 508, 509 addressof, 511 adjacent_difference, 955 adjacent_find, 849 advance, 815 , 837 align, 504 all bitset, 496 all_of, 847 allocate allocator, 509 allocator_traits, 507 scoped_allocator_adaptor, 596 allocate_shared, 530 allocator, 1082 allocator, 508 address, 508, 509 allocate, 509 constructor, 509 deallocate, 509 destructor, 509 max_size, 509 operator!=, 509 Cross references
operator==, 509 allocator_arg, 504 allocator_arg_t, 504 allocator_traits, 505 allocate, 507 const_pointer, 506 const_void_pointer, 506 constructor, 507 deallocate, 507 destructor, 507 difference_type, 506 max_size, 507 pointer, 506 propagate_on_container_copy_assignment, 506 propagate_on_container_move_assignment, 507 propagate_on_container_swap, 507 rebind_alloc, 507 select_on_container_copy_construction, 507 size_type, 506 void_pointer, 506 alpha gamma_distribution, 919 always_noconv codecvt, 667 any bitset, 496 any_of, 847 append basic_string, 622, 623 apply valarray, 942 arg, 887 complex, 884 <array>, 729 array, 731, 733 begin, 731 data, 733 end, 731 fill, 733 get, 734 max_size, 731 size, 731, 733
1272
c ISO/IEC
swap, 733 asin, 945, 957 complex, 885 asinh, 957 complex, 885 , 409 assign deque, 737 list, 749 basic_regex, 1069 basic_string, 623, 624 deque, 737 error_code, 466 error_condition, 469 forward_list, 742 function, 557 list, 750 vector, 756 async, 1156 at basic_string, 621 map, 767 unordered_map, 783 at_quick_exit, 438, 439 atan, 945, 957 complex, 885 atan2, 945, 957 atanh, 957 complex, 885 atexit, 61, 408, 438 , 1097 atomic type atomic_compare_exchange_strong, 1109 atomic_compare_exchange_strong_explicit, 1109 atomic_compare_exchange_weak, 1109 atomic_compare_exchange_weak_explicit, 1109 atomic_exchange, 1109 atomic_exchange_explicit, 1109 atomic_fetch_, 1111 atomic_is_lock_free, 1108 atomic_load, 1109 atomic_load_explicit, 1109 atomic_store, 1108 atomic_store_explicit, 1108 compare_exchange_strong, 1109 compare_exchange_strong_explicit, 1109 compare_exchange_weak, 1109 compare_exchange_weak_explicit, 1109 constructor, 1107, 1108 Cross references
N3376
exchange, 1109 fetch_, 1111 load, 1109 operator @=, 1111 operator C , 1109 operator++, 1111 operator--, 1111, 1112 operator=, 1108 store, 1108 atomic_compare_exchange_strong atomic type, 1109 shared_ptr, 538 atomic_compare_exchange_strong_explicit atomic type, 1109 shared_ptr, 538 atomic_compare_exchange_weak atomic type, 1109 shared_ptr, 538 atomic_compare_exchange_weak_explicit atomic type, 1109 shared_ptr, 538 atomic_exchange atomic type, 1109 shared_ptr, 538 atomic_exchange_explicit atomic type, 1109 shared_ptr, 538 atomic_fetch_ atomic type, 1111 atomic_flag clear, 1113 atomic_flag_clear, 1113 atomic_flag_clear_explicit, 1113 atomic_flag_test_and_set, 1112 atomic_flag_test_and_set_explicit, 1112 atomic_is_lock_free atomic type, 1108 shared_ptr, 537 atomic_load atomic type, 1109 shared_ptr, 537 atomic_load_explicit atomic type, 1109 shared_ptr, 537 atomic_signal_fence, 1113 atomic_store atomic type, 1108 shared_ptr, 537 atomic_store_explicit atomic type, 1108 shared_ptr, 537 1273
c ISO/IEC
atomic_thread_fence, 1113 auto_ptr, 528, 1218 auto_ptr, 1219 auto_ptr_ref, 1220 constructor, 1219, 1220 destructor, 1220 operator=, 1219 auto_ptr_ref auto_ptr, 1220 operator auto_ptr, 1220 operator=, 1220 b cauchy_distribution, 924 extreme_value_distribution, 921 uniform_int_distribution, 912 uniform_real_distribution, 913 weibull_distribution, 920 back basic_string, 621 back_insert_iterator, 821 back_insert_iterator, 821 back_inserter, 822 bad basic_ios, 981 bad_alloc, 108, 440, 443, 444 bad_alloc, 444 bad_alloc::what implementation-defined, 444 bad_array_new_length, 444 bad_array_new_length, 444 bad_cast, 98, 445, 446 bad_cast, 446 bad_cast::what implementation-defined, 446 bad_exception, 449 bad_exception, 449 bad_exception::what implementation-defined, 449 bad_function_call, 553 bad_function_call, 553 bad_typeid, 99, 445, 447 bad_typeid, 447 bad_weak_ptr, 523 bad_weak_ptr, 524 what, 524 base move_iterator, 826 reverse_iterator, 818 basic_filebuf, 962, 1034 basic_filebuf, 1035 Cross references
N3376
constructor, 1035 destructor, 1036 operator=, 1036 swap, 1036 basic_filebuf, 1033 basic_filebuf<wchar_t>, 1033 basic_fstream, 962, 1045 basic_fstream, 1046 constructor, 1046 operator=, 1046 swap, 1046 basic_ifstream, 962, 1040 basic_ifstream, 1041 constructor, 1041 operator=, 1042 swap, 1042 basic_ifstream, 1033 basic_ifstream<wchar_t>, 1033 basic_ios, 962, 977 basic_ios, 978 constructor, 978 destructor, 978 exceptions, 982 fill, 979 init, 978 move, 980 rdbuf, 979 set_rdbuf, 980 swap, 980 tie, 979 basic_ios, 967 basic_ios<wchar_t>, 967 basic_iostream, 1008 basic_iostream, 1009 constructor, 1009 destructor, 1009 operator=, 1009 swap, 1009 basic_istream, 962, 996 basic_istream, 998 constructor, 998 destructor, 998, 1000 get, 1003, 1004, 1008 operator, 1022 basic_ofstream, 962, 1043 basic_ofstream, 1043 constructor, 1043, 1044 operator=, 1044 swap, 1044 basic_ofstream, 1033 basic_ofstream<wchar_t>, 1033 basic_ostream, 962, 1077 basic_ostream, 1011 constructor, 1012 destructor, 1011, 1012 operator, 1022 basic_regex, 1052, 1065, 1094 assign, 1069 basic_regex, 1067, 1068 constants, 1066, 1067 constructor, 1067, 1068 flag_type, 1070 getloc, 1070 imbue, 1070 mark_count, 1070 operator=, 1068 swap, 1070 basic_streambuf, 962, 986 basic_streambuf, 988 constructor, 988 destructor, 988 operator=, 990 setbuf, 1027 Cross references
N3376
swap, 990 basic_streambuf, 985 basic_streambuf<wchar_t>, 985 basic_string, 610, 611, 633, 1022 append, 622, 623 assign, 623, 624 at, 621 back, 621 begin, 619 capacity, 620 cbegin, 619 cend, 619 clear, 620 compare, 633 constructor, 615–617 copy, 628 crbegin, 619 crend, 619 empty, 620 end, 619 erase, 626 find, 629 find_first_not_of, 631, 632 find_first_of, 630 find_last_not_of, 632 find_last_of, 631 front, 621 get_allocator, 629 getline, 638, 639 insert, 624, 625 length, 619 max_size, 620 operator!=, 636 operator+, 633–635 operator+=, 621, 622 operator, 638 operator[], 621 pop_back, 626 push_back, 623 rbegin, 619 rend, 619 replace, 626–628 reserve, 620 resize, 620 1275
c ISO/IEC
rfind, 630 shrink_to_fit, 620 size, 619 substr, 632 swap, 629, 637 basic_stringbuf, 962, 1022 basic_stringbuf, 1024 constructor, 1024 operator=, 1024 str, 1025 swap, 1025 basic_stringbuf, 1022 basic_stringbuf<wchar_t>, 1022 basic_stringstream, 962, 1031 basic_stringstream, 1032 constructor, 1032 operator=, 1032 str, 1033 swap, 1032, 1033 before type_info, 446 before_begin forward_list, 742 begin, 452 array, 731 basic_string, 619 initializer_list, 453 match_results, 1081 valarray, 953 begin(C&), 836 begin(initializer_list<E>), 453 begin(T (&)[N]), 836 bernoulli_distribution, 913 constructor, 913 p, 914 beta gamma_distribution, 919 bidirectional_iterator_tag, 814 binary_function, 545, 1214 binary_negate, 550 binary_search, 864 bind, 551–552 bind1st, 1217 bind2nd, 1218 binder1st, 1217 binder2nd, 1217 binomial_distribution, 914 constructor, 914 p, 914 t, 914 bit_and, 549 Cross references
N3376
bit_or, 549 bit_xor, 549 , 490 bitset, 490 bitset, 492, 493 flip, 495 operator[], 496 reset, 494 set, 494 boolalpha, 982 byte_string wstring_convert, 655 c_str basic_string, 629 cacos complex, 885 cacosh complex, 885 call_once, 1135 calloc, 512, 1201 capacity basic_string, 620 vector, 757 casin complex, 885 casinh complex, 885 , 409 catan complex, 885 catanh complex, 885 category error_code, 467 error_condition, 469 locale, 648 cauchy_distribution, 923 a, 924 b, 924 constructor, 924 cbefore_begin forward_list, 742 cbegin basic_string, 619 cbrt, 957 , 887 cend basic_string, 619 cerr, 965 , 419 1276
c ISO/IEC
, 876 CHAR_BIT, 436 char_class_type regex_traits, 1063 CHAR_MAX, 436 char_traits, 603–606 char_type, 603 int_type, 603 off_type, 603 pos_type, 603 state_type, 603 char_type char_traits, 603 chi_squared_distribution, 923 constructor, 923 n, 923 chrono, 578 cin, 965 , 1201 classic locale, 653 classic_table ctype, 665 clear atomic_flag, 1113 basic_ios, 981 basic_string, 620 error_code, 467 error_condition, 469 forward_list, 744 , 1206 , 406, 1201 clock, 453, 454 clock_t, 454 CLOCKS_PER_SEC, 454 clog, 965 close basic_filebuf, 1037, 1047 basic_ifstream, 1042 basic_ofstream, 1045 messages, 695 code future_error, 1147 system_error, 471 codecvt, 665, 699 always_noconv, 667 do_always_noconv, 669 do_encoding, 668 do_in, 667 do_length, 669 do_max_length, 669 Cross references
N3376
do_out, 667 do_unshift, 668 encoding, 667 in, 667 length, 667 max_length, 667 out, 666 unshift, 667 codecvt_byname, 669 collate, 681 compare, 681 do_compare, 682 do_hash, 682 do_transform, 682 hash, 682 transform, 682 collate_byname, 682 combine locale, 652 common_type, 582, 586 compare basic_string, 633 collate, 681 sub_match, 1071 compare_exchange_strong atomic type, 1109 compare_exchange_strong_explicit atomic type, 1109 compare_exchange_weak atomic type, 1109 compare_exchange_weak_explicit atomic type, 1109 , 877 complex, 879 complex, 881 imag, 881 operator-, 883 operator/, 883 real, 881 , 1137 condition_variable constructor, 1138 destructor, 1138 notify_all, 1139 notify_one, 1138 wait, 1139 wait_for, 1140, 1141 wait_until, 1139, 1140 condition_variable_any constructor, 1142 destructor, 1142 1277
c ISO/IEC
notify_all, 1143 notify_one, 1143 wait, 1143 wait_for, 1144 wait_until, 1143, 1144 conj, 887 complex, 885 const_mem_fun1_ref_t, 1216 const_mem_fun1_t, 1216 const_mem_fun_ref_t, 1216 const_mem_fun_t, 1216 const_pointer allocator_traits, 506 const_pointer_cast shared_ptr, 532 const_void_pointer allocator_traits, 506 construct scoped_allocator_adaptor, 597, 598 converted wstring_convert, 655 copy, 852 basic_string, 628 copy_backward, 852 copy_n, 852 copyfmt basic_ios, 979 copysign, 957 cos, 945, 957 complex, 886 cosh, 945, 957 complex, 886 count, 849 bitset, 495 duration, 584 count_if, 849 cout, 965 crbegin basic_string, 619 cref reference_wrapper, 546 crend basic_string, 619 , 419, 453, 454 cshift valarray, 942 , 453, 454 , 454 , 419, 453, 454 , 453, 454 , 1201 Cross references
N3376
, 436 , 964–966, 1034, 1036, 1037, 1201 , 408, 453, 454, 1201, 1202 , 406, 1201, 1206, 1211 , 956 , 453, 454, 646, 1201 ctype, 659 do_is, 661 do_narrow, 662 do_scan_not, 661 do_tolower, 661 do_toupper, 661 do_widen, 661 is, 660 narrow, 660 scan_is, 660 scan_not, 660 tolower, 660 toupper, 660 widen, 660 ctype, 662 classic_table, 665 constructor, 664 ctype, 664 destructor, 663 do_narrow, 665 do_tolower, 665 do_toupper, 665 do_widen, 665 is, 664 narrow, 665 scan_is, 664 scan_not, 664 table, 665 tolower, 664 toupper, 664 widen, 664 ctype_base, 658 do_scan_is, 661 ctype_byname, 662 <cuchar>, 419 curr_symbol moneypunct, 693 current_exception, 450 , 419, 1201 data basic_string, 629 array, 733 vector, 758 date_order 1278
c ISO/IEC
time_get, 684 DBL_DIG, 436 DBL_EPSILON, 436 DBL_MANT_DIG, 436 DBL_MAX, 436 DBL_MAX_10_EXP, 436 DBL_MAX_EXP, 436 DBL_MIN, 436 DBL_MIN_10_EXP, 436 DBL_MIN_EXP, 436 deallocate allocator, 509 allocator_traits, 507 scoped_allocator_adaptor, 596 dec, 984, 1015 DECIMAL_DIG, 436 decimal_point moneypunct, 693 numpunct, 679 declare_no_pointers, 503 declare_reachable, 503 declval, 476 default_delete default_delete, 514 operator(), 514, 515 default_error_condition error_category, 464 error_code, 467 default_random_engine, 907 defaultfloat, 984 delete operator, 512 operator, 420, 441, 442 denorm_absent, 434 denorm_indeterminate, 434 denorm_min numeric_limits, 432 denorm_present, 434 densities piecewise_constant_distribution, 929 piecewise_linear_distribution, 931 <deque>, 730 deque, 734 assign, 737 deque, 736, 737 shrink_to_fit, 737 swap, 738 detach thread, 1122 difference_type allocator_traits, 506 Cross references
N3376
pointer_traits, 502 digits numeric_limits, 429 digits10 numeric_limits, 429 discard_block_engine, 903 constructor, 904 discrete_distribution, 926 constructor, 927 probabilities, 927 distance, 815 div, 957 divides, 546 do_always_noconv codecvt, 669 do_close message, 696 do_compare collate, 682 do_curr_symbol moneypunct, 694 do_date_order time_get, 685 do_decimal_point moneypunct, 693 numpunct, 680 do_encoding codecvt, 668 do_falsename numpunct, 680 do_frac_digits moneypunct, 694 do_get messages, 696 money_get, 689 num_get, 671, 674 time_get, 686 do_get_date time_get, 685 do_get_monthname time_get, 685 do_get_time time_get, 685 do_get_weekday time_get, 685 do_get_year time_get, 686 do_grouping moneypunct, 694 numpunct, 680 do_hash 1279
c ISO/IEC
collate, 682 do_in codecvt, 667 do_is ctype, 661 do_length codecvt, 669 do_max_length codecvt, 669 do_narrow, 665 ctype, 662 ctype, 665 do_neg_format moneypunct, 694 do_negative_sign moneypunct, 694 do_open messages, 695 do_out codecvt, 667 do_pos_format moneypunct, 694 do_positive_sign moneypunct, 694 do_put money_put, 691 num_put, 675, 678 time_put, 688 do_scan_is ctype_base, 661 do_scan_not ctype, 661 do_thousands_sep moneypunct, 693 numpunct, 680 do_tolower ctype, 661 ctype, 665 do_toupper ctype, 661 ctype, 665 do_transform collate, 682 do_truename numpunct, 680 do_unshift codecvt, 668 do_widen, 665 ctype, 661 ctype, 665 domain_error, 456, 457 Cross references
N3376
domain_error, 457 duration constructor, 583, 584 count, 584 max, 586 min, 586 operator!=, 587 operator*, 586 operator*=, 585 operator+, 584, 590 operator++, 584 operator+=, 585 operator-, 584, 590 operator-=, 585 operator--, 585 operator/, 586, 587 operator/=, 585 operator), 453 end(T (&)[N]), 836 endl, 1015, 1017 ends, 1017 entropy random_device, 908 eof basic_ios, 981 epptr basic_streambuf, 991 epsilon numeric_limits, 430 eq char_traits, 629–632 equal, 850 istreambuf_iterator, 834 equal_range, 864 equal_to, 547 equivalent error_category, 464, 465 erase deque, 738 list, 751 basic_string, 626 vector, 758 erase_after forward_list, 743 erased forward_list, 744 erf, 957 erfc, 957 errc, 460 error_category, 460, 463 default_error_condition, 464 equivalent, 464, 465 message, 464 name, 464 operator!=, 464 operator, 761 map, 763 constructor, 766 find, 767 insert, 767 map, 766 operator, 498 merge, 865 list, 752 forward_list, 745 mersenne_twister_engine, 900 constructor, 901 message do_close, 696 error_category, 464 error_code, 467 error_condition, 469 messages, 694 close, 695 do_get, 696 do_open, 695 get, 695 open, 695 messages_byname, 696 min, 870 duration, 586 duration_values, 582 numeric_limits, 429 time_point, 590 valarray, 942 1288
c ISO/IEC
min_element, 871 min_exponent numeric_limits, 430 min_exponent10 numeric_limits, 431 minmax, 870, 871 minmax_element, 871 minstd_rand, 906 minstd_rand0, 906 minus, 546 mismatch, 850 mod, 957 modf, 957 modulus, 547 money_get, 689 do_get, 689 get, 689 money_put, 690 do_put, 691 put, 691 moneypunct, 692 curr_symbol, 693 decimal_point, 693 do_curr_symbol, 694 do_decimal_point, 693 do_frac_digits, 694 do_grouping, 694 do_neg_format, 694 do_negative_sign, 694 do_pos_format, 694 do_positive_sign, 694 do_thousands_sep, 693 frac_digits, 693 grouping, 693 negative_sign, 693 positive_sign, 693 thousands_sep, 693 moneypunct_byname, 694 move, 475 basic_ios, 980 movemove, 853 move_backward, 853 move_if_noexcept, 476 move_iterator, 825 base, 826 constructor, 826 move_iterator, 826 operator!=, 828 operator*, 827 operator+, 827, 828 operator++, 827 Cross references
N3376
operator+=, 827 operator-, 827, 828 operator-=, 828 operator->, 827 operator--, 827 operator=, 828 operator[], 828 mt19937, 906 mt19937_64, 906 multimap, 768 find, 771 insert, 771 multimap, 770, 771 operator Cross references
N3376
auto_ptr, 1220 istream_iterator, 830 move_iterator, 827 regex_iterator, 1090 regex_token_iterator, 1093 reverse_iterator, 818 shared_ptr, 529 unique_ptr, 519 operator-atomic type, 1111, 1112 duration, 585 move_iterator, 827 reverse_iterator, 818 operator/ complex, 883 duration, 586, 587 valarray, 943 operator/= complex, 882 duration, 585 gslice_array, 950 indirect_array, 952 mask_array, 951 slice_array, 947 valarray, 941 operator< pair, 479 basic_string, 636 duration, 587 error_category, 464 error_code, 467 error_condition, 469 move_iterator, 828 queue, 796 reverse_iterator, 819 shared_ptr, 531 stack, 802 sub_match, 1072, 1074–1076 thread::id, 1120 time_point, 590 tuple, 489 type_index, 599 unique_ptr, 522, 523 valarray, 944 operator« shared_ptr, 533 sub_match, 1077 operator> basic_istream, 1001 Cross references
N3376
basic_string, 638 istream, 1000–1003 valarray, 943 operator>>= gslice_array, 950 indirect_array, 952 mask_array, 951 slice_array, 947 valarray, 941 operator[] basic_string, 621 bitset, 496 indirect_array, 952 map, 766, 767 mask_array, 951 match_results, 1080 move_iterator, 828 reverse_iterator, 819 unique_ptr, 521 unordered_map, 783 unordered_multimap, 787 valarray, 938–940 operator% duration, 587 valarray, 943 operator%= duration, 585 gslice_array, 950 indirect_array, 952 mask_array, 951 slice_array, 947 valarray, 941 operator& bitset, 497 valarray, 943 operator&= bitset, 493 gslice_array, 950 indirect_array, 952 mask_array, 951 slice_array, 947 valarray, 941 operator&& valarray, 943, 944 operatorˆ bitset, 497 valarray, 943 operatorˆ= bitset, 493 gslice_array, 950 indirect_array, 952 1294
c ISO/IEC
mask_array, 951 slice_array, 947 valarray, 941 operator˜ bitset, 494 valarray, 940 operators== locale, 652 operator| bitset, 497 valarray, 943 operator|= bitset, 493 gslice_array, 950 indirect_array, 952 mask_array, 951 slice_array, 947 valarray, 941 operator|| valarray, 943, 944 , 995 ostream, 962, 996 ostream_iterator, 831 constructor, 832 destructor, 832 operator*, 832 operator++, 832 operator=, 832 ostreambuf_iterator, 835 constructor, 835 ostringstream, 962, 1022 ostrstream, 1211 constructor, 1211 ostrstream, 1211 out codecvt, 666 out_of_range, 458, 492–496, 611 out_of_range, 458 out_of_range_error, 456 outer_allocator scoped_allocator_adaptor, 596 output_iterator_tag, 814 overflow basic_filebuf, 1038 basic_streambuf, 994 basic_stringbuf, 1026 strstreambuf, 1207 overflow_error, 456, 459, 460, 492, 495 overflow_error, 459 owner_before shared_ptr, 530, 535 Cross references
N3376
owns_lock unique_lock, 1134 p bernoulli_distribution, 914 binomial_distribution, 914 geometric_distribution, 915 negative_binomial_distribution, 916 packaged_task constructor, 1159 destructor, 1159 get_future, 1160 make_ready_at_thread_exit, 1160 operator(), 1160 operator=, 1159 reset, 1160 swap, 1159, 1161 valid, 1159 pair, 476, 484, 486 get, 480 operator=, 478 pair, 477, 478 swap, 478 param seed_seq, 910 partial_sort, 861 partial_sort_copy, 862 partial_sum, 955 partition, 859 partition_copy, 859 partition_point, 860 pbackfail basic_filebuf, 1038 basic_streambuf, 994 basic_stringbuf, 1025 strstreambuf, 1208 pbase basic_streambuf, 991 pbump basic_streambuf, 991 pcount ostrstream, 1212 strstream, 1213 strstreambuf, 1207 peek basic_istream, 1006 piecewise_constant_distribution, 928 constructor, 928, 929 densities, 929 intervals, 929 piecewise_construct, 480 1295
c ISO/IEC
piecewise_construct_t, 480 piecewise_linear_distribution, 930 constructor, 930, 931 densities, 931 intervals, 931 placeholders, 552 plus, 546 pointer allocator_traits, 506 pointer_to pointer_traits, 503 pointer_to_binary_function, 1214 pointer_to_unary_function, 1214 pointer_traits, 502 difference_type, 502 element_type, 502 pointer_to, 503 rebind, 502 poisson_distribution, 916 constructor, 917 mean, 917 polar complex, 885 pop priority_queue, 800 forward_list, 743 pop_back basic_string, 626 pop_heap, 868 pos_type char_traits, 603 position match_results, 1080 positive_sign moneypunct, 693 pow, 887, 945, 957 complex, 886 pptr basic_streambuf, 991 precision ios_base, 658, 973 prefix match_results, 1081 prev, 815 prev_permutation, 873 priority_queue, 797 emplace, 800 priority_queue, 798 swap, 800 probabilities discrete_distribution, 927 Cross references
N3376
proj complex, 885 promise constructor, 1149 destructor, 1149 get_future, 1149 operator=, 1149 set_exception, 1150 set_exception_at_thread_exit, 1150 set_value, 1150 set_value_at_thread_exit, 1150 swap, 1149, 1151 propagate_on_container_copy_assignment allocator_traits, 506 scoped_allocator_adaptor, 595 propagate_on_container_move_assignment allocator_traits, 507 scoped_allocator_adaptor, 595 propagate_on_container_swap allocator_traits, 507 scoped_allocator_adaptor, 595 proxy istreambuf_iterator, 833 ptr_fun, 1214 ptrdiff_t, 426 pubimbue basic_streambuf, 988 pubseekoff basic_streambuf, 989 pubseekpos basic_streambuf, 989 pubsetbuf basic_streambuf, 989 pubsync basic_streambuf, 989 push priority_queue, 799 push_back basic_string, 623 push_front forward_list, 742 push_heap, 868 put basic_ostream, 1017 money_put, 691 num_put, 675 time_put, 687 put_money, 1020 put_time, 1021 putback basic_istream, 1007 1296
c ISO/IEC
putenv, 453 pword ios_base, 975 , 794 queue, 794 swap, 797 quick_exit, 438, 439 quiet_NaN numeric_limits, 432 radix numeric_limits, 430 raise, 454 , 896–898 random_access_iterator_tag, 814 random_device, 907 constructor, 908 entropy, 908 operator(), 908 random_shuffle, 858 range_error, 456, 459 range_error, 459 ranlux24, 907 ranlux24_base, 906 ranlux48, 907 ranlux48_base, 906 ratio, 575 ratio_equal, 577 ratio_greater, 577 ratio_greater_equal, 577 ratio_less, 577 ratio_less_equal, 577 ratio_not_equal, 577 raw_storage_iterator constructor, 510 operator*, 510 operator++, 510 operator=, 510 rbegin basic_string, 619 rdbuf basic_filebuf, 1047 basic_ifstream, 1042 basic_ios, 979 basic_istringstream, 1029 basic_ofstream, 1044 basic_ostringstream, 1031 basic_stringstream, 1033 istrstream, 1211 ostrstream, 1212 Cross references
N3376
strstream, 1213 wbuffer_convert, 658 rdstate basic_ios, 981 read basic_istream, 1006 readsome basic_istream, 1006 real, 887 complex, 881, 884 realloc, 512, 1201 rebind pointer_traits, 502 rebind_alloc allocator_traits, 507 ref reference_wrapper, 546 reference_wrapper, 544 cref, 546 get, 545 operator T&, 545 operator(), 545 operator=, 545 ref, 546 reference_wrapper, 545 , 1052 regex, 1052 regex_constants, 1058 error_type, 1061, 1062 match_flag_type, 1059 syntax_option_type, 1058 regex_error, 1062, 1065, 1095 constructor, 1062 regex_iterator, 1088 increment, 1090 operator!=, 1089 operator*, 1090 operator++, 1090 operator->, 1090 operator==, 1089 regex_iterator, 1089 regex_match, 1083, 1084 regex_replace, 1086, 1087 regex_search, 1085, 1086 regex_token_iterator, 1090 end-of-sequence, 1091 operator!=, 1093 operator*, 1093 operator++, 1093, 1094 operator->, 1093 operator==, 1091, 1093 1297
c ISO/IEC
regex_token_iterator, 1092 regex_traits, 1062 char_class_type, 1063 isctype, 1064 length, 1063 lookup_classname, 1063 lookup_collatename, 1063 transform, 1063 transform_primary, 1063 translate, 1063 translate_nocase, 1063 value, 1064 register_callback ios_base, 975 regular expression traits isctype, 1095 lookup_classname, 1095 lookup_collatename, 1095 transform_primary, 1095 rel_ops, 472 release auto_ptr, 1220 unique_lock, 1134 unique_ptr, 520 remainder, 957 remove, 855 list, 752 forward_list, 745 remove_copy, 856 remove_copy_if, 856 remove_if, 855 forward_list, 745 remquo, 957 rend basic_string, 619 rep system_clock, 591 replace, 854 basic_string, 626–628 replace_copy, 854 replace_copy_if, 854 replace_if, 854 reserve basic_string, 620 vector, 757 reset auto_ptr, 1220 bitset, 494 packaged_task, 1160 shared_ptr, 529 unique_ptr, 520, 521 Cross references
N3376
weak_ptr, 534 resetiosflags, 1018 resize deque, 737 list, 750 basic_string, 620 forward_list, 744 valarray, 942 vector, 757 rethrow_exception, 451 rethrow_if_nested nested_exception, 452 rethrow_nested nested_exception, 451 return_temporary_buffer, 510 reverse, 857 list, 753 forward_list, 746 reverse_copy, 857 reverse_iterator, 816 reverse_iterator, 817 base, 818 constructor, 817 operator++, 818 operator--, 818 rfind basic_string, 630 right, 983 rint, 957 rotate, 857 rotate_copy, 858 round, 957 round_error numeric_limits, 430 round_indeterminate, 434 round_style numeric_limits, 433 round_to_nearest, 434 round_toward_infinity, 434 round_toward_neg_infinity, 434 round_toward_zero, 434 runtime_error, 456, 458 runtime_error, 459 s lognormal_distribution, 922 sbumpc basic_streambuf, 989 scalbln, 957 scalbn, 957 scan_is 1298
c ISO/IEC
ctype, 660 ctype, 664 scan_not ctype, 660 ctype, 664 SCHAR_MAX, 436 SCHAR_MIN, 436 scientific, 984 scoped_allocator_adaptor allocate, 596 construct, 597, 598 constructor, 595, 596 deallocate, 596 destructor, 598 inner_allocator, 596 inner_allocator_type, 595 max_size, 596 operator!=, 598 operator==, 598 outer_allocator, 596 propagate_on_container_copy_assignment, 595 propagate_on_container_move_assignment, 595 propagate_on_container_swap, 595 select_on_container_copy_construction, 598 search, 851 search_n, 851 seed_seq constructor, 909 generate, 909 param, 910 size, 910 seekdir ios_base, 970 seekg basic_istream, 1007 seekoff basic_filebuf, 1039 basic_streambuf, 992 basic_stringbuf, 1026 strstreambuf, 1208 seekp basic_ostream, 1013 seekpos basic_filebuf, 1040 basic_streambuf, 992 basic_stringbuf, 1026 strstreambuf, 1209 select_on_container_copy_construction Cross references
N3376
allocator_traits, 507 scoped_allocator_adaptor, 598 sentry basic_istream, 999 basic_ostream, 1012 constructor, 999, 1012 <set>, 762 set, 772 bitset, 494 operator, 453 setlocale, 406 setp basic_streambuf, 991 setprecision, 1019 setstate 1299
c ISO/IEC
basic_ios, 981 setw, 1020 sgetc basic_streambuf, 989 sgetn basic_streambuf, 989 share future, 1152 shared_from_this enable_shared_from_this, 536 shared_future constructor, 1154 destructor, 1154 get, 1155 operator=, 1155 valid, 1155 wait, 1156 wait_for, 1156 wait_until, 1156 shared_ptr, 524, 536 atomic_compare_exchange_strong, 538 atomic_compare_exchange_strong_explicit, 538 atomic_compare_exchange_weak, 538 atomic_compare_exchange_weak_explicit, 538 atomic_exchange, 538 atomic_exchange_explicit, 538 atomic_is_lock_free, 537 atomic_load, 537 atomic_load_explicit, 537 atomic_store, 537 atomic_store_explicit, 537 const_pointer_cast, 532 constructor, 526–528 destructor, 528 dynamic_pointer_cast, 532 get, 529 get_deleter, 533 operator bool, 530 operator!=, 531 operator*, 529 operator->, 529 operator=, 531 owner_before, 530, 535 Cross references
N3376
reset, 529 shared_ptr, 526 static_pointer_cast, 532 swap, 529, 532 unique, 530 use_count, 530 shift valarray, 942 showbase, 982 showmanyc basic_filebuf, 1037 basic_streambuf, 992, 1037 showpoint, 982 showpos, 982 shrink_to_fit basic_string, 620 deque, 737 vector, 757 SHRT_MAX, 436 SHRT_MIN, 436 shuffle, 858 shuffle_order_engine, 905 constructor, 906 sig_atomic_t, 454 SIG_DFL, 454 SIG_ERR, 454 SIG_IGN, 454 SIGABRT, 454 SIGFPE, 454 SIGILL, 454 SIGINT, 454 signal, 454 <signal.h>, 453 signaling_NaN numeric_limits, 432 signbit, 959 SIGSEGV, 454 SIGTERM, 454 sin, 945, 957 complex, 886 sinh, 945, 957 complex, 886 size array, 731, 733 basic_string, 619 bitset, 495 gslice, 949 initializer_list, 453 match_results, 1080 seed_seq, 910 slice, 946 1300
c ISO/IEC
size_t, 106, 426 size_type allocator_traits, 506 skipws, 983 sleep_for this_thread, 1123 sleep_until this_thread, 1123 slice, 945 slice, 946 slice_array, 946 snextc basic_streambuf, 989 sort, 861 list, 753 forward_list, 746 sort_heap, 869 splice list, 751 list, 751, 752 splice_after forward_list, 744, 745 sputbackc basic_streambuf, 990 sputc basic_streambuf, 990 sputn basic_streambuf, 990 sqrt, 945, 957 complex, 886 <sstream>, 1022 <staarg.h>, 453 stable_partition, 859 stable_sort, 861 <stack>, 800 stack, 800 swap, 803 start gslice, 949 slice, 946 state fpos, 976 match_results, 1079 wbuffer_convert, 658 wstring_convert, 656 state_type char_traits, 603 wbuffer_convert, 658 wstring_convert, 656 static_pointer_cast shared_ptr, 532 Cross references
N3376
<stdalign.h>, 454 <stdarg.h>, 453 <stdbool.h>, 454 stddev normal_distribution, 922 <stdexcept>, 456 <stdlib.h>, 453, 1202 stod, 640 stof, 639, 640 stoi, 639, 640 stol, 639, 640 stold, 639, 640 stoll, 639, 640 store atomic type, 1108 stoul, 639, 640 stoull, 639, 640 str basic_istringstream, 1029 basic_ostringstream, 1031 basic_stringbuf, 1025 basic_stringstream, 1033 istrstream, 1211 match_results, 1080 ostrstream, 1212 strstream, 1213 strstreambuf, 1207 sub_match, 1071 strchr, 641 <streambuf>, 985 streambuf, 962, 985 streamoff, 967, 976, 1203 streamsize, 967 ios_base, 973 strftime, 688 stride gslice, 949 slice, 946 <string>, 607 stringbuf, 962, 1022 stringstream, 962 strlen, 1206, 1211 strpbrk, 641 strrchr, 641 strstr, 641 strstream, 1212 destructor, 1213 strstream, 1213 strstreambuf, 1204, 1206 strstreambuf, 1205 destructor, 1207 1301
c ISO/IEC
setg, 1207 student_t_distribution, 925 constructor, 926 mean, 926 sub_match, 1070 compare, 1071 constructor, 1071 length, 1071 operator basic_string, 1071 operator!=, 1072–1076 operator=, 1072–1077 str, 1071 substr basic_string, 632 subtract_with_carry_engine, 901 constructor, 902 suffix match_results, 1081 sum valarray, 942 sungetc basic_streambuf, 990 swap, 474, 490 pair, 479 array, 733 basic_filebuf, 1036 basic_fstream, 1046 basic_ifstream, 1042 basic_ios, 980 basic_iostream, 1009 basic_istream, 999 basic_istringstream, 1029 basic_ofstream, 1044 basic_ostream, 1012 basic_ostringstream, 1031 basic_regex, 1070 basic_streambuf, 990 basic_string, 629, 637 basic_stringbuf, 1025 basic_stringstream, 1032, 1033 deque, 738 forward_list, 746 function, 557, 558 list, 753 map, 768 match_results, 1082 Cross references
N3376
multimap, 771 multiset, 778 packaged_task, 1159, 1161 pair, 478 priority_queue, 800 promise, 1149, 1151 queue, 797 set, 774 shared_ptr, 529, 532 stack, 803 thread, 1121, 1122 tuple, 486 unique_lock, 1134 unique_ptr, 520 unordered_map, 783 unordered_multimap, 787 unordered_multiset, 793 unordered_set, 790 valarray, 941, 945 vector, 757, 758 vector, 761 weak_ptr, 534, 535 swap(unique_ptr&, unique_ptr&), 522 swap_ranges, 853 sync basic_filebuf, 1040 basic_istream, 1007 basic_streambuf, 992 sync_with_stdio ios_base, 974 syntax_option_type, 1058, 1059 awk, 1059 basic, 1059 collate, 1059, 1095 ECMAScript, 1059 egrep, 1059 extended, 1059 grep, 1059 icase, 1059 nosubs, 1059 optimize, 1059 syntax_option_type awk, 1059 basic, 1059 collate, 1059 ECMAScript, 1059 egrep, 1059 extended, 1059 grep, 1059 icase, 1059 nosubs, 1059 1302
c ISO/IEC
optimize, 1059 system, 453, 454 system_category, 463, 465 system_clock rep, 591 system_error, 460, 470 code, 471 system_error, 471 what, 471 t binomial_distribution, 914 negative_binomial_distribution, 916 table ctype, 665 tan, 945, 957 complex, 887 tanh, 945, 957 complex, 887 target function, 557 target_type function, 557 tellg basic_istream, 1007 tellp basic_ostream, 1013 terminate, 438, 439, 449, 450, 1221 terminate_handler, 420, 449 test bitset, 496 tgamma, 957 this_thread get_id, 1123 sleep_for, 1123 sleep_until, 1123 yield, 1123 thousands_sep moneypunct, 693 numpunct, 680 , 1118 thread constructor, 1120, 1121 destructor, 1121 detach, 1122 get_id, 1122 hardware_concurrency, 1122 join, 1121 joinable, 1121 operator=, 1121 swap, 1121, 1122 Cross references
N3376
thread::id constructor, 1119 operator!=, 1120 operator