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
§ 14.8.2.1
© ISO/IEC 2011 – All rights reserved
385
ISO/IEC 14882:2011(E)
— 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 }
— end example ] 2
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 =
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 ] 4
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.
§ 14.8.2.1
386
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
[ 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 ] 5
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 ]
6
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 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.1
© ISO/IEC 2011 – All rights reserved
387
ISO/IEC 14882:2011(E)
14.8.2.2 1
Deducing template arguments taking the address of a function template [temp.deduct.funcaddr]
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.
2
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.
3
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, — 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.
4
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.
5
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
These alternatives are considered only if type deduction would otherwise fail. If they yield more than one possible deduced A, the type deduction fails.
7
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.3
388
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
14.8.2.4
Deducing template arguments during partial ordering
[temp.deduct.partial]
1
Template argument deduction is done by comparing certain types associated with the two function templates being compared.
2
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.
3
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.143 — 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.
4
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.
5
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
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.
7
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();
// #1 // #2 // #3
// calls #1
143) 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
© ISO/IEC 2011 – All rights reserved
389
ISO/IEC 14882:2011(E)
f(1, 2, 3); f(1, 2);
// calls #2 // calls #3; non-variadic template #3 is more // specialized than the variadic templates #1 and #2
— end example ] 9
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
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.
11
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: template T f(int); // #1 template T f(U); // #2 void g() { f(1); // calls #1 }
— end example ] 12
[ 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
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
§ 14.8.2.5
390
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
a template for a template parameter) that will make P, after substitution of the deduced values (call it the deduced A), compatible with A. 2
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.
3
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
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.
5
The non-deduced contexts are: — The nested-name-specifier of a type that was specified using a qualified-id. — 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.
§ 14.8.2.5
© ISO/IEC 2011 – All rights reserved
391
ISO/IEC 14882:2011(E)
6
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 ]
7
[ 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); }
// OK: T is int and U is float // error: T could be char or int // error: U could be char or float
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); }
struct B { }; struct D : public B {}; B {}; void f(B&){}
// calls f(B&) // calls f(B&)
§ 14.8.2.5
392
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
— end example ] 8
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. 9
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
§ 14.8.2.5
© ISO/IEC 2011 – All rights reserved
393
ISO/IEC 14882:2011(E)
template struct A { }; template struct A; // selects #2
// #3
— end example ] 10
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 declaratorid 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
// #1 // #2
— end example ] 11
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
(*)(T)
where type is X and T is char[6]. — end example ] 12
Template arguments cannot be deduced from function arguments involving constructs other than the ones specified above.
13
A template type argument cannot be deduced from the type of a non-type template-argument. § 14.8.2.5
394
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
14
[ Example: template void f(double a[10][i]); int v[10][20]; f(v); // error: argument for template-parameter T cannot be deduced
— end example ] 15
[ 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, T t, typename B::Y y); A a; B b;
// T is not deduced here // 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
— end note ] § 14.8.2.5
© ISO/IEC 2011 – All rights reserved
395
ISO/IEC 14882:2011(E)
17
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.144 [ 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 }
— end example ] 18
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 }
— end example ] 19
A template type-parameter cannot be deduced from the type of a function default argument. [ Example: template void f(T = 5, T = 7); void g() { f(1); // OK: call f(1,7) f(); // error: cannot deduce T f(); // OK: call f(5,7) }
— end example ] 20
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: 144) 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
396
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
template struct A { }; template void f(A<X>) { } template struct B { }; A ab; f(ab); // calls f(A)
— end example ] 21
[ 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
Deducing template arguments from a function declaration
[temp.deduct.decl]
1
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.
2
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
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 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 § 14.8.3
© ISO/IEC 2011 – All rights reserved
397
ISO/IEC 14882:2011(E)
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.145 [ 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);
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. 3
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))
}
— end example ] 5
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: 145) 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
398
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
6
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
© ISO/IEC 2011 – All rights reserved
399
ISO/IEC 14882:2011(E)
15 1
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
The optional attribute-specifier-seq in an exception-declaration appertains to the formal parameter of the catch clause (15.3). 2
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 ]
3
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:
400
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
lab: try { T1 t1; try { T2 t2; if (condition) goto lab; } catch(...) { /∗ handler 2 ∗/ } } catch(...) { /∗ handler 1 ∗/ }
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 ] 4
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
§ 15.1
© ISO/IEC 2011 – All rights reserved
401
ISO/IEC 14882:2011(E)
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 try { f(1.2); } catch(Overflow& oo) { // handle exceptions of type Overflow here }
— end example ] 2
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.
3
A throw-expression initializes 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.
4
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 ]
5
When the thrown object is a class object, the copy/move constructor and the destructor shall be accessible, even if the copy/move operation is elided (12.8).
6
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 ]
7
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; }
§ 15.1
402
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
}; int main() { try { throw C(); } catch(C) { } }
// calls std::terminate()
— end example ] 8
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: try { // ... } catch (...) { // catch all exceptions // respond (partially) to exception throw; // pass the exception to some // other handler }
— end example ] 9
If no exception is presently being handled, executing a throw-expression with no operand calls std:: terminate() (15.5.1).
15.2
Constructors and destructors
[except.ctor]
1
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.
2
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.
3
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
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*.
§ 15.3
© ISO/IEC 2011 – All rights reserved
403
ISO/IEC 14882:2011(E)
2
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.
3
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 cv1 T* cv2 and E is a pointer type that can be converted to the type of the handler 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 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: class class class class
Matherr { /∗ ... ∗/ virtual void vf(); }; Overflow: public Matherr { /∗ ... ∗/ }; Underflow: public Matherr { /∗ ... ∗/ }; Zerodivide: public Matherr { /∗ ... ∗/ };
void f() { try { g(); } catch (Overflow oo) { // ... } catch (Matherr mm) { // ... } }
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 ] 4
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.
5
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.
6
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.
7
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. § 15.3
404
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
8
The exception with the most recently activated handler that is still active is called the currently handled exception.
9
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).
10
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.
11
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).
12
The scope and lifetime of the parameters of a function or constructor extend into the handlers of a functiontry-block.
13
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.
14
If a return statement appears in a handler of the function-try-block of a constructor, the program is ill-formed.
15
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 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).
16
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.
17
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
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
§ 15.4
© ISO/IEC 2011 – All rights reserved
405
ISO/IEC 14882:2011(E)
noexcept-specification: noexcept ( constant-expression ) noexcept
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). 2
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);
OK OK OK ill-formed
— end example ] A type denoted in an exception-specification shall not denote an incomplete type. A type denoted in an exception-specification shall not denote a pointer or reference to an incomplete type, other than void*, const void*, volatile void*, or const volatile void*. 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. 3
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 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.
5
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 § 15.4
406
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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; }
// OK: pf1 is less restrictive // error: pf2 is more restrictive
— end example ] 6
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.
7
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 ]
8
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.
9
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 class class class
X { }; Y { }; Z: public X { }; W { };
void f() throw (X, Y) { int n = 0; if (n) throw X(); if (n) throw Z(); throw W(); }
// 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 ] 10
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().
11
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: § 15.4
© ISO/IEC 2011 – All rights reserved
407
ISO/IEC 14882:2011(E)
extern void f() throw(X, Y); void g() throw(X) { f(); }
// OK
the call to f is well-formed even though when called, f might throw exception Y that g does not allow. — end example ] 12
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.
13
An exception-specification is not considered part of a function’s type.
14
An implicitly declared special member function (Clause 12) shall have an exception-specification. If f is 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 shall allow all exceptions if any function it directly invokes allows all exceptions, and f shall allow no exceptions if every function it directly invokes allows no exceptions. [ 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&) throw(); // Implicit declaration of D::D(D&&) throw(Y); // Implicit declaration of D::∼D() throw(X, Y); };
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 ] 15
A deallocation function (3.7.4.2) with no explicit exception-specification is treated as if it were specified with noexcept(true).
16
In a dynamic-exception-specification, a type-id followed by an ellipsis is a pack expansion (14.5.3).
17
[ Note: The use of dynamic-exception-specifications is deprecated (see Annex D). — end note ]
§ 15.4
408
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
15.5 1
[except.special]
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.
15.5.1 1
Special functions
The std::terminate() function
[except.terminate]
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 — 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 — 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). — end note ]
2
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.1
© ISO/IEC 2011 – All rights reserved
409
ISO/IEC 14882:2011(E)
15.5.2
The std::unexpected() function
[except.unexpected]
1
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.
2
[ 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 ]
3
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.
4
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::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
410
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
16 1
Preprocessing directives
[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.146 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 # ifdef # ifndef
constant-expression new-line groupopt identifier new-line groupopt 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
146) 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).
© ISO/IEC 2011 – All rights reserved
411
ISO/IEC 14882:2011(E)
control-line: # include # define # define # define # define # undef # line # error # pragma # new-line
pp-tokens new-line identifier replacement-list new-line identifier lparen identifier-listopt ) replacement-list new-line identifier lparen ... ) replacement-list new-line identifier lparen identifier-list, ... ) replacement-list new-line identifier new-line pp-tokens new-line pp-tokensopt new-line pp-tokensopt new-line
text-line: pp-tokensopt new-line 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 2
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.
3
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.
4
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).
5
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.
6
The preprocessing tokens within a preprocessing directive are not subject to macro expansion unless otherwise stated. [ Example: In: #define EMPTY EMPTY # include
412
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 below147 and it may contain unary operator expressions of the form defined identifier
or defined ( identifier )
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. 2
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).
3
Preprocessing directives of the forms # if # elif
constant-expression new-line groupopt constant-expression new-line groupopt
check whether the controlling constant expression evaluates to nonzero. 4
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 keywords148 , 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).149 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.150 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. 147) 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. 148) 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. 149) 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). 150) 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)
§ 16.1
© ISO/IEC 2011 – All rights reserved
413
ISO/IEC 14882:2011(E)
5
Preprocessing directives of the forms # ifdef # ifndef
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. 6
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.151
16.2
Source file inclusion
[cpp.include]
1
A #include directive shall identify a header or source file that can be processed by the implementation.
2
A preprocessing directive of the form # include < h-char-sequence> new-line
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. 3
A preprocessing directive of the form # 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 # include < h-char-sequence> new-line
with the identical contained sequence (including > characters, if any) from the original directive. 4
A preprocessing directive of the form # include pp-tokens new-line
(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.152 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. 5
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. 151) 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. 152) 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.2
414
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
6
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.
7
[ 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
<stdio.h> "usefullib.h" "myprog.h"
— end note ] 8
[ 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
Macro replacement
[cpp.replace]
1
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.
2
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.
3
There shall be white-space between the identifier and the replacement list in the definition of an object-like macro.
4
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 than there are parameters in the macro definition (excluding the ...). There shall exist a ) preprocessing token that terminates the invocation.
5
The identifier _ _ VA_ARGS _ _ shall occur only in the replacement-list of a function-like macro that uses the ellipsis notation in the parameters.
6
A parameter identifier in a function-like macro shall be uniquely declared within its scope.
7
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.
§ 16.3
© ISO/IEC 2011 – All rights reserved
415
ISO/IEC 14882:2011(E)
8
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.
9
A preprocessing directive of the form # define identifier replacement-list new-line
defines an object-like macro that causes each subsequent instance of the macro name153 to be replaced by the replacement list of preprocessing tokens that constitute the remainder of the directive.154 The replacement list is then rescanned for more macro names as specified below. 10
A preprocessing directive of the form # 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
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. 11
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,155 the behavior is undefined.
12
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. 153) 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. 154) 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. 155) Despite the name, a non-directive is a preprocessing directive.
§ 16.3.1
416
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
The # operator
[cpp.stringize]
1
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.
2
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
The ## operator
[cpp.concat]
1
A ## preprocessing token shall not occur at the beginning or at the end of a replacement list for either form of macro definition.
2
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.156
3
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) 156) Placemarker preprocessing tokens do not appear in the syntax because they are temporary entities that exist only within translation phase 4.
§ 16.3.3
© ISO/IEC 2011 – All rights reserved
417
ISO/IEC 14882:2011(E)
mkstr(x ## y) "x ## y"
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
Rescanning and further replacement
[cpp.rescan]
1
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.
2
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.
3
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
Scope of macro definitions
[cpp.scope]
1
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.
2
A preprocessing directive of the form # undef identifier new-line
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. 3
[ Note: The simplest use of this facility is to define a “manifest constant,” as in #define TABSIZE 100 int table[TABSIZE];
— end note ] 4
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))
The parentheses ensure that the arguments and the resulting expression are bound properly. 5
To illustrate the rules for redefinition and reexamination, the sequence #define x #define f(a) #undef x
3 f(x * (a))
§ 16.3.5
418
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
#define #define #define #define #define #define #define #define #define #define #define
x g z h m(a) w t(a) p() q(x) r(x,y) str(x)
2 f z[0] g(∼ a(w) 0,1 a int x x ## y # x
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)
§ 16.3.5
© ISO/IEC 2011 – All rights reserved
419
ISO/IEC 14882:2011(E)
"hello"; "hello, world"
Space around the # and ## tokens in the macro definition is optional. 7
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, }; 8
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
Line control
[cpp.line]
1
The string literal of a #line directive, if present, shall be a character string literal.
2
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. § 16.4
420
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
3
A preprocessing directive of the form # line digit-sequence new-line
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. 4
A preprocessing directive of the form # line digit-sequence " s-char-sequenceopt " new-line
sets the presumed line number similarly and changes the presumed name of the source file to be the contents of the character string literal. 5
A preprocessing directive of the form # 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 # 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.157 157) 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.
§ 16.8
© ISO/IEC 2011 – All rights reserved
421
ISO/IEC 14882:2011(E)
_ _ 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).158 _ _ LINE _ _ The presumed line number (within the current source file) of the current source line (an integer constant).158 _ _ 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. _ _ 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
The values of the predefined macros (except for _ _ FILE _ _ and _ _ LINE _ _) remain constant throughout the translation unit.
4
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. 158) The presumed source file name and line number can be changed by the #line directive.
§ 16.8
422
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
© ISO/IEC 2011 – All rights reserved
423
ISO/IEC 14882:2011(E)
17 17.1
Library introduction General
[library] [library.general]
1
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.
2
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.
3
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
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
4
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).
5
The diagnostics library (Clause 19) provides a consistent framework for reporting errors in a C++ program, including predefined exception classes.
6
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.
7
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.
8
The localization library (Clause 22) provides extended internationalization support for text processing.
9
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.
10
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, § 17.1
424
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
potentially implemented as parallel operations on platforms that support such processing. The random number component provides facilities for generating pseudo-random numbers. 11
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, locales, and iterators.
12
The regular expressions library (Clause 28) provides regular expression matching and searching.
13
The atomic operations library (Clause 29) allows more fine-grained concurrent access to shared data than is possible with locks.
14
The thread support library (Clause 30) provides components to create and manage threads, including mutual exclusion and interthread communication.
17.2
The C standard library
[library.c]
1
The C++ standard library also makes available the facilities of the C standard library, suitably adjusted to ensure static type safety.
2
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 execution159 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 character container type a class or a type used to represent a character
[defns.character.container]
159) This definition is taken from POSIX.
§ 17.3
© ISO/IEC 2011 – All rights reserved
425
ISO/IEC 14882:2011(E)
[ 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 [defns.component] component a group of library entities directly related as members, parameters, or return types [ 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
426
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 [defns.ntcts] 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
© ISO/IEC 2011 – All rights reserved
427
ISO/IEC 14882:2011(E)
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 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 17.5.1.1 1
[defns.additional]
1.3 defines additional terms used elsewhere in this International Standard.
17.5 1
Additional definitions
Structure of each clause Elements
[structure] [structure.elements]
Each library clause contains the following elements, as applicable:160 — Summary — Requirements — Detailed specifications — References to the Standard C library 17.5.1.2
1
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. 160) 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.2
428
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
2
Paragraphs labeled “Note(s):” or “Example(s):” are informative, other paragraphs are normative.
3
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
[structure.requirements]
Requirements describe constraints that shall be met by a C++ program that extends the standard library. Such extensions are generally one of the following: — Template arguments — Derived classes — Containers, iterators, and algorithms that meet an interface convention
2
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.
3
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.
4
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.
5
Template argument requirements are sometimes referenced by name. See 17.5.2.1.
6
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.161 17.5.1.4
1
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 161) Although in some cases the code given is unambiguously the optimum implementation.
§ 17.5.1.4
© ISO/IEC 2011 – All rights reserved
429
ISO/IEC 14882:2011(E)
2
Descriptions of class member functions follow the order (as appropriate):162 — 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):163 — 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 — Error conditions: the error conditions for error codes reported by the function. — Notes: non-normative comments about the function
4
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.
5
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.
6
If the formulation of a complexity requirement calls for a negative number of operations, the actual requirement is zero operations.164 162) 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. 163) 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. 164) This simplifies the presentation of complexity requirements in some cases.
§ 17.5.1.4
430
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
7
Complexity requirements specified in the library clauses are upper bounds, and implementations that provide better complexity guarantees satisfy the requirements.
8
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
[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
Other conventions
[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 17.5.2.1.1
Type descriptions
[type.descriptions]
General
[type.descriptions.general]
1
The Requirements subclauses may describe names that are used to specify constraints on template arguments.165 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.
2
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]
1
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.166
2
The enumerated type enumerated can be written: enum enumerated static const static const static const static const .....
3
{ V0 , V1 , V2 , V3 , ..... };
enumerated enumerated enumerated enumerated
C0 C1 C2 C3
(V0 (V1 (V2 (V3
); ); ); );
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: 165) Examples from 17.6.3 include: EqualityComparable, LessThanComparable, CopyConstructible. Examples from 24.2 include: InputIterator, ForwardIterator, Function, Predicate. 166) Such as an integer type, with constant integer values (3.9.1).
§ 17.5.2.1.3
© ISO/IEC 2011 – All rights reserved
431
ISO/IEC 14882:2011(E)
// 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>
<set> <sstream> <stack> <stdexcept> <streambuf> <string> <strstream> <system_error>
Table 15 — C++ headers for C library facilities
<cuchar>
TR, as appropriate, as if by inclusion. In the C++ standard library, however, the declarations (except for names which are defined as macros in C) are within namespace scope (3.3.6) of the namespace std. It is unspecified whether these names are first declared within the global namespace scope and are then injected into namespace std by explicit using-declarations (7.3.3). 5
Names which are defined as macros in C shall be defined as macros in the C++ standard library, even if C grants license for implementation as functions. [ Note: The names defined as macros in C include the following: assert, offsetof, setjmp, va_arg, va_end, and va_start. — end note ]
6
Names that are defined as functions in C shall be defined as functions in the C++ standard library.175
7
Identifiers that are keywords or operators in C++ shall not be defined as macros in C++ standard library headers.176
8
D.5, C standard library headers, describes the effects of using the name.h (C header) form in a C++ program.177 17.6.1.3
Freestanding implementations
[compliance]
1
Two kinds of implementations are defined: hosted and freestanding (1.4). For a hosted implementation, this International Standard describes the set of available headers.
2
A freestanding implementation has an implementation-defined set of headers. This set shall include at least the headers shown in Table 16.
3
The supplied version of the header shall declare at least the functions abort, atexit, at_quick_175) 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. 176) In particular, including the standard header or has no effect. 177) 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.1.3
© ISO/IEC 2011 – All rights reserved
435
ISO/IEC 14882:2011(E)
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>
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 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
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).
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.178
3
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]
1
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).
2
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.179 178) This is the same as the Standard C library. 179) 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.2.3
436
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
3
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 1
Requirements on types and expressions
[utility.requirements]
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 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.
2
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
§ 17.6.3.1
© ISO/IEC 2011 – All rights reserved
437
ISO/IEC 14882:2011(E)
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 ] 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
Post-condition All resources owned by u are reclaimed, no exception is propagated.
Swappable requirements
[swappable.requirements]
1
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.
2
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: § 17.6.3.2
438
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
— the two swap function templates defined in (20.2) and — the lookup set produced by argument-dependent lookup (3.4.2). [ 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 ] 4
An rvalue or lvalue t is swappable if and only if t is swappable with any rvalue or lvalue, respectively, of type T.
5
A type X satisfying any of the iterator requirements (24.2) is 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 contraint
} 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);
§ 17.6.3.2
© ISO/IEC 2011 – All rights reserved
439
ISO/IEC 14882:2011(E)
}
— 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 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
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 ]
3
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.
4
No operation which is part of the NullablePointer requirements shall exit via an exception.
5
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), — the expressions shown in Table 26 are valid and have the indicated semantics, and — it satisfies all other requirements in this subclause.
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.4
440
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 26 — Hash requirements [hash]
17.6.3.5
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.
Allocator requirements
[allocator.requirements]
1
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.
2
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
Definition any non-const, non-reference object type 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
§ 17.6.3.5
© ISO/IEC 2011 – All rights reserved
441
ISO/IEC 14882:2011(E)
Table 27 — Descriptive variable definitions (continued) Variable z r s u v n Args args
Definition 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. a value of type V a value of type XX::size_type. a template parameter pack a 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 size of the largest object in the allocation model. a type that can represent the difference between any two pointers 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
§ 17.6.3.5
442
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 28 — Allocator requirements (continued) Expression
Return type
typename X::template rebind::other *p *q
Y
p->m
type of T::m
q->m
type of T::m
static_cast<X::pointer>(w) static_cast<X ::const_pointer>(z) a.allocate(n)
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
bool
T& const T&
X::const_pointer X::pointer
Assertion/note pre-/post-condition For all U (including T), Y::template rebind::other is X. *q refers to the same object as *p pre: (*p).m is well-defined. equivalent to (*p).m 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.180 [ 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)
Default See Note A, below.
a.allocate(n)
numeric_limits<size_type>::max()
§ 17.6.3.5
© ISO/IEC 2011 – All rights reserved
443
ISO/IEC 14882:2011(E)
Table 28 — Allocator requirements (continued) Expression
Return type
X a1(a); X a(b); X a1(move(a));
X a(move(b));
Assertion/note pre-/post-condition 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. 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
3
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.
4
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, 180) 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
444
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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). 5
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 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); };
— end example ] 6
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
Overview
[constraints] [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 17.6.4.2.1
Namespace use Namespace std
[namespace.constraints] [namespace.std]
1
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.181
2
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 181) 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
© ISO/IEC 2011 – All rights reserved
445
ISO/IEC 14882:2011(E)
— an explicit or partial specialization of any member class template of a standard library class or class template. 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. 3
A translation unit shall not declare namespace std to be an inline namespace (7.3.1). 17.6.4.2.2
1
[namespace.posix]
The behavior of a C++ 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
1
Namespace posix
Reserved names
[reserved.names]
The C++ standard library reserves the following kinds of names: — macros — 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
Macro names
[macro.names]
1
A translation unit that includes a standard library header shall not #define or #undef names declared in any standard library header.
2
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
1
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
External linkage
[extern.names]
1
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,182 both in namespace std and in the global namespace.
2
Each global function signature declared with external linkage in a header is reserved to the implementation to designate that function signature with external linkage. 183 182) The list of such reserved names includes errno, declared or defined in . 183) 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 .
§ 17.6.4.3.3
446
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
3
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.
4
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, 184 or as a name of namespace scope in the global namespace. 17.6.4.3.4
1
[usrlit.suffix]
Headers
[alt.headers]
If a file with a name equivalent to the derived file name for one of the C++ standard library headers is not 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
1
User-defined literal suffixes
Literal suffix identifiers that do not start with an underscore are reserved for future standardization. 17.6.4.4
1
[extern.types]
For each type T from the Standard C library,185 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
1
Types
Derived classes
[derived.classes]
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).
2
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) — 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. 184) 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. 185) 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.6
© ISO/IEC 2011 – All rights reserved
447
ISO/IEC 14882:2011(E)
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.8
Other functions
[res.on.functions]
1
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.
2
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.8
448
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
Shared objects and the library
[res.on.objects]
1
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 ]
2
[ 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 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
1
Requires paragraph
[res.on.required]
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
Conforming implementations Overview
[conforming] [conforming.overview]
1
This section describes the constraints upon, and latitude of, implementations of the C++ standard library.
2
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
1
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.
§ 17.6.5.2
© ISO/IEC 2011 – All rights reserved
449
ISO/IEC 14882:2011(E)
2
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).
3
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]
1
The names and global function signatures described in 17.6.1.1 are reserved to the implementation.
2
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]
1
It is unspecified whether any global or non-member functions in the C++ standard library are defined as inline (7.1.2).
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.186
3
An implementation shall not declare a global or non-member function signature with additional default arguments.
4
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:
3
The macro NULL is an implementation-defined C++ null pointer constant in this International Standard (4.10).194
4
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.195 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.
5
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.
6
The type size_t is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object.
7
[ 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 ]
8
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.
9
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
In general
[support.limits] [support.limits.general]
The headers (18.3.2), , and (18.3.3) supply characteristics of implementationdependent arithmetic types (3.9.1).
18.3.2 18.3.2.1
Numeric limits Class template numeric_limits
[limits] [limits.numeric]
1
The numeric_limits class template provides a C++ program with information about various properties of the implementation’s representation of the arithmetic types.
2
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. 194) Possible definitions include 0 and 0L, but not (void*)0. 195) Note that offsetof is required to work as specified even if unary operator& is overloaded for any of the types involved.
§ 18.3.2.1
© ISO/IEC 2011 – All rights reserved
455
ISO/IEC 14882:2011(E)
3
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.
4
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; 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 constexpr int
min_exponent = 0;
§ 18.3.2.3
456
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
static constexpr int static constexpr int static constexpr int static static static static static static static static static
constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr constexpr
min_exponent10 = 0; max_exponent = 0; max_exponent10 = 0;
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(); } 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
The default numeric_limits template shall have all members, but with 0 or false values.
2
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.196
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.197
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.198 196) Equivalent to CHAR_MIN, SHRT_MIN, FLT_MIN, DBL_MIN, etc. 197) Equivalent to CHAR_MAX, SHRT_MAX, FLT_MAX, DBL_MAX, etc. 198) 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.
§ 18.3.2.4
© ISO/IEC 2011 – All rights reserved
457
ISO/IEC 14882:2011(E)
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. For floating point types, the number of radix digits in the mantissa.199
10
static constexpr int digits10; 11
Number of base 10 digits that can be represented without change.200
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).201
22
For integer types, specifies the base of the representation.202
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.203
25
Meaningful for all floating point types. static constexpr T round_error() noexcept; 199) 200) 201) 202) 203)
Equivalent to FLT_MANT_DIG, DBL_MANT_DIG, LDBL_MANT_DIG. 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.
§ 18.3.2.4
458
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
26
Measure of the maximum rounding error.204 static constexpr int
min_exponent;
27
Minimum negative integer such that radix raised to the power of one less than that integer is a normalized floating point number.205
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.206
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.207
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.208
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.”209
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.”210
42
Meaningful for all floating point types.
43
Shall be true for all specializations in which is_iec559 != false. static constexpr float_denorm_style has_denorm; 204) 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. 205) Equivalent to FLT_MIN_EXP, DBL_MIN_EXP, LDBL_MIN_EXP. 206) Equivalent to FLT_MIN_10_EXP, DBL_MIN_10_EXP, LDBL_MIN_10_EXP. 207) Equivalent to FLT_MAX_EXP, DBL_MAX_EXP, LDBL_MAX_EXP. 208) Equivalent to FLT_MAX_10_EXP, DBL_MAX_10_EXP, LDBL_MAX_10_EXP. 209) Required by LIA-1. 210) Required by LIA-1.
§ 18.3.2.4
© ISO/IEC 2011 – All rights reserved
459
ISO/IEC 14882:2011(E)
44
denorm_present if the type allows denormalized values (variable number of exponent bits)211 , 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.212
46
static constexpr T infinity() noexcept; 47
Representation of positive infinity, if available.213
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.214
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.215
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.216
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.217
57
Meaningful for all floating point types. static constexpr bool is_bounded;
58
True if the set of values representable by the type is finite.218 [ 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; 211) 212) 213) 214) 215) 216) 217) 218)
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. Required by LIA-1.
§ 18.3.2.4
460
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
60
True if the type is modulo.219 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.220
64
Meaningful for all specializations. static constexpr bool tinyness_before;
65
true if tinyness is detected before rounding.221
66
Meaningful for all floating point types. static constexpr float_round_style round_style;
67
The rounding style for the type.222
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 }; } 1
[round.style]
= -1, = 0, = 1, = 2, = 3
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 219) 220) 221) 222)
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
© ISO/IEC 2011 – All rights reserved
461
ISO/IEC 14882:2011(E)
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
numeric_limits specializations
[numeric.special]
1
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.
2
[ 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 static static static
constexpr constexpr constexpr constexpr
int int int int
min_exponent min_exponent10 max_exponent max_exponent10
= = = =
-125; - 37; +128; + 38;
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
= = = = =
true; true; true; denorm_absent; false;
§ 18.3.2.7
462
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
inline inline inline inline
static static static static
constexpr constexpr constexpr constexpr
static static static static static
constexpr constexpr constexpr constexpr constexpr
bool bool bool bool bool
float float float float
infinity() quiet_NaN() signaling_NaN() denorm_min()
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; }; }
— end example ] 3
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 static static static static
constexpr 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; bool infinity() noexcept { return 0; } bool quiet_NaN() noexcept { return 0; } bool signaling_NaN() noexcept { return 0; } bool denorm_min() noexcept { return 0; }
0; = 0; 0; = 0;
static constexpr bool is_iec559 = false; static constexpr bool is_bounded = true;
§ 18.3.2.7
© ISO/IEC 2011 – All rights reserved
463
ISO/IEC 14882:2011(E)
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
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
2
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 ]
3
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
Integer types
[cstdint]
Header synopsis
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;
[cstdint.syn] // // // //
optional optional optional optional
§ 18.4.1
464
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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;
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 C++. — end note ]
18.5
Start and termination
[support.start.term]
1
Table 33 describes some of the contents of the header .
2
The contents are the same as the Standard C library header <stdlib.h>, with the following changes: [[noreturn]] void _Exit(int status) noexcept;
§ 18.5
© ISO/IEC 2011 – All rights reserved
465
ISO/IEC 14882:2011(E)
Table 33 — Header synopsis Type Macros: Functions:
3
EXIT_FAILURE _Exit at_quick_exit
Name(s) EXIT_SUCCESS abort exit
atexit quick_exit
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.223 See 3.6.3 for the order of destructions and calls. (Automatic objects are not destroyed as a result of calling exit().)224 If control leaves a registered function called by exit because the function does not provide a handler for a thrown exception, terminate() shall be called (15.5.1). — 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.225 223) A function is called for every time it is registered. 224) 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(). 225) The macros EXIT_FAILURE and EXIT_SUCCESS are defined in .
§ 18.5
466
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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, 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; } 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* operator new
(std::size_t size, void* ptr) noexcept;
§ 18.6
© ISO/IEC 2011 – All rights reserved
467
ISO/IEC 14882:2011(E)
void* operator new[](std::size_t size, void* ptr) noexcept; void operator delete (void* ptr, void*) noexcept; void operator 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.
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 ] § 18.6.1.1
468
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.226
2
Replaceable: a C++ program can define a function with this function signature that displaces the default version defined by the C++ standard library.
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. 226) 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
© ISO/IEC 2011 – All rights reserved
469
ISO/IEC 14882:2011(E)
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;
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;
§ 18.6.1.3
470
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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; 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. § 18.6.2.1
© ISO/IEC 2011 – All rights reserved
471
ISO/IEC 14882:2011(E)
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.4
set_new_handler
[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.6.2.5
472
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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). 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. § 18.7.1
© ISO/IEC 2011 – All rights reserved
473
ISO/IEC 14882:2011(E)
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.3
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;
§ 18.7.3
474
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
exception_ptr;
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:
§ 18.8.1
© ISO/IEC 2011 – All rights reserved
475
ISO/IEC 14882:2011(E)
exception() noexcept; exception(const exception&) noexcept; exception& operator=(const exception&) noexcept; virtual ~exception(); virtual const char* what() const noexcept; }; } 1
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.
2
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.2
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).
§ 18.8.2
476
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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.4
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.3.4
© ISO/IEC 2011 – All rights reserved
477
ISO/IEC 14882:2011(E)
18.8.4
[uncaught]
uncaught_exception
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 unexpected() or 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 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. [ 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 10
Requires: p shall not be a null pointer. Throws: the exception object to which p refers.
§ 18.8.5
478
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
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.
2
[ 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 terminate(). Otherwise, it throws the stored exception captured by *this. exception_ptr nested_ptr() const noexcept;
5
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). § 18.8.6
© ISO/IEC 2011 – All rights reserved
479
ISO/IEC 14882:2011(E)
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.2
Initializer list access
[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;
§ 18.9.2
480
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
Other runtime support
[support.runtime]
1
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.
2
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:
3
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 ...).227 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.
4
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.
5
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 ]
6
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.
7
The header and the header <stdalign.h> shall not define a macro named alignas.
8
The header and the header <stdbool.h> shall not define macros named bool, true, or false. 227) Note that va_start is required to work as specified even if unary operator& is overloaded for the type of parmN.
§ 18.10
© ISO/IEC 2011 – All rights reserved
481
ISO/IEC 14882:2011(E)
9
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.228 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 Table 38 — Header synopsis
Type Macro:
Name(s) __bool_true_false_are_defined Table 39 — Header synopsis
Type Functions:
Name(s) getenv
system
228) 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
482
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 40 — Header synopsis Type Macro: Type: Function:
Name(s) CLOCKS_PER_SEC clock_t clock
§ 18.10
© ISO/IEC 2011 – All rights reserved
483
ISO/IEC 14882:2011(E)
19 19.1
Diagnostics library
[diagnostics]
General
[diagnostics.general]
1
This Clause describes components that C++ programs may use to detect and report error conditions.
2
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
Subclause Exception classes Assertions Error numbers System error support
Exception classes
Header(s) <stdexcept> <system_error>
[std.exceptions]
1
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.
2
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.
3
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);
§ 19.2.1
484
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
explicit logic_error(const char* what_arg); }; } 1
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);
§ 19.2.3
© ISO/IEC 2011 – All rights reserved
485
ISO/IEC 14882:2011(E)
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.4
Class length_error
[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.5
486
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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); }; } 1
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); };
§ 19.2.8
© ISO/IEC 2011 – All rights reserved
487
ISO/IEC 14882:2011(E)
} 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.9
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
Name(s) assert
The contents are the same as the Standard C library header . See also: ISO C 7.2.
§ 19.3
488
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
19.4 1
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. Table 43 — Header synopsis Type Macros: E2BIG EACCES EADDRINUSE EADDRNOTAVAIL EAFNOSUPPORT EAGAIN EALREADY EBADF EBADMSG EBUSY ECANCELED ECHILD ECONNABORTED
19.5
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
System error support
ENOTEMPTY ENOTRECOVERABLE ENOTSOCK ENOTSUP ENOTTY ENXIO EOPNOTSUPP EOVERFLOW EOWNERDEAD EPERM EPIPE EPROTO EPROTONOSUPPORT EPROTOTYPE
ERANGE EROFS ESPIPE ESRCH ETIME ETIMEDOUT ETXTBSY EWOULDBLOCK EXDEV errno
[syserr]
1
This subclause describes components that the standard library and C++ programs may use to report error conditions originating from the operating system or other low-level application program interfaces.
2
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; class error_code; 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,
// // // // // // //
EAFNOSUPPORT EADDRINUSE EADDRNOTAVAIL EISCONN E2BIG EDOM EFAULT
§ 19.5
© ISO/IEC 2011 – All rights reserved
489
ISO/IEC 14882:2011(E)
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, 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,
// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //
EBADF EBADMSG EPIPE ECONNABORTED EALREADY ECONNREFUSED ECONNRESET EXDEV EDESTADDRREQ EBUSY ENOTEMPTY ENOEXEC EEXIST EFBIG ENAMETOOLONG ENOSYS 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
§ 19.5
490
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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,
// // // // // // // // // // // // // // // //
EPROTO EPROTONOSUPPORT EROFS EDEADLK EAGAIN ERANGE ENOTRECOVERABLE ETIME ETXTBSY ETIMEDOUT ENFILE EMFILE EMLINK ELOOP EOVERFLOW EPROTOTYPE
}; 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
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.
4
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
§ 19.5.1.1
© ISO/IEC 2011 – All rights reserved
491
ISO/IEC 14882:2011(E)
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();
§ 20.2
© ISO/IEC 2011 – All rights reserved
501
ISO/IEC 14882:2011(E)
template class tuple;
// defined in
}
20.2.1 1
Operators
[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;
§ 20.3.2
504
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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);
§ 20.3.2
© ISO/IEC 2011 – All rights reserved
505
ISO/IEC 14882:2011(E)
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. 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.
§ 20.3.2
506
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
28
Effects: Assigns to first with std::forward(p.first) and to second with std::forward(p.second).
29
Returns: *this. 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. § 20.3.3
© ISO/IEC 2011 – All rights reserved
507
ISO/IEC 14882:2011(E)
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 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. § 20.4.1
508
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
2
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.1
© ISO/IEC 2011 – All rights reserved
509
ISO/IEC 14882:2011(E)
// 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, const 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 tuple(allocator_arg_t, const Alloc& a, pair&&);
§ 20.4.2
510
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
// 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&); // iff sizeof...(Types) == 2 operator=(pair&&) noexcept; // iff sizeof...(Types) == 2
// 20.4.2.3, tuple swap void swap(tuple&) noexcept(see below); }; }
20.4.2.1
Construction
[tuple.cnstr]
1
For each tuple constructor, an exception is thrown only if the construction of one of the types in Types throws an exception.
2
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. tuple(tuple&& u) = default;
§ 20.4.2.1
© ISO/IEC 2011 – All rights reserved
511
ISO/IEC 14882:2011(E)
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, const 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&&);
§ 20.4.2.1
512
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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);
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);
§ 20.4.2.2
© ISO/IEC 2011 – All rights reserved
513
ISO/IEC 14882:2011(E)
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
[tuple.swap]
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 tuple
— end example ]
§ 20.4.2.4
514
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.5
Tuple helper classes
[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; };
§ 20.4.2.5
© ISO/IEC 2011 – All rights reserved
515
ISO/IEC 14882:2011(E)
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&&. 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.6
516
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
The class template bitsetdescribes an object that can store a sequence consisting of a fixed number of bits, N.
3
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;
§ 20.5.2
© ISO/IEC 2011 – All rights reserved
521
ISO/IEC 14882:2011(E)
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(). 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.
§ 20.5.2
522
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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;
39
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);
§ 20.5.2
© ISO/IEC 2011 – All rights reserved
523
ISO/IEC 14882:2011(E)
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.3
bitset hash support
[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. § 20.5.4
524
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
template basic_ostream& operator synopsis
[memory.syn]
The header <memory> defines several types and template functions that describe properties of pointers and pointer-like types, manage memory for containers and other template types, and construct multiple objects in unitialized 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;
§ 20.6.2
© ISO/IEC 2011 – All rights reserved
525
ISO/IEC 14882:2011(E)
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.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: class default_delete; class 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) template bool operator==(nullptr_t, const unique_ptr& y) template bool operator!=(const unique_ptr& x, nullptr_t) template bool operator!=(nullptr_t, const unique_ptr& y)
noexcept; noexcept; noexcept; noexcept;
§ 20.6.2
526
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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,
§ 20.6.2
528
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
memory_order mo); template bool atomic_compare_exchange_weak( shared_ptr* p, shared_ptr* v, shared_ptr template bool atomic_compare_exchange_strong( shared_ptr* p, shared_ptr* v, shared_ptr template bool atomic_compare_exchange_weak_explicit( shared_ptr* p, shared_ptr* v, shared_ptr memory_order success, memory_order failure); template bool atomic_compare_exchange_strong_explicit( shared_ptr* p, shared_ptr* v, shared_ptr memory_order success, memory_order failure);
w);
w);
w,
w,
// 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;
§ 20.6.3.1
© ISO/IEC 2011 – All rights reserved
529
ISO/IEC 14882:2011(E)
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.2
Pointer traits member functions
[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 T&. Returns: The first template 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 template 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);
§ 20.6.4
530
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 ] 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.229
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. 229) 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.5
© ISO/IEC 2011 – All rights reserved
531
ISO/IEC 14882:2011(E)
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; 1
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 ] § 20.6.8
532
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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; 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;
§ 20.6.8.1
© ISO/IEC 2011 – All rights reserved
533
ISO/IEC 14882:2011(E)
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;
7
Type: Alloc::propagate_on_container_copy_assignment if such a type exits, otherwise false_type. typedef see below propagate_on_container_move_assignment;
8
Type: Alloc::propagate_on_container_move_assignment if such a type exits, otherwise false_type. typedef see below propagate_on_container_swap;
9
Type: Alloc::propagate_on_container_swap if such a type exits, 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);
§ 20.6.8.2
534
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.9
The default allocator
[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
© ISO/IEC 2011 – All rights reserved
535
ISO/IEC 14882:2011(E)
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&. 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. § 20.6.9.2
536
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
template bool operator!=(const allocator&, const allocator&) noexcept; 2
Returns: false.
20.6.10 1
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);
§ 20.6.12.3
538
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
1
Effects: for (; first != last; ++first) ::new (static_cast(&*first)) typename iterator_traits::value_type(x);
20.6.12.4
[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:
Name(s) calloc malloc free realloc
2
The contents are the same as the Standard C library header <stdlib.h>, with the following changes:
3
The functions calloc(), malloc(), and realloc() do not attempt to allocate storage by calling ::operator new() (18.6).
4
The function free() does not attempt to deallocate storage by calling ::operator delete(). See also: ISO C Clause 7.11.2.
5
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 ]
6
Table 46 describes the header .
7
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
© ISO/IEC 2011 – All rights reserved
539
ISO/IEC 14882:2011(E)
Table 46 — Header synopsis Type Macro: Type: Functions: memcpy
20.7 20.7.1
Name(s) NULL size_t memchr memcmp memmove memset
Smart pointers
[smartptr]
Class template unique_ptr
[unique.ptr]
1
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.
2
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).
3
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.
4
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. 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 ]
5
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.
6
[ 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);
§ 20.7.1
540
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.1.1 20.7.1.1.1
Default deleters In general
[unique.ptr.dltr] [unique.ptr.dltr.general]
1
The class template default_delete serves as the default deleter (destruction policy) for the class template unique_ptr.
2
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; };
§ 20.7.1.1.2
© ISO/IEC 2011 – All rights reserved
541
ISO/IEC 14882:2011(E)
} 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.3
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
542
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
// 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; void swap(unique_ptr& u) noexcept; // disable copy from lvalue unique_ptr(const unique_ptr&) = delete; unique_ptr& operator=(const unique_ptr&) = delete; }; } 1
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.
2
If the deleter’s type D is not a reference type, D shall satisfy the requirements of Destructible (Table 24).
3
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).
4
[ 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;
§ 20.7.1.2.1
© ISO/IEC 2011 – All rights reserved
543
ISO/IEC 14882:2011(E)
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: 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:
§ 20.7.1.2.1
544
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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. 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 implictly 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();
§ 20.7.1.2.2
© ISO/IEC 2011 – All rights reserved
545
ISO/IEC 14882:2011(E)
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 execption. 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;
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(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. § 20.7.1.2.4
546
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.5
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) : unique_ptr() { } // destructor ~unique_ptr();
§ 20.7.1.3
© ISO/IEC 2011 – All rights reserved
547
ISO/IEC 14882:2011(E)
// 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.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
Descriptions are provided below only for member functions that have behavior different from the primary template.
3
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;
§ 20.7.1.3.2
548
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.4
unique_ptr specialized algorithms
[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;
§ 20.7.1.4
© ISO/IEC 2011 – All rights reserved
549
ISO/IEC 14882:2011(E)
10
Returns: !x. 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 template function returns nullptr < x. The second template function returns x < nullptr. template bool operator=(nullptr_t, const unique_ptr& x);
16
Returns: The first template function returns !(x < nullptr). The second template function 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 1
An exception of type bad_weak_ptr is thrown by the shared_ptr constructor taking a weak_ptr. § 20.7.2.1
550
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
© ISO/IEC 2011 – All rights reserved
551
ISO/IEC 14882:2011(E)
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
552
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
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.
3
[ Example: if(shared_ptr<X> px = dynamic_pointer_cast<X>(py)) { // do something with px }
— end example ] 4
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
© ISO/IEC 2011 – All rights reserved
553
ISO/IEC 14882:2011(E)
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. template shared_ptr(auto_ptr&& r);
§ 20.7.2.2.1
554
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
© ISO/IEC 2011 – All rights reserved
555
ISO/IEC 14882:2011(E)
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(). 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;
§ 20.7.2.2.5
556
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.7
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.4
Class template enable_shared_from_this
[util.smartptr.enab]
1
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.
2
[ Example: struct X: public enable_shared_from_this<X> { }; int main() { shared_ptr<X> p(new X);
§ 20.7.2.4
562
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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: 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); } };
§ 20.7.2.4
© ISO/IEC 2011 – All rights reserved
563
ISO/IEC 14882:2011(E)
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
shared_ptr atomic access
[util.smartptr.shared.atomic]
1
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.
2
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. 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.7.2.5
564
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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);
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.5
© ISO/IEC 2011 – All rights reserved
565
ISO/IEC 14882:2011(E)
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
Function objects
[function.objects]
1
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).230 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.
2
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;
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 equal_to; template struct not_equal_to; template struct greater; 230) 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
566
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
template struct less; template struct greater_equal; template struct 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; } // 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;
§ 20.8
© ISO/IEC 2011 – All rights reserved
567
ISO/IEC 14882:2011(E)
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 unspecified mem_fn(R (T::*)(Args...) const volatile); template unspecified mem_fn(R (T::*)(Args...) &); template unspecified mem_fn(R (T::*)(Args...) const &); template unspecified mem_fn(R (T::*)(Args...) volatile &); template unspecified mem_fn(R (T::*)(Args...) const volatile &); template unspecified mem_fn(R (T::*)(Args...) &&); template unspecified mem_fn(R (T::*)(Args...) const &&); template unspecified mem_fn(R (T::*)(Args...) volatile &&);
§ 20.8
568
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
template unspecified mem_fn(R (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; 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>());
— end example ] 4
[ Example: To negate every element of a: § 20.8
© ISO/IEC 2011 – All rights reserved
569
ISO/IEC 14882:2011(E)
transform(a.begin(), a.end(), a.begin(), negate<double>());
— end example ] 5
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
Definitions
[func.def ]
1
The following definitions apply to this Clause:
2
A call signature is the name of a return type followed by a parenthesized comma-separated list of zero or more argument types.
3
A callable type is a function object type (20.8) or a pointer to member.
4
A callable object is an object of a callable type.
5
A call wrapper type is a type that holds a callable object and supports a call operation that forwards to that object.
6
A call wrapper is an object of a call wrapper type.
7
A target object is the callable object held by a call wrapper.
20.8.2 1
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
Define INVOKE (f, t1, t2, ..., tN, R) as INVOKE (f, t1, t2, ..., tN) implicitly converted to R.
3
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; — 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.
§ 20.8.2
570
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
reference_wrapper is a CopyConstructible and CopyAssignable wrapper around a reference to an object or function of type T.
2
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.
3
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
© ISO/IEC 2011 – All rights reserved
571
ISO/IEC 14882:2011(E)
— 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
572
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
20.8.3.5
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. 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.
§ 20.8.4
© ISO/IEC 2011 – All rights reserved
573
ISO/IEC 14882:2011(E)
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; };
4
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.
§ 20.8.5
574
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 ::type, — ti is the ith argument in the function paramater 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);
§ 20.8.9.1.2
© ISO/IEC 2011 – All rights reserved
577
ISO/IEC 14882:2011(E)
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, v1, v2, ..., 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, v1, v2, ..., 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 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.3
Placeholders
[func.bind.place]
namespace std { namespace placeholders { // M is the implementation-defined number of placeholders
§ 20.8.9.1.3
578
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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...) 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. § 20.8.10
© ISO/IEC 2011 – All rights reserved
579
ISO/IEC 14882:2011(E)
4
Throws: Nothing.
20.8.11 1
Polymorphic function wrappers
This subclause describes a polymorphic wrapper class that encapsulates arbitrary callable objects. 20.8.11.1
1
[func.wrap]
Class bad_function_call
[func.wrap.badcall]
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 { public: typedef R result_type; typedef T1 argument_type; typedef T1 first_argument_type; typedef T2 second_argument_type;
// // // // // //
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);
§ 20.8.11.2
580
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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; 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
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.
2
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). § 20.8.11.2
© ISO/IEC 2011 – All rights reserved
581
ISO/IEC 14882:2011(E)
3
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
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);
6
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);
§ 20.8.11.2.1
582
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.2
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).
§ 20.8.11.2.4
© ISO/IEC 2011 – All rights reserved
583
ISO/IEC 14882:2011(E)
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
[func.wrap.func.nullptr]
null pointer comparison operators
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.7
(bool) f. 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; § 20.8.12
584
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
— 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]
This subclause describes components used by C++ 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 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
Requirements
[meta.rqmts]
1
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.
2
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.
§ 20.9.1
© ISO/IEC 2011 – All rights reserved
585
ISO/IEC 14882:2011(E)
3
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.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;
§ 20.9.2
586
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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; 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.2
© ISO/IEC 2011 – All rights reserved
587
ISO/IEC 14882:2011(E)
// 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> struct aligned_storage; 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; } 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
Unary type traits
[meta.unary]
1
This sub-clause contains templates that may be used to query the properties of a type at compile time.
2
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]
1
The primary type categories correspond to the descriptions given in section 3.9 of the C++ standard.
2
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.
3
[ Note: For any given type T, exactly one of the primary type categories has a value member that evaluates to true. — end note ]
§ 20.9.4.1
588
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 47 — Primary type category predicates 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
20.9.4.2
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)
Composite type traits
[meta.unary.comp]
1
These templates provide convenient compositions of the primary type categories, corresponding to the descriptions given in section 3.9.
2
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;
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)
Comments
§ 20.9.4.2
© ISO/IEC 2011 – All rights reserved
589
ISO/IEC 14882:2011(E)
Table 48 — Composite type category predicates (continued) Template template struct is_object; template struct is_scalar; template struct is_compound; template struct is_member_pointer;
20.9.4.3
Condition 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]
1
These templates provide access to some of the more important properties of types.
2
It is unspecified whether the library defines any full or partial specialisations of any of these templates.
3
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)
template struct is_standard_layout;
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)
T is volatile-qualified (3.9.3) T is a trivial type (3.9)
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 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.
§ 20.9.4.3
590
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 49 — Type property predicates (continued) Template template struct is_empty;
template struct is_polymorphic;
Condition 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;
template struct is_copy_constructible;
template struct is_move_constructible;
Preconditions T shall be a complete type, (possibly cv-qualified) void, or an array of unknown bound.
T shall be a complete type, type, (possibly cv-qualified) void, or an array of unknown bound. T shall be a complete type, 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. is_T shall be a complete type, constructible::value (possibly cv-qualified) is true. void, or an array of unknown bound. is_constructible::value is (possibly cv-qualified) true. void, or an array of unknown bound. is_constructible::value is true. (possibly cv-qualified) void, or an array of unknown bound.
§ 20.9.4.3
© ISO/IEC 2011 – All rights reserved
591
ISO/IEC 14882:2011(E)
Table 49 — Type property predicates (continued) Template template struct is_assignable;
template struct is_copy_assignable;
Condition 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_move_assignable;
is_assignable::value is true.
template struct is_destructible;
For a complete type T and given template struct test { U u; };, test::˜test() is not deleted.
Preconditions 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.
§ 20.9.4.3
592
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 49 — Type property predicates (continued) Template template
template struct is_nothrow_constructible;
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. T and all types in the parameter pack Args shall be complete types, (possibly cv-qualified) void, or arrays of unknown bound.
§ 20.9.4.3
© ISO/IEC 2011 – All rights reserved
593
ISO/IEC 14882:2011(E)
Table 49 — Type property predicates (continued) Template template struct is_nothrow_default_constructible;
Condition Preconditions is_nothrow_T shall be a complete type, constructible::value (possibly cv-qualified) is true. void, or an array of unknown bound. is_nothrow_T shall be a complete type, constructible::value is true. void, or an array of unknown bound. is_nothrow_T shall be a complete type, constructible::value is true. void, or an array of unknown bound. is_assignable::value is true and types, (possibly the assignment is known cv-qualified) void, or not to throw any arrays of unknown bound. exceptions (5.3.7). T shall be a complete type, is_nothrow_(possibly cv-qualified) assignable::value is true. unknown bound. is_nothrow_T shall be a complete type, assignable::value is true. void, or an array of unknown bound. T shall be a complete type, is_destructible::value (possibly cv-qualified) void, or an array of is true and the indicated destructor is known not to unknown bound. throw any exceptions (5.3.7). T has a virtual T shall be a complete type, destructor (12.4) (possibly cv-qualified) void, or an array of unknown bound.
template struct is_nothrow_copy_constructible; template 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;
4
[ Example: is_const::value is_const::value is_const::value is_const::value is_const::value
// // // // //
true false false false true
— end example ] 5
[ Example: remove_const::type
// volatile int
§ 20.9.4.3
594
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
remove_const::type remove_const::type remove_const::type
// const int* // const int& // int[3]
— end example ] 6
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);
— end example ] 3
[ Example: // the following assertions hold: assert(extent::value == 0); assert(extent::value == 2); assert(extent::value == 2); assert(extent::value == 0);
§ 20.9.5
© ISO/IEC 2011 – All rights reserved
595
ISO/IEC 14882:2011(E)
assert((extent::value) == 0); assert((extent::value) == 0); assert((extent::value) == 4); assert((extent::value) == 4);
— end example ]
20.9.6
Relationships between types
[meta.rel]
1
This sub-clause contains templates that may be used to query relationships between types at compile time.
2
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 see below
template struct is_base_of;
template struct is_convertible;
3
Comments
If Base and Derived are 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
// // // // // // // //
true true true true false false false false
— end example ] 4
Given the following function prototype: template
§ 20.9.6
596
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
typename add_rvalue_reference::type create();
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
Transformations between types
[meta.trans]
1
This sub-clause contains templates that may be used to transform one type to another following some predefined rule.
2
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;
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.
§ 20.9.7.1
© ISO/IEC 2011 – All rights reserved
597
ISO/IEC 14882:2011(E)
20.9.7.2
Reference modifications
[meta.trans.ref ]
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;
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.
§ 20.9.7.3
598
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
20.9.7.4
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));
— end example ] 2
[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;
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*.
§ 20.9.7.5
© ISO/IEC 2011 – All rights reserved
599
ISO/IEC 14882:2011(E)
20.9.7.6
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;
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 cosntant 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.
§ 20.9.7.6
600
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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; };
— end note ] 2
It is implementation-defined whether any extended alignment is supported (3.11).
3
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 {
§ 20.9.7.6
© ISO/IEC 2011 – All rights reserved
601
ISO/IEC 14882:2011(E)
typedef typename common_type::type type; }; 4
[ 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
Compile-time rational arithmetic In general
[ratio] [ratio.general]
1
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.
2
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
ratio_add = see below; ratio_subtract = see below; ratio_multiply = see below; ratio_divide = see below;
// 20.10.5, ratio comparison template struct ratio_equal; template struct ratio_not_equal; template struct ratio_less;
§ 20.10.2
602
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
template struct ratio_less_equal; template struct ratio_greater; template struct ratio_greater_equal; // 20.10.6, convenience SI typedefs typedef ratio typedef ratio typedef ratio typedef ratio typedef ratio typedef ratio typedef ratio typedef ratio typedef ratio typedef ratio typedef ratio< 10, 1> typedef ratio< 100, 1> typedef ratio< 1000, 1> typedef ratio< 1000000, 1> typedef ratio< 1000000000, 1> typedef ratio< 1000000000000, 1> typedef ratio< 1000000000000000, 1> typedef ratio< 1000000000000000000, 1> typedef ratio< 1000000000000000000000, 1> typedef ratio
yocto; zepto; atto; femto; pico; nano; micro; milli; centi; deci; deca; hecto; kilo; mega; giga; tera; peta; exa; zetta; yotta;
// see below // see below
// 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
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 ]
2
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
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 § 20.10.4
© ISO/IEC 2011 – All rights reserved
603
ISO/IEC 14882:2011(E)
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. 2
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. Table 58 — Expressions used to perform ratio arithmetic Type ratio_add ratio_subtract ratio_multiply ratio_divide
3
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
[ 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"); 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. § 20.10.5
604
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
template struct ratio_less_equal : integral_constant { }; template struct ratio_greater : integral_constant { }; template struct ratio_greater_equal : integral_constant { };
20.10.6 1
[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 20.11.1 1
SI types for ratio
Time utilities In general
[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);
§ 20.11.2
© ISO/IEC 2011 – All rights reserved
605
ISO/IEC 14882:2011(E)
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 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);
§ 20.11.2
606
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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, 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
Clock requirements
[time.clock.req]
1
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.
2
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 ]
§ 20.11.3
© ISO/IEC 2011 – All rights reserved
607
ISO/IEC 14882:2011(E)
Table 59 — Clock requirements Expression C1::rep C1::period C1::duration
Return type An arithmetic type or a class emulating an arithmetic type a specialization of ratio
C1::is_steady
chrono::duration chrono::time_point or chrono::time_point const bool
C1::now()
C1::time_point
C1::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. 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); 1
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.1
© ISO/IEC 2011 – All rights reserved
611
ISO/IEC 14882:2011(E)
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. 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);
§ 20.11.5.3
612
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
17
Effects: rep_ %= rhs.
18
Returns: *this. duration& operator%=(const duration& rhs);
19
Effects: rep_ %= rhs.count().
20
Returns: *this. 20.11.5.4
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.
§ 20.11.5.5
© ISO/IEC 2011 – All rights reserved
613
ISO/IEC 14882:2011(E)
template constexpr duration operator/(const duration& d, const Rep2& s); 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
[time.duration.cast]
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 explicit time_point(const duration& d); template
// same as time_point() + d
§ 20.11.6
© ISO/IEC 2011 – All rights reserved
615
ISO/IEC 14882:2011(E)
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
Clock shall meet the Clock requirements (20.11.7).
2
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
616
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
20.11.6.4
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 1
[time.clock]
The types defined in this subclause shall satisfy the TrivialClock requirements (20.11.3). 20.11.7.1
1
Clocks
Class system_clock
[time.clock.system]
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. static time_point from_time_t(time_t t) noexcept;
4
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.1
618
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
20.11.7.2 1
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; };
20.11.7.3 1
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 .231 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. 231) 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
© ISO/IEC 2011 – All rights reserved
619
ISO/IEC 14882:2011(E)
20.12 20.12.1
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
620
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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( const 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
© ISO/IEC 2011 – All rights reserved
621
ISO/IEC 14882:2011(E)
20.12.2
Scoped allocator adaptor member types
[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;
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(const scoped_allocator_adaptor&& other) noexcept;
§ 20.12.3
622
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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()). 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)...).
§ 20.12.4
© ISO/IEC 2011 – All rights reserved
623
ISO/IEC 14882:2011(E)
— 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())). — 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);
§ 20.12.4
624
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.13 20.13.1
Class type_index Header synopsis
[type.index] [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:
§ 20.13.2
© ISO/IEC 2011 – All rights reserved
625
ISO/IEC 14882:2011(E)
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) 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]
§ 20.13.4
626
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
© ISO/IEC 2011 – All rights reserved
627
ISO/IEC 14882:2011(E)
21 21.1
Strings library
[strings]
General
[strings.general]
1
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.
2
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
21.2 21.3
Subclause Character traits String classes
21.7
Null-terminated sequence utilities
Character traits
Header(s) <string> <string> <cuchar>
[char.traits]
1
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.
2
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.
3
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.
4
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
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;
§ 21.2.1
628
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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. 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)
charT
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
bool
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
§ 21.2.1
© ISO/IEC 2011 – All rights reserved
629
ISO/IEC 14882:2011(E)
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.232 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. 232) If eof() can be held in char_type then some iostreams operations may give surprising results.
§ 21.2.2
630
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
21.2.3
char_traits specializations
namespace std { template struct template struct template struct template struct }
[char.traits.specializations]
char_traits; char_traits; char_traits; char_traits<wchar_t>;
1
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>.
2
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
The defined types for int_type, pos_type, off_type, and state_type shall be int, streampos, streamoff, and mbstate_t respectively.
2
The type streampos shall be an implementation-defined type that satisfies the requirements for pos_type in 27.2.2 and 27.3.
3
The type streamoff shall be an implementation-defined type that satisfies the requirements for off_type in 27.2.2 and 27.3.
4
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.
§ 21.2.3.1
© ISO/IEC 2011 – All rights reserved
631
ISO/IEC 14882:2011(E)
5
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.
6
The member eof() shall return EOF. 21.2.3.2
struct char_traits
[char.traits.specializations.char16_t]
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
The type u16streampos shall be an implementation-defined type that satisfies the requirements for pos_type in 27.2.2 and 27.3.
2
The two-argument members assign, eq, and lt shall be defined identically to the built-in operators =, ==, and < respectively.
3
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;
§ 21.2.3.3
632
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
The type u32streampos shall be an implementation-defined type that satisfies the requirements for pos_type in 27.2.2 and 27.3.
2
The two-argument members assign, eq, and lt shall be defined identically to the built-in operators =, ==, and < respectively.
3
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;
}; }
§ 21.2.3.4
© ISO/IEC 2011 – All rights reserved
633
ISO/IEC 14882:2011(E)
1
The defined types for int_type, pos_type, and state_type shall be wint_t, wstreampos, and mbstate_t respectively.
2
The type wstreampos shall be an implementation-defined type that satisfies the requirements for pos_type in 27.2.2 and 27.3.
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.
4
The two-argument members assign, eq, and lt shall be defined identically to the built-in operators =, ==, and < respectively.
5
The member eof() shall return WEOF.
21.3 1
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
§ 21.3
634
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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&
lhs, rhs);
rhs); lhs,
lhs, rhs);
rhs); lhs,
lhs, rhs); lhs,
rhs);
§ 21.3
© ISO/IEC 2011 – All rights reserved
635
ISO/IEC 14882:2011(E)
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 charT* lhs, const basic_string&
lhs, rhs); lhs,
rhs);
lhs, rhs); lhs,
rhs); lhs, rhs); 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;
§ 21.3
© ISO/IEC 2011 – All rights reserved
637
ISO/IEC 14882:2011(E)
template struct hash<wstring>; }
21.4
Class template basic_string
[basic.string]
1
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.
2
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.233
3
The iterators supported by basic_string are random access iterators (24.2.7).
4
In all cases, size() ()
(21.4.8.9),
and
§ 21.4.2
642
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 63 — basic_string(const Allocator&) effects Element data() size() capacity()
Value a non-null pointer that is copyable and can have 0 added to it 0 an unspecified value
basic_string(const basic_string& str); basic_string(basic_string&& str) noexcept; 2
Effects: Constructs an object of class basic_string as indicated in Table 64. In the second form, str is left in a valid state with an unspecified value.
3
Throws: The second form throws nothing if the allocator’s move constructor throws nothing. 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()
basic_string(const basic_string& str, size_type pos, size_type n = npos, const Allocator& a = Allocator()); 4
Requires: pos str.size().
6
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()); 7
Requires: s shall not be a null pointer and n < npos.
8
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. basic_string(const charT* s, const Allocator& a = Allocator());
§ 21.4.2
© ISO/IEC 2011 – All rights reserved
643
ISO/IEC 14882:2011(E)
Table 66 — basic_string(const charT*, size_type, const Allocator&) effects Element data() size() capacity() 9 10
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()
Requires: s shall not be a null pointer. 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. Table 67 — basic_string(const charT*, const Allocator&) effects Element data() size() capacity()
11
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());
12
Requires: n < npos
13
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()); 14
Effects: If InputIterator is an integral type, equivalent to basic_string(static_cast<size_type>(begin), static_cast(end), a)
15
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());
16
Effects: Same as basic_string(il.begin(), il.end(), a).
§ 21.4.2
644
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
basic_string(const basic_string& str, const Allocator& alloc); basic_string(basic_string&& str, const Allocator& alloc); 17
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. Table 69 — basic_string(const basic_string&, const Allocator&) and basic_string(basic_string&&, const Allocator&) effects Element data()
size() capacity() get_allocator() 18
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
Throws: The second form throws nothing if alloc == str.get_allocator() unless the copy constructor for Allocator throws. basic_string& operator=(const basic_string& str);
19
Effects: If *this and str are not the same object, modifies *this as shown in Table 70.
20
If *this and str are the same object, the member has no effect.
21
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; 22
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 ]
23
If *this and str are the same object, the member has no effect.
24
Returns: *this Table 71 — operator=(const basic_string&&) effects Element data() size() capacity()
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()
§ 21.4.2
© ISO/IEC 2011 – All rights reserved
645
ISO/IEC 14882:2011(E)
basic_string& operator=(const charT* s); 25
Returns: *this = basic_string(s).
26
Remarks: Uses traits::length(). basic_string& operator=(charT c);
27
Returns: *this = basic_string(1,c). basic_string& operator=(initializer_list il);
28
Effects: *this = basic_string(il).
29
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(). size_type max_size() const noexcept;
4
Returns: The size of the largest possible string.
5
Complexity: constant time. § 21.4.4
646
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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().235 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.
21.4.5
basic_string element access
[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.data, str.size()).
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 append(1, c);
6
Returns: *this. basic_string& operator+=(initializer_list il);
7
Effects: Calls append(il.first(), il.size()).
8
Returns: *this. 21.4.6.2
basic_string::append
[string::append]
basic_string& append(const basic_string& str);
§ 21.4.6.2
648
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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);
16
Requires: [first,last) is a valid range.
17
Effects: Equivalent to append(basic_string(first, last)).
18
Returns: *this. basic_string& append(initializer_list il);
19
Effects: Calls append(il.begin(), il.size()).
20
*this. void push_back(charT c)
21
Effects: Equivalent to append(static_cast<size_type>(1), c).
§ 21.4.6.2
© ISO/IEC 2011 – All rights reserved
649
ISO/IEC 14882:2011(E)
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);
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);
§ 21.4.6.3
650
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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);
9
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;
§ 21.4.8.9
© ISO/IEC 2011 – All rights reserved
663
ISO/IEC 14882:2011(E)
— 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; template struct hash;
§ 21.6
666
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
template struct hash; template struct hash<wstring>; 1
Requires: the template specializations shall meet the requirements of class template hash (20.8.12).
21.7
Null-terminated sequence utilities
[c.strings]
1
Tables 74, 75, 76, 77, 78, and 79 describe headers , , , , (character conversions), and <cuchar>, respectively.
2
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:
3
The headers shall not define the types char16_t, char32_t, and wchar_t (2.12).
4
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);
both of which shall have the same behavior as the original declaration. 5
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);
both of which shall have the same behavior as the original declaration. 6
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);
both of which shall have the same behavior as the original declaration. 7
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);
both of which shall have the same behavior as the original declaration. 8
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);
both of which shall have the same behavior as the original declaration. 9
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);
both of which shall have the same behavior as the original declaration. 10
The function signature wcspbrk(const wchar_t*, const wchar_t*) shall be replaced by the two declarations: § 21.7
© ISO/IEC 2011 – All rights reserved
667
ISO/IEC 14882:2011(E)
const wchar_t* wcspbrk(const wchar_t* s1, const wchar_t* s2); wchar_t* wcspbrk( wchar_t* s1, const wchar_t* s2);
both of which shall have the same behavior as the original declaration. 11
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);
both of which shall have the same behavior as the original declaration. 12
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);
both of which shall have the same behavior as the original declaration. 13
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);
both of which shall have the same behavior as the original declaration. 14
The functions strerror and strtok are not required to avoid data races (17.6.5.9).
15
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
Name(s) isblank isalpha iscntrl
isdigit isgraph islower
isprint ispunct isspace
isupper isxdigit
§ 21.7
668
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
NULL mbstate_t
Name(s) WCHAR_MAX WCHAR_MIN wint_t size_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
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
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
§ 21.7
© ISO/IEC 2011 – All rights reserved
669
ISO/IEC 14882:2011(E)
Table 79 — Header <cuchar> synopsis Type Macros: Functions:
Name(s) __STDC_UTF_16__ __STDC_UTF_32__ mbrtoc16 c16rtomb mbrtoc32 c32rtomb
§ 21.7
670
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
22 22.1
Localization library
[localization]
General
[localization.general]
1
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.
2
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:
§ 22.2
© ISO/IEC 2011 – All rights reserved
671
ISO/IEC 14882:2011(E)
class ctype_base; 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.236
22.3 22.3.1
Locales
[locales]
Class locale
[locale]
namespace std { class locale { public: // types: 236) In this subclause, the type name struct tm is an incomplete type that is defined in .
§ 22.3.1
672
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
class facet; class id; typedef int category; 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
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.
2
Access to the facets of a locale is via two function templates, use_facet and has_facet.
3
[ 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
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.
7
In successive calls to a locale facet member function on a facet object installed in the same locale, the returned result shall be identical.
8
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 "*".
9
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
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.
§ 22.3.1.1.1
674
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
2
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. 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>
3
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.
4
An implementation is required to provide those specializations for facet templates identified as members of a category, and for those shown in Table 82.
5
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.
6
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; }; }
§ 22.3.1.1.2
© ISO/IEC 2011 – All rights reserved
675
ISO/IEC 14882:2011(E)
Table 82 — Required specializations Category collate ctype
monetary
numeric time
messages
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>
1
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.
2
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.
3
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.
4
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 {
§ 22.3.1.1.3
676
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
public: id(); void operator=(const id&) = delete; id(const id&) = delete; }; } 1
The class locale::id provides identification of a locale facet interface, used as an index for lookup and to encapsulate initialization.
2
[ 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 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);
§ 22.3.1.2
© ISO/IEC 2011 – All rights reserved
677
ISO/IEC 14882:2011(E)
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. 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-definedreturn value of locale::name. 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:
§ 22.3.1.4
678
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
use_facet< collate >(*this).compare (s1.data(), s1.data()+s1.size(), s2.data(), s2.data()+s2.size()) < 0; 6
[ 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
Convenience interfaces Character classification
[locale.convenience] [classification]
§ 22.3.3.1
© ISO/IEC 2011 – All rights reserved
679
ISO/IEC 14882:2011(E)
template template template template template template template template template template template template 1
bool bool bool bool bool bool bool bool bool bool bool bool
isspace (charT isprint (charT iscntrl (charT isupper (charT islower (charT isalpha (charT isdigit (charT ispunct (charT isxdigit(charT isalnum (charT isgraph (charT isblank (charT
c, c, c, c, c, c, c, c, c, c, c, c,
const const const const const const const const const const const const
locale& locale& locale& locale& locale& locale& locale& locale& locale& locale& locale& locale&
loc); loc); loc); loc); loc); loc); loc); 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).238 22.3.3.2 22.3.3.2.1
Conversions 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; 238) 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
680
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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);
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
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>.
4
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 from_bytes(char byte);
§ 22.3.3.2.2
© ISO/IEC 2011 – All rights reserved
681
ISO/IEC 14882:2011(E)
wide_string from_bytes(const char *ptr); wide_string from_bytes(const byte_string& str); wide_string 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 nul-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: — 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 nul-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,
§ 22.3.3.2.2
682
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
const wide_string& wide_err = wide_string()); 16
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
Buffer conversions
[conversions.buffer]
1
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.
2
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
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>.
4
An object of this class template stores: — bufptr — a pointer to its underlying byte stream buffer
§ 22.3.3.2.3
© ISO/IEC 2011 – All rights reserved
683
ISO/IEC 14882:2011(E)
— cvtptr — a pointer to the allocated conversion object (which is freed when the wbuffer_convert object is destroyed) — cvtstate — a conversion state object 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
Standard locale categories
[locale.categories]
1
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.
2
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.
3
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; 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; }
§ 22.4.8
© ISO/IEC 2011 – All rights reserved
723
ISO/IEC 14882:2011(E)
— end example ] 10
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.
11
[ 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]
1
Containers are objects that store other objects. They control allocation and deallocation of these objects through constructors, destructors, insert and erase operations.
2
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 ]
3
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 ]
4
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
728
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 96 — Container requirements Expression
Return type
X::value_type X::reference X::const_reference X::iterator
T
X::const_iterator
constant iterator type whose value type is T signed integer type
X::difference_type
X::size_type
Operational semantics
lvalue of T const lvalue of T iterator type whose value type is T
X u; X() X(a)
X u(a) X u = a;
X u(rv) X u = rv
X&
(&a)->∼X()
void
Complexity compile time compile time compile time
unsigned integer type
a = rv
Assertion/note pre-/post-condition Requires: T is Destructible
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 note: the destructor is applied to every element of a; all the memory is deallocated.
compile time
compile time
compile time
compile time
constant constant linear
linear
(Note B)
linear
linear
§ 23.2.1
© ISO/IEC 2011 – All rights reserved
729
ISO/IEC 14882:2011(E)
Table 96 — Container requirements (continued) Expression a.begin()
a.end()
a.cbegin() a.cend() a == b
Return type iterator; const_iterator for constant a iterator; const_iterator for constant a const_iterator const_iterator convertible to bool
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
Operational semantics
Assertion/note pre-/post-condition
Complexity constant
constant
const_cast<X const&>(a).begin(); const_cast<X const&>(a).end(); == is an equivalence Requires: T is relation. EqualityComparable 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. 5
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.
6
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();
7
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. 8
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.
9
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()
Return type iterator type whose value type is T iterator type whose value type is const T
a.crbegin();
reverse_iterator; const_reverse_iterator for constant a reverse_iterator; const_reverse_iterator for constant a const_reverse_iterator
a.crend();
const_reverse_iterator
a.rend()
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(); const_cast<X const&>(a).rend();
constant constant
§ 23.2.1
© ISO/IEC 2011 – All rights reserved
731
ISO/IEC 14882:2011(E)
10
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
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.
12
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
Return type
a < b
convertible to bool
a > b
convertible to bool convertible to bool convertible to bool
a = b
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. 13
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 and given an lvalue m of type A, a pointer p of type T*, an expression v of type 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.) — T is CopyInsertable into X means that the following expression is well-formed: allocator_traits::construct(m, p, v);
§ 23.2.1
732
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
— 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);
[ 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 ] 14
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); X(t, m) X u(t, m);
X(rv) X u(rv)
X(rv, m) X u(rv, m);
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 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
constant
constant linear
constant
constant if m == rv.get_allocator(), otherwise linear
§ 23.2.1
© ISO/IEC 2011 – All rights reserved
733
ISO/IEC 14882:2011(E)
Table 99 — Allocator-aware container requirements (continued) Expression
Return type
a = t
X&
a = rv
X&
a.swap(b)
void
23.2.2
Container data races
Assertion/note pre-/post-condition 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
linear
constant
[container.requirements.dataraces]
1
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[].
2
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.
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
Sequence containers
[sequence.reqmts]
1
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).
2
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.
3
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 § 23.2.3
734
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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&&. 4
The complexities of the expressions are sequence dependent. Table 100 — Sequence container requirements (in addition to container) Expression
Return type
X(n, t) X a(n, t)
X(i, j) X a(i, j)
X(il); a = il;
X&
a.emplace(p, args);
iterator
a.insert(p,t)
iterator
a.insert(p,rv)
iterator
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()) 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.
§ 23.2.3
© ISO/IEC 2011 – All rights reserved
735
ISO/IEC 14882:2011(E)
Table 100 — Sequence container requirements (in addition to container) (continued) Expression
Return type
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
a.assign(i,j)
void
a.assign(il) a.assign(n,t)
void void
Assertion/note pre-/post-condition 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 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.
5
iterator and const_iterator types for sequence containers shall be at least of the forward iterator category.
6
The iterator returned from a.insert(p, t) points to the copy of t inserted into a.
7
The iterator returned from a.insert(p, rv) points to the copy of rv inserted into a.
§ 23.2.3
736
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
8
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.
9
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.
10
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.
11
The iterator returned from a.emplace(p, args) points to the new element constructed from args into a.
12
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.
13
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.
14
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 // such as replace() 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
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.
16
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
Operational semantics *a.begin()
Container basic_string, array, deque, forward_list, list, vector
§ 23.2.3
© ISO/IEC 2011 – All rights reserved
737
ISO/IEC 14882:2011(E)
Table 101 — Optional sequence container operations (continued) Expression a.back()
Return type reference; const_reference for constant a
a.emplace_front(args)
void
a.emplace_back(args)
void
Operational semantics { auto tmp = a.end(); --tmp; return *tmp; }
Container basic_string, array, deque, list, vector Prepends an object of type T deque, constructed with forward_std::forward(args).... list, list Requires: T shall be EmplaceConstructible into X from args. Appends an object of type T deque, list, 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.
a.push_back(rv)
void
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)
deque, forward_list, list deque, forward_list, list basic_string, deque, list, vector basic_string, deque, list, vector deque, forward_list, list basic_string, deque, list, vector basic_string, array, deque, vector
§ 23.2.3
738
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 101 — Optional sequence container operations (continued) Expression a.at(n)
17
Return type reference; const_reference for constant a
Operational semantics *(a.begin() + n)
Container 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
Associative containers
[associative.reqmts]
1
Associative containers provide fast retrieval of data based on keys. The library provides four basic kinds of associative containers: set, multiset, map and multimap.
2
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 type T with the Key. The object of type Compare is called the comparison object of a container.
3
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.
4
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.
5
For set and multiset the value type is the same as the key type. For map and multimap it is equal to pair. Keys in an associative container are immutable.
6
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 ]
7
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 ]
8
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
§ 23.2.4
© ISO/IEC 2011 – All rights reserved
739
ISO/IEC 14882:2011(E)
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
Key
mapped_type (map and multimap only) X::key_compare X::value_compare
T
Assertion/note pre-/post-condition Requires: Key is Destructible. Requires: T is Destructible.
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. 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
compile time
X(c) X a(c);
X() X a;
X(i,j,c) X a(i,j,c);
X(i,j) X a(i,j);
Return type
Complexity compile time compile time
constant
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
§ 23.2.4
740
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 102 — Associative container requirements (in addition to container) (continued) Expression
Return type
Assertion/note pre-/post-condition X(il); Same as X(il.begin(), il.end()). a = il X& Requires: T 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. a.key_X::key_returns the comparison object comp() compare out of which a was constructed. a.value_X::value_returns an object of comp() compare value_compare constructed out of the comparison object a_uniq. pair EmplaceConstructible into X from args. Effects: Inserts a T 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. a_eq. iterator Requires: T shall be emplace(args) EmplaceConstructible into X from args. Effects: Inserts a T 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.
Complexity 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
logarithmic
logarithmic
§ 23.2.4
© ISO/IEC 2011 – All rights reserved
741
ISO/IEC 14882:2011(E)
Table 102 — Associative container requirements (in addition to container) (continued) Expression
Return type
Assertion/note Complexity pre-/post-condition 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. a_uniq. pair rvalue expression, T shall be MoveInsertable into X; otherwise, T 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. logarithmic a_iterator Requires: If t is a non-const eq.insert(t) rvalue expression, T shall be MoveInsertable into X; otherwise, T 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.
§ 23.2.4
742
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 102 — Associative container requirements (in addition to container) (continued) Expression
Return type
a.insert( p, t)
iterator
a.insert( i, j)
void
a.insert(il) void
a.erase(k)
size_type
a.erase(q)
iterator
a.erase( q1, q2)
iterator
Assertion/note pre-/post-condition Requires: If t is a non-const rvalue expression, T shall be MoveInsertable into X; otherwise, T 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. Requires: T 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.
Complexity logarithmic in general, but amortized constant if t is inserted right before p.
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).
§ 23.2.4
© ISO/IEC 2011 – All rights reserved
743
ISO/IEC 14882:2011(E)
Table 102 — Associative container requirements (in addition to container) (continued) Expression
Return type
a.clear()
void
a.find(k)
iterator; const_iterator for constant a. size_type
a.count(k) a.lower_bound(k)
a.upper_bound(k)
a.equal_range(k)
Assertion/note pre-/post-condition 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 iterator; returns an iterator pointing to const_the first element with key not iterator for less than k, or a.end() if such constant a. an element is not found. returns an iterator pointing to iterator; the first element with key const_greater than k, or a.end() if iterator for such an element is not found. constant a. pair; a.upper_bound(k)). pair for constant a.
Complexity linear in a.size().
logarithmic
log(a.size()) + a.count(k) logarithmic
logarithmic
logarithmic
9
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.
10
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
1
Exception safety guarantees
[associative.reqmts.except]
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). § 23.2.4.1
744
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
2
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.
3
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).
23.2.5
Unordered associative containers
[unord.req]
1
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.
2
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.
3
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.
4
A hash function is a function object that takes a single argument of type Key and returns a value of type std::size_t.
5
Two values k1 and k2 of type Key are considered equivalent if the container’s key_equal function object returns true when passed those values. If k1 and k2 are equivalent, the hash function shall return the same value for both. [ Note: Thus, when an unordered associative container is instantiated with a non-default Pred parameter it usually needs a non-default Hash parameter as well. — end note ]
6
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.
7
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.
8
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.
9
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 ]
10
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 § 23.2.5
© ISO/IEC 2011 – All rights reserved
745
ISO/IEC 14882:2011(E)
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
Return type Key
X::mapped_type (unordered_map and unordered_multimap only) X::hasher
T
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)
Hash
Assertion/note pre-/post-condition Requires: Key shall be Destructible. Requires: T is Destructible.
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.
Complexity compile time compile time
compile time
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)
§ 23.2.5
746
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
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 )
§ 23.2.5
© ISO/IEC 2011 – All rights reserved
747
ISO/IEC 14882:2011(E)
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
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()).
§ 23.2.5
748
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
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: T 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: T shall be EmplaceConstructible into X from args. Effects: Inserts a T 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: T shall be EmplaceConstructible into X from args. Effects: Inserts a T 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()).
§ 23.2.5
© ISO/IEC 2011 – All rights reserved
749
ISO/IEC 14882:2011(E)
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
Assertion/note pre-/post-condition Requires: T 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, T shall be MoveInsertable into X; otherwise, T 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, T shall be MoveInsertable into X; otherwise, T 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()).
§ 23.2.5
750
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 103 — Unordered associative container requirements (in addition to container) (continued) Expression a.insert(q, t)
Return type iterator
Assertion/note pre-/post-condition Requires: If t is a non-const rvalue expression, T shall be MoveInsertable into X; otherwise, T 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: T 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).
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.
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()).
§ 23.2.5
© ISO/IEC 2011 – All rights reserved
751
ISO/IEC 14882:2011(E)
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
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
§ 23.2.5
752
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 103 — Unordered associative container requirements (in addition to container) (continued) 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.
11
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 refinement263 of the partition into equivalent-key groups produced by Pred.
12
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. 263) Equality comparison is a refinement of partitioning if no two objects that compare equal fall into different partitions.
§ 23.2.5
© ISO/IEC 2011 – All rights reserved
753
ISO/IEC 14882:2011(E)
13
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.
14
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]
1
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).
2
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.
3
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).
4
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
Sequence containers
[sequences]
In general
[sequences.general]
1
The headers <array>, <deque>, , <list>, and define template classes that meet the requirements for sequence containers.
2
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;
§ 23.3.1
754
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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; template <size_t I, class T, size_t N> const T& get(const array&) noexcept; }
Header <deque> synopsis namespace std { #include 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 namespace std { #include template class list; 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 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 § 23.3.2.1
756
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 1
Return type: integral constant expression.
2
Value: N 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
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.
§ 23.3.3.1
© ISO/IEC 2011 – All rights reserved
759
ISO/IEC 14882:2011(E)
2
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.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;
§ 23.3.3.1
760
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.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& x, const deque& y); template bool operator< (const deque& x, const deque& y); template bool operator!=(const deque& x, const deque& y);
§ 23.3.3.1
© ISO/IEC 2011 – All rights reserved
761
ISO/IEC 14882:2011(E)
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& y); template bool operator>=(const forward_list& x, const forward_list& y); template bool operator (const list& 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
Class template vector Class template vector overview
[vector] [vector.overview]
1
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& x, const vector& y); template bool operator>=(const vector& x, const vector& y); template bool operator max_size().266
5
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();
6
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 swap(vector& x);
7
Effects: Exchanges the contents and capacity() of *this with that of x.
8
Complexity: Constant time. void resize(size_type sz);
9
10
Effects: If sz size()) insert(end(), sz-size(), c); else if (sz < size()) erase(begin()+sz, end()); else ; // do nothing 266) reserve() uses Allocator::allocate() which may throw an appropriate exception.
§ 23.3.6.3
782
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
12
Requires: If an exception is thrown other than by the move constructor of a non-CopyInsertable T there are no effects. 23.3.6.4
vector data
T* const T*
data() noexcept; data() const noexcept;
[vector.data]
1
Returns: A pointer such that [data(),data() + size()) is a valid range. For a non-empty vector, data() == &front().
2
Complexity: Constant time. 23.3.6.5
vector modifiers
[vector.modifiers]
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); template void emplace_back(Args&&... args); template iterator emplace(const_iterator position, Args&&... args); void push_back(const T& x); void push_back(T&& x); 1
Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid. If an exception is thrown other than by the copy constructor, move constructor, assignment operator, or move assignment operator of T or by any InputIterator operation there are no effects. If an exception is thrown by the move constructor of a non-CopyInsertable T, the effects are unspecified.
2
Complexity: The complexity is linear in the number of elements inserted plus the distance to the end of the vector. iterator erase(const_iterator position); iterator erase(const_iterator first, const_iterator last);
3
Effects: Invalidates iterators and references at or after the point of the erase.
4
Complexity: The destructor of T is called the number of times equal to the number of the elements erased, but the move assignment operator of T is called the number of times equal to the number of elements in the vector after the erased elements.
5
Throws: Nothing unless an exception is thrown by the copy constructor, move constructor, assignment operator, or move assignment operator of T. 23.3.6.6
vector specialized algorithms
[vector.special]
template void swap(vector& x, vector& y); 1
Effects: x.swap(y);
§ 23.3.6.6
© ISO/IEC 2011 – All rights reserved
783
ISO/IEC 14882:2011(E)
23.3.7 1
Class vector
[vector.bool]
To optimize space allocation, a specialization of vector for bool elements is provided: namespace std { template class vector { public: // types: typedef bool 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 bool value_type; typedef Allocator allocator_type; typedef implementation-defined pointer; typedef implementation-defined const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // bit reference: class reference { friend class vector; reference() noexcept; public: ~reference(); operator bool() const noexcept; reference& operator=(const bool x) noexcept; reference& operator=(const reference& x) noexcept; void flip() noexcept; // flips the bit }; // construct/copy/destroy: explicit vector(const Allocator& = Allocator()); explicit vector(size_type n, const bool& value = bool(), const Allocator& = Allocator()); template vector(InputIterator first, InputIterator last, const Allocator& = Allocator()); vector(const vector& x); vector(vector&& x); vector(const vector&, const Allocator&); vector(vector&&, const Allocator&); vector(initializer_list, const Allocator& = Allocator())); ~vector(); vector& operator=(const vector& x); vector& operator=(vector&& x); vector operator=(initializer_list); template void assign(InputIterator first, InputIterator last); void assign(size_type n, const bool& t); void assign(initializer_list; allocator_type get_allocator() const noexcept; // iterators: iterator
begin() noexcept;
§ 23.3.7
784
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
const_iterator iterator const_iterator reverse_iterator const_reverse_iterator reverse_iterator const_reverse_iterator
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;
// capacity: size_type size() const noexcept; size_type max_size() const noexcept; void resize(size_type sz, bool c = false); size_type capacity() const noexcept; bool empty() const noexcept; void reserve(size_type n); void shrink_to_fit(); // element access: reference operator[](size_type n); const_reference operator[](size_type n) const; const_reference at(size_type n) const; reference at(size_type n); reference front(); const_reference front() const; reference back(); const_reference back() const; // modifiers: void push_back(const bool& x); void pop_back(); iterator insert(const_iterator position, const bool& x); iterator insert (const_iterator position, size_type n, const bool& x); template iterator insert(const_iterator position, InputIterator first, InputIterator last); iterator insert(const_iterator position, initializer_list il); iterator erase(const_iterator position); iterator erase(const_iterator first, const_iterator last); void swap(vector&); static void swap(reference x, reference y) noexcept; void flip() noexcept; // flips all bits void clear() noexcept; }; } 2
Unless described below, all operations have the same requirements and semantics as the primary vector template, except that operations dealing with the bool value type map to bit values in the container storage and allocator_traits::construct (20.6.8.2) is not used to construct these values.
§ 23.3.7
© ISO/IEC 2011 – All rights reserved
785
ISO/IEC 14882:2011(E)
3
There is no requirement that the data be stored as a contiguous allocation of bool values. A space-optimized representation of bits is recommended instead.
4
reference is a class that simulates the behavior of references of a single bit in vector. The conversion operator returns true when the bit is set, and false otherwise. The assignment operator sets the bit when the argument is (convertible to) true and clears it otherwise. flip reverses the state of the bit. void flip() noexcept;
5
Effects: Replaces each element in the container with its complement. static void swap(reference x, reference y) noexcept;
6
Effects: exchanges the contents of x and y as if by bool b = x; x = y; y = b; template struct hash;
7
Requires: the template specialization shall meet the requirements of class template hash (20.8.12).
23.4 23.4.1 1
Associative containers In general
[associative] [associative.general]
The header <map> defines the class templates map and multimap; the header <set> 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
§ 23.4.3
© ISO/IEC 2011 – All rights reserved
787
ISO/IEC 14882:2011(E)
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;
§ 23.4.4.1
788
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef
pair value_type; Compare key_compare; Allocator allocator_type; value_type& reference; const value_type& const_reference; 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;
§ 23.4.4.1
© ISO/IEC 2011 – All rights reserved
789
ISO/IEC 14882:2011(E)
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 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
§ 23.4.4.1
790
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
equal_range(const key_type& x); pair equal_range(const key_type& x) const; }; 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;
§ 23.4.5.1
© ISO/IEC 2011 – All rights reserved
793
ISO/IEC 14882:2011(E)
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); } }; // 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
empty() const noexcept;
§ 23.4.5.1
794
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
size_type size_type
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 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);
§ 23.4.5.1
© ISO/IEC 2011 – All rights reserved
795
ISO/IEC 14882:2011(E)
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.2
© ISO/IEC 2011 – All rights reserved
803
ISO/IEC 14882:2011(E)
// 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& const unordered_multimap& template bool operator!=(const unordered_multimap& const unordered_multimap& } // namespace std
23.5.3
Header synopsis
a, b); a, b);
[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);
§ 23.5.3
804
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
a, b); a, b);
Class template unordered_map Class template unordered_map overview
[unord.map] [unord.map.overview]
1
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.
2
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 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.
3
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_type::pointer pointer; typedef typename allocator_type::const_pointer const_pointer; typedef typename allocator_type::reference reference; typedef typename allocator_type::const_reference const_reference; typedef implementation-defined size_type;
§ 23.5.4.1
© ISO/IEC 2011 – All rights reserved
805
ISO/IEC 14882:2011(E)
typedef implementation-defined typedef typedef typedef typedef
implementation-defined implementation-defined implementation-defined implementation-defined
difference_type; 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()); ~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);
§ 23.5.4.1
806
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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; 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.1
© ISO/IEC 2011 – All rights reserved
807
ISO/IEC 14882:2011(E)
}
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.3
unordered_map element access
[unord.map.elem]
mapped_type& operator[](const key_type& k); mapped_type& operator[](key_type&& k); 1
Requires: mapped_type shall be DefaultConstructible. For the first operator, key_type shall be CopyConstructible. 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.modifers]
template pair insert(P&& obj);
§ 23.5.4.4
808
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.5 23.5.5.1
Class template unordered_multimap Class template unordered_multimap overview
[unord.multimap] [unord.multimap.overview]
1
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.
2
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.
3
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_type::pointer pointer; typedef typename allocator_type::const_pointer const_pointer; typedef typename allocator_type::reference reference; typedef typename allocator_type::const_reference 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&&); 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;
§ 23.5.5.1
810
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
// 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; // 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);
§ 23.5.5.1
© ISO/IEC 2011 – All rights reserved
811
ISO/IEC 14882:2011(E)
}; 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.
4
Complexity: Average case linear, worst case quadratic. 23.5.5.3
unordered_multimap modifiers
[unord.multimap.modifers]
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.
§ 23.5.5.3
812
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
Class template unordered_set
[unord.set]
Class template unordered_set overview
[unord.set.overview]
1
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.
2
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.
3
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 class unordered_set { public: // types typedef Key typedef Key typedef Hash typedef Pred typedef Allocator typedef typename allocator_type::pointer typedef typename allocator_type::const_pointer typedef typename allocator_type::reference
key_type; value_type; hasher; key_equal; allocator_type; pointer; const_pointer; reference;
§ 23.5.6.1
© ISO/IEC 2011 – All rights reserved
813
ISO/IEC 14882:2011(E)
typedef typename allocator_type::const_reference 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_set(size_type n = implementation-defined, 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 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); pair insert(value_type&& obj); iterator insert(const_iterator hint, const value_type& obj);
§ 23.5.6.1
814
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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]
§ 23.5.6.2
© ISO/IEC 2011 – All rights reserved
815
ISO/IEC 14882:2011(E)
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
Class template unordered_multiset Class template unordered_multiset overview
[unord.multiset] [unord.multiset.overview]
1
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.
2
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 are both Key. The iterator and const_iterator types are both const iterator types. It is unspecified whether they are the same type.
3
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
§ 23.5.7.1
816
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
class unordered_multiset { public: // types typedef Key typedef Key typedef Hash typedef Pred typedef Allocator typedef typename allocator_type::pointer typedef typename allocator_type::const_pointer typedef typename allocator_type::reference typedef typename allocator_type::const_reference 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 = implementation-defined, 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&&); 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
begin() noexcept;
§ 23.5.7.1
© ISO/IEC 2011 – All rights reserved
817
ISO/IEC 14882:2011(E)
const_iterator iterator const_iterator const_iterator const_iterator
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; // 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.7.1
818
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.6 23.6.1
Container adaptors In general
[container.adaptors] [container.adaptors.general]
1
The headers and <stack> define the container adaptors queue, priority_queue, and stack. These container adaptors meet the requirements for sequence containers.
2
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. § 23.6.1
© ISO/IEC 2011 – All rights reserved
819
ISO/IEC 14882:2011(E)
3
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);
§ 23.6.3.4
822
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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, 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);
§ 23.6.4
© ISO/IEC 2011 – All rights reserved
823
ISO/IEC 14882:2011(E)
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.2
1
priority_queue constructors with allocators
[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
§ 23.6.4.2
824
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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); 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)));
§ 23.6.4.4
© ISO/IEC 2011 – All rights reserved
825
ISO/IEC 14882:2011(E)
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());
2
Effects: Initializes c with std::move(cont). 23.6.5.4
1
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
§ 23.6.5.4
© ISO/IEC 2011 – All rights reserved
827
ISO/IEC 14882:2011(E)
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. 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
828
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
24 24.1
Iterators library
[iterators]
General
[iterators.general]
1
This Clause describes components that C++ programs may use to perform iterations over containers (Clause 23), streams (27.7), and stream buffers (27.6).
2
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
Subclause Requirements Iterator primitives Predefined iterators Stream iterators
Header(s)
Iterator requirements
[iterator.requirements]
In general
[iterator.requirements.general]
1
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.
2
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
→ 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.
§ 24.2.1
© ISO/IEC 2011 – All rights reserved
829
ISO/IEC 14882:2011(E)
4
Iterators that further satisfy the requirements of output iterators are called mutable iterators. Nonmutable iterators are referred to as constant iterators.
5
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.
6
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.
7
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.
8
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.
9
Destruction of an iterator may invalidate pointers and references previously obtained from that iterator.
10
An invalid iterator is an iterator that may be singular.267
11
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
Iterator
[iterator.iterators]
1
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).)
2
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.
267) This definition applies to pointers, since pointers are iterators. The effect of dereferencing an iterator that has been invalidated is undefined.
§ 24.2.2
830
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 106 — Iterator requirements Expression *r ++r
24.2.3
Return type
Operational semantics
reference X&
Assertion/note pre-/post-condition pre: r is dereferenceable.
Input iterators
[input.iterators]
1
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.
2
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 != b
*a
3
Return type contextually convertible to bool convertible to T
a->m ++r
X&
(void)r++ *r++
convertible to T
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 substi§ 24.2.3
© ISO/IEC 2011 – All rights reserved
831
ISO/IEC 14882:2011(E)
tution 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
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. 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. § 24.2.5
832
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
2
The domain of == for forward iterators is that of iterators over the same underlying sequence.
3
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 ] Table 109 — Forward iterator requirements (in addition to input iterator) Expression
Return type
r++
convertible to const X&
*r++
reference
Operational semantics { X tmp = r; ++r; return tmp; }
Assertion/note pre-/post-condition
5
If a and b are equal, then either a and b are both dereferenceable or else neither is dereferenceable.
6
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
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
Return type
--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; }
§ 24.2.6
© ISO/IEC 2011 – All rights reserved
833
ISO/IEC 14882:2011(E)
2
[ Note: Bidirectional iterators allow algorithms to move iterators backward as well as forward. — end note ]
24.2.7 1
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. 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;
§ 24.3
834
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
template struct iterator; struct struct struct struct struct
input_iterator_tag { }; output_iterator_tag { }; forward_iterator_tag: public input_iterator_tag { }; bidirectional_iterator_tag: public forward_iterator_tag { }; 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
§ 24.3
© ISO/IEC 2011 – All rights reserved
835
ISO/IEC 14882:2011(E)
reverse_iterator operator+( typename reverse_iterator::difference_type n, const reverse_iterator& x); template class back_insert_iterator; template 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(const Iterator& i); // 24.6, stream iterators: template class istream_iterator; template bool operator==(const istream_iterator& x, const istream_iterator& y); template
§ 24.3
836
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
bool operator!=(const istream_iterator& x, const istream_iterator& y); template class ostream_iterator; template 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.6.5, 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
may be defined as void. § 24.4.1
© ISO/IEC 2011 – All rights reserved
837
ISO/IEC 14882:2011(E)
2
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; }; }
3
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; };
— end note ] 5
[ 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) {
§ 24.4.1
838
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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; };
§ 24.4.3
© ISO/IEC 2011 – All rights reserved
839
ISO/IEC 14882:2011(E)
Typically, however, it would be easier to derive BinaryTreeIterator from iterator. — end example ] 3
[ 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 } template void evolve(RandomAccessIterator first, RandomAccessIterator last, random_access_iterator_tag) { // more efficient, but less generic algorithm }
— end example ] 4
[ 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.
§ 24.4.4
840
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.5
Iterator adaptors
24.5.1 1
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);
§ 24.5.1.1
© ISO/IEC 2011 – All rights reserved
841
ISO/IEC 14882:2011(E)
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
reverse_iterator requirements
[reverse.iter.requirements]
1
The template parameter Iterator shall meet all the requirements of a Bidirectional Iterator (24.2.6).
2
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). is
§ 24.5.1.2
842
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
referenced in a way that requires instantiation (14.7.1). 24.5.1.3
reverse_iterator operations
24.5.1.3.1
reverse_iterator constructor
[reverse.iter.ops] [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.2
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.5
© ISO/IEC 2011 – All rights reserved
843
ISO/IEC 14882:2011(E)
24.5.1.3.6
[reverse.iter.op++]
operator++
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
[reverse.iter.op--]
operator--
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.8
[reverse.iter.op+]
operator+
reverse_iterator operator+(typename reverse_iterator::difference_type n) const; 1
Returns: reverse_iterator(current-n). 24.5.1.3.9
[reverse.iter.op+=]
operator+=
reverse_iterator& operator+=(typename reverse_iterator::difference_type n); 1
Effects: current -= n;
2
Returns: *this. 24.5.1.3.10
[reverse.iter.op-]
operator-
reverse_iterator operator-(typename reverse_iterator::difference_type n) const; 1
Returns: reverse_iterator(current+n).
§ 24.5.1.3.10
844
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.16
© ISO/IEC 2011 – All rights reserved
845
ISO/IEC 14882:2011(E)
24.5.1.3.17
[reverse.iter.op>=]
operator>=
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*();
§ 24.5.2.2.3
© ISO/IEC 2011 – All rights reserved
847
ISO/IEC 14882:2011(E)
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.2
front_insert_iterator::operator=
[front.insert.iter.op=]
front_insert_iterator& operator=(const typename Container::value_type& value);
§ 24.5.2.4.2
848
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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); }; template insert_iterator inserter(Container& x, typename Container::iterator i);
§ 24.5.2.5
© ISO/IEC 2011 – All rights reserved
849
ISO/IEC 14882:2011(E)
}
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.2.6.5
850
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
24.5.3
Move iterators
[move.iterators]
1
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.
2
[ Example: 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
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&&
[move.iterator]
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==(
§ 24.5.3.1
© ISO/IEC 2011 – All rights reserved
851
ISO/IEC 14882:2011(E)
const move_iterator& x, const template bool operator!=( const move_iterator& x, const template bool operator=( const move_iterator& x, const
move_iterator& y);
move_iterator& y);
move_iterator& y);
move_iterator& y);
move_iterator& y);
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(const 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 24.5.3.3.1
move_iterator operations
[move.iter.ops]
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=]
§ 24.5.3.3.2
852
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.4
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.7
© ISO/IEC 2011 – All rights reserved
853
ISO/IEC 14882:2011(E)
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.11
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(). template move_iterator operator+( typename move_iterator::difference_type n, const move_iterator& x);
2
Returns: x + n. template move_iterator make_move_iterator(const 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
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. § 24.6.1
© ISO/IEC 2011 – All rights reserved
855
ISO/IEC 14882:2011(E)
2
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& istream_iterator private: basic_istream* in_stream; // T value; // };
operator++(); operator++(int); exposition only 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;
§ 24.6.1.1
856
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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. 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;
§ 24.6.3.5
860
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
[istreambuf.iterator::op==]
operator==
template bool operator==(const istreambuf_iterator& a, const istreambuf_iterator& b); 1
Returns: a.equal(b). 24.6.3.7
[istreambuf.iterator::op!=]
operator!=
template bool operator!=(const istreambuf_iterator& a, const istreambuf_iterator& b); 1
Returns: !a.equal(b).
24.6.4
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.
§ 24.6.4.1
© ISO/IEC 2011 – All rights reserved
861
ISO/IEC 14882:2011(E)
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. 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.6.5 1
range access
[iterator.range]
In addition to being available via inclusion of the header, the function templates in 24.6.5 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.6.5
862
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
25 25.1
Algorithms library
[algorithms]
General
[algorithms.general]
1
This Clause describes components that C++ programs may use to perform algorithmic operations on containers (Clause 23) and other sequences.
2
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
§ 25.1
© ISO/IEC 2011 – All rights reserved
863
ISO/IEC 14882:2011(E)
ForwardIterator1 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,
§ 25.1
864
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
ForwardIterator2 first2, BinaryPredicate pred); 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,
§ 25.1
© ISO/IEC 2011 – All rights reserved
865
ISO/IEC 14882:2011(E)
OutputIterator result, UnaryOperation op); 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
§ 25.1
866
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
OutputIterator unique_copy(InputIterator first, InputIterator last, 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:
§ 25.1
© ISO/IEC 2011 – All rights reserved
867
ISO/IEC 14882:2011(E)
template 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,
§ 25.1
868
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
const T& value, Compare comp); 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
§ 25.1
© ISO/IEC 2011 – All rights reserved
869
ISO/IEC 14882:2011(E)
OutputIterator set_union(InputIterator1 first1, InputIterator1 last1, 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
§ 25.1
870
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
void pop_heap(RandomAccessIterator first, RandomAccessIterator last, 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);
§ 25.1
© ISO/IEC 2011 – All rights reserved
871
ISO/IEC 14882:2011(E)
template 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
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.
4
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.
5
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). § 25.1
872
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
6
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 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 ]
7
Both in-place and copying versions are provided for certain algorithms.268 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).
8
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.
9
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.
10
[ 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 ]
11
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.
12
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 25.2.1
Non-modifying sequence operations All of
[alg.nonmodifying] [alg.all_of ]
template bool all_of(InputIterator first, InputIterator last, Predicate pred); 268) 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.1
© ISO/IEC 2011 – All rights reserved
873
ISO/IEC 14882:2011(E)
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 ]
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);
§ 25.2.5
874
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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); 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]
§ 25.2.8
© ISO/IEC 2011 – All rights reserved
875
ISO/IEC 14882:2011(E)
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
Count
[alg.count]
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]
§ 25.2.11
876
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
[alg.is_permutation]
template bool is_permutation(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2); 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. § 25.2.13
© ISO/IEC 2011 – All rights reserved
877
ISO/IEC 14882:2011(E)
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.3
Mutating sequence operations
25.3.1
[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.
§ 25.3.1
878
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
Complexity: Exactly last - first applications of the corresponding predicate.
11
Remarks: Stable. template BidirectionalIterator2 copy_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result);
12
Effects: Copies elements in the range [first,last) into the range [result - (last-first),result ) starting from last - 1 and proceeding to first.269 For each positive integer n 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. 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
898
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 32 (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);
§ 25.4.9
© ISO/IEC 2011 – All rights reserved
899
ISO/IEC 14882:2011(E)
template bool next_permutation(BidirectionalIterator first, BidirectionalIterator last, Compare comp); 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:
Name(s) size_t bsearch qsort
2
The contents are the same as the Standard C library header <stdlib.h> with the following exceptions:
3
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 *));
§ 25.5
900
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
both of which have the same behavior as the original declaration. 4
The function signature: 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
© ISO/IEC 2011 – All rights reserved
901
ISO/IEC 14882:2011(E)
26 26.1
Numerics library
[numerics]
General
[numerics.general]
1
This Clause describes components that C++ programs may use to perform seminumerical operations.
2
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
Header(s)
Numeric type requirements
[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:272 — 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. 272) In other words, value types. These include arithmetic types, pointers, the library class complex, and instantiations of valarray for value types.
§ 26.2
902
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
If any operation on T throws an exception the effects are undefined.
3
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.
4
[ 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
§ 26.3.1
© ISO/IEC 2011 – All rights reserved
903
ISO/IEC 14882:2011(E)
FE_INVALID FE_OVERFLOW FE_UNDERFLOW FE_DOWNWARD FE_TONEAREST FE_TOWARDZERO FE_UPWARD FE_DFL_ENV 2
The header defines all functions, types, and macros the same as Clause 7.6 of the C standard.
3
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 ]
4
A separate floating-point environment shall be maintained for each thread. Each function accesses the environment corresponding to its calling thread.
26.4
Complex numbers
[complex.numbers]
1
The header defines a class template, and numerous functions for representing and manipulating complex numbers.
2
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).
3
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.
4
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
§ 26.4.1
904
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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&, 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>&);
}; }
§ 26.4.2
906
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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; 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 complex<X>&); template complex<double>& operator+=(const complex<X>&); template complex<double>& operator-=(const complex<X>&);
§ 26.4.3
© ISO/IEC 2011 – All rights reserved
907
ISO/IEC 14882:2011(E)
template complex<double>& operator*=(const complex<X>&); template complex<double>& operator/=(const complex<X>&); }; template class complex { public: typedef long double value_type; 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]
§ 26.4.5
908
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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. 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
© ISO/IEC 2011 – All rights reserved
909
ISO/IEC 14882:2011(E)
3
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);
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. § 26.4.6
910
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
template basic_ostream& operator(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;
§ 26.6.2.6
© ISO/IEC 2011 – All rights reserved
967
ISO/IEC 14882:2011(E)
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.7
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.7
968
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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;
3
Returns: The number of elements in the array.
4
Complexity: constant time. 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
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&);
§ 26.6.3.2
© ISO/IEC 2011 – All rights reserved
971
ISO/IEC 14882:2011(E)
template valarray operator||(const valarray&, const T&); template valarray operator||(const T&, const valarray&); 4
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.
5
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);
§ 26.6.4.1
972
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
size_t start() const; size_t size() const; size_t stride() const; }; } 1
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.287 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
operator= (const operator*= (const operator/= (const operator%= (const operator+= (const operator-= (const operator^= (const operator&= (const operator|= (const operator=(const valarray&) 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
}; } 1
The slice_array template is a helper template used by the slice subscript operator slice_array valarray::operator[](slice);
It has reference semantics to a subset of an array specified by a slice object. 2
[ 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]
§ 26.6.6.1
974
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.
2
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
where the multidimensional indices ij range in value from 0 to lij − 1. 3
[ 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 , (0, 0, (0, 0, (0, 0, (0, 1, (0, 1, (0, 1, (0, 2, (0, 2, (0, 2, (0, 3, (0, 3, (0, 3, (1, 0, (1, 0, ... (1, 3,
k) 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1,
= 3), 4), 5), 7), 8), 9), 11), 12), 13), 15), 16), 17), 22), 23),
2,
36)
§ 26.6.6.1
© ISO/IEC 2011 – All rights reserved
975
ISO/IEC 14882:2011(E)
That is, the highest-ordered index turns fastest. — end example ] 4
It is possible to have degenerate generalized slices in which an address is repeated.
5
[ 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, ...
0, 0, 0, 1, 1, 1,
0, 1, 2, 0, 1, 2,
3), 4), 5), 4), 5), 6),
— end example ] 6
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.2
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
operator= operator*= operator/= operator%= operator+= operator-=
(const (const (const (const (const (const
valarray&) valarray&) valarray&) valarray&) valarray&) valarray&)
const; const; const; const; const; const;
§ 26.6.7.1
976
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
void void void void void
operator^= (const operator&= (const operator|= (const operator=(const
valarray&) valarray&) valarray&) valarray&) valarray&)
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.2
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.7.4
© ISO/IEC 2011 – All rights reserved
977
ISO/IEC 14882:2011(E)
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; mask_array() = delete;
// as implied by declaring copy constructor above
}; } 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
mask_array computed assignment
operator*= operator/= operator%= operator+= operator-= operator^= operator&=
(const (const (const (const (const (const (const
valarray&) valarray&) valarray&) valarray&) valarray&) valarray&) valarray&)
[mask.array.comp.assign]
const; const; const; const; const; const; const;
§ 26.6.8.3
978
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
void operator|= (const valarray&) const; void operator=(const valarray&) 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 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 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;
indirect_array(const indirect_array&); ~indirect_array(); const indirect_array& operator=(const indirect_array&) const; void operator=(const T&) const; indirect_array() = delete;
// as implied by declaring copy constructor above
}; } 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]
§ 26.6.9.2
© ISO/IEC 2011 – All rights reserved
979
ISO/IEC 14882:2011(E)
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.4
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, unspecified1 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&. unspecified2 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 unspecified1 begin(valarray& v); template unspecified2 begin(const valarray& v);
2
Returns: An iterator referencing the first value in the numeric array. § 26.6.10
980
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
template unspecified1 end(valarray& v); template unspecified2 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 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); }
§ 26.7.1
© ISO/IEC 2011 – All rights reserved
981
ISO/IEC 14882:2011(E)
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.288
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.289
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 [first,last) and iterator i2 in the range [first2,first2 + (last - first)) in order.
2
Requires: T shall meet the requirements of CopyConstructible (Table 21) and CopyAssignable (Table 23) types. In the ranges [first,last] and [first2,first2 + (last - first)] binary_op1 and binary_op2 shall neither modify elements nor invalidate iterators or subranges.290
26.7.4
Partial sum
[partial.sum]
template OutputIterator partial_sum( InputIterator first, InputIterator last, OutputIterator result); template OutputIterator partial_sum( InputIterator first, InputIterator last, 288) 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. 289) The use of fully closed ranges is intentional 290) The use of fully closed ranges is intentional
§ 26.7.4
982
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.291
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.292
2
Remarks: result may be equal to first.
3
Returns: result + (last - first).
4
Complexity: Exactly (last - first) - 1 applications of the binary operation.
26.7.6
Iota
[numeric.iota]
template void iota(ForwardIterator first, ForwardIterator last, T value); 291) The use of fully closed ranges is intentional. 292) The use of fully closed ranges is intentional.
§ 26.7.6
© ISO/IEC 2011 – All rights reserved
983
ISO/IEC 14882:2011(E)
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
C library
[c.math]
The header simply includes the headers and .
2
[ Note: The overloads provided in C by magic macros are already provided in and by “sufficient” additional overloads. — end note ]
3
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
MATH_ERRNO MATH_ERREXCEPT math_errhandling
remquo rint round scalbln scalbn sin sinh sqrt tan tanh tgamma trunc isunordered signbit
4
The contents of these headers are the same as the Standard C library headers <math.h> and <stdlib.h> respectively, with the following changes:
5
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 ]
6
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. § 26.8
984
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 120 — Header synopsis Type Macro: Types: div_t Functions: abs div labs 7
Name(s) RAND_MAX ldiv_t
lldiv_t
ldiv llabs lldiv
rand srand
The added signatures are: long abs(long); long long abs(long long); ldiv_t div(long, long); lldiv_t div(long long, long long);
// // // //
labs() llabs() ldiv() lldiv()
8
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.
9
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); float lgamma(float); long long llrint(float); long long llround(float);
§ 26.8
© ISO/IEC 2011 – All rights reserved
985
ISO/IEC 14882:2011(E)
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 long long long
double double double 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); fmod(long double, long double); frexp(long double, int*); hypot(long double, long double);
§ 26.8
986
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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); bool isnormal(double x); bool signbit(double x);
§ 26.8
© ISO/IEC 2011 – All rights reserved
987
ISO/IEC 14882:2011(E)
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
988
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
27 27.1
Input/output library
[input.output]
General
[input.output.general]
1
This Clause describes components that C++ programs may use to perform input/output operations.
2
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 ths 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.1
© ISO/IEC 2011 – All rights reserved
989
ISO/IEC 14882:2011(E)
27.2 27.2.1 1
Iostreams requirements Imbue limitations
[iostreams.requirements] [iostream.limits.imbue]
No function described in Clause 27 except for ios_base::imbue and basic_filebuf::pubimbue causes any 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
Positioning type limitations
[iostreams.limits.pos]
1
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.
2
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
Thread safety
[iostreams.threadsafety]
1
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 ]
2
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;
§ 27.3
990
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
template class basic_istringstream; template class basic_ostringstream; template class basic_stringstream; 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>
stringbuf; istringstream; ostringstream; stringstream;
filebuf; ifstream; ofstream; fstream; wstreambuf; wistream; wostream; wiostream; wstringbuf; wistringstream; wostringstream; wstringstream;
typedef basic_filebuf<wchar_t> wfilebuf; typedef basic_ifstream<wchar_t> wifstream; typedef basic_ofstream<wchar_t> wofstream;
§ 27.3
© ISO/IEC 2011 – All rights reserved
991
ISO/IEC 14882:2011(E)
typedef basic_fstream<wchar_t>
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.293
2
[ 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.
3
The class template specialization basic_streambuf serves as a base class for class templates basic_stringbuf and basic_filebuf.
4
The class template specialization basic_istream serves as a base class for class templates basic_istringstream and basic_ifstream.
5
The class template specialization basic_ostream serves as a base class for class templates basic_ostringstream and basic_ofstream.
6
The class template specialization basic_iostream serves as a base class for class templates basic_stringstream and basic_fstream.
7
Other typedefs define instances of class templates specialized for char or wchar_t types.
8
Specializations of the class template fpos are used for specifying file position information.
9
The types streampos and wstreampos are used for positioning streams specialized on char and wchar_t respectively.
10
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 293) It is the implementation’s responsibility to implement headers so that including and other headers does not violate the rules about multiple occurences of default arguments.
§ 27.4.1
992
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
#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.
2
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.294 The objects are not destroyed during program execution.295 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.
3
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.
4
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; 294) If it is possible for them to do so, implementations are encouraged to initialize the objects earlier than required. 295) Constructors and destructors for static objects can access these objects to read input from stdin or write output to stdout
or stderr.
§ 27.4.2
© ISO/IEC 2011 – All rights reserved
993
ISO/IEC 14882:2011(E)
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). 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:
§ 27.5.1
994
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 ios_base& nounitbuf
(ios_base& str); (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.296 296) Typically long long.
§ 27.5.2
© ISO/IEC 2011 – All rights reserved
995
ISO/IEC 14882:2011(E)
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.297
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 static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags static constexpr fmtflags
boolalpha = unspecified ; 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;
// 27.5.3.1.3 iostate typedef T2 iostate; static constexpr iostate static constexpr iostate static constexpr iostate static constexpr iostate
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 ; 297) 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
996
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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: 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; § 27.5.3
© ISO/IEC 2011 – All rights reserved
997
ISO/IEC 14882:2011(E)
— 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.1 27.5.3.1.1
Types
[ios.types]
Class ios_base::failure
[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
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.
2
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.2
998
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
27.5.3.1.3
Allowable values left | right | internal dec | oct | hex scientific | fixed
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. Table 124 — iostate effects Element badbit eofbit failbit
2
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.
Type iostate also defines the constant: — goodbit, the value zero. 27.5.3.1.4
Type ios_base::openmode
[ios::openmode]
typedef T3 openmode;
§ 27.5.3.1.4
© ISO/IEC 2011 – All rights reserved
999
ISO/IEC 14882:2011(E)
1
The type openmode is a bitmask type (17.5.2.1.3). It contains the elements indicated in Table 125. 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
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. 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
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).
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();
§ 27.5.3.1.6
1000
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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);
4
Effects: Sets fmtfl in flags().
5
Returns: The previous value of flags(). 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().
§ 27.5.3.3
© ISO/IEC 2011 – All rights reserved
1001
ISO/IEC 14882:2011(E)
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.4
ios_base static members
[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.298 27.5.3.5
ios_base storage functions
[ios.base.storage]
static int xalloc(); 1
Returns: index ++. long& iword(int idx); 298) 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.
§ 27.5.3.5
1002
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.299 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 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).
3
Returns: On success iarray[idx]. On failure, a valid long& initialized to 0. 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 fails301 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() 299) 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. 300) for example, because it cannot allocate space. 301) for example, because it cannot allocate space.
§ 27.5.3.7
© ISO/IEC 2011 – All rights reserved
1003
ISO/IEC 14882:2011(E)
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 }; }
27.5.4.1
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
fpos streamoff convertible to bool convertible to bool
converts from offset converts to offset
Assertion/note pre-/post-condition p == P(i) note: a destructor is assumed. post: p == P(i).
P(O(p)) == p == is an equivalence relation
!(p == q)
§ 27.5.4.2
1004
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 127 — Position type requirements (continued) Expression q = p + o p += o q = p - o p -= o o = p - q streamsize(o) O(sz)
Return type fpos
Operational semantics + offset
Assertion/note pre-/post-condition 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
2
[ 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 ]
3
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.5 27.5.5.1
Class template basic_ios Overview
[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.1
© ISO/IEC 2011 – All rights reserved
1005
ISO/IEC 14882:2011(E)
// 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); void move(basic_ios& rhs); void move(basic_ios&& rhs); void swap(basic_ios& rhs) noexcept; void 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. 27.5.5.3
Member functions
[basic.ios.members]
basic_ostream* tie() const;
§ 27.5.5.3
1006
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Table 128 — basic_ios::init() effects Element rdbuf() tie() rdstate() exceptions() flags() width() precision() fill() getloc() iarray parray 1
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
Returns: An output sequence that is tied to (synchronized with) the sequence controlled by the stream buffer. 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.
§ 27.5.5.3
© ISO/IEC 2011 – All rights reserved
1007
ISO/IEC 14882:2011(E)
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 — rdstate(), rdbuf(), and exceptions() are left unchanged; — the contents of arrays pointed at by pword and iword are copied, not the pointers themselves;302 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; 302) 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
1008
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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);
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().303 bool bad() const;
10
Returns: true if badbit is set in rdstate(). iostate exceptions() const; 303) Checking badbit also for fail() is historical practice.
§ 27.5.5.4
© ISO/IEC 2011 – All rights reserved
1009
ISO/IEC 14882:2011(E)
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. ios_base& noshowpos(ios_base& str);
15
Effects: Calls str.unsetf(ios_base::showpos).
16
Returns: str. ios_base& skipws(ios_base& str);
§ 27.5.6.1
1010
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.3
basefield manipulators
[basefield.manip]
ios_base& dec(ios_base& str); 1
Effects: Calls str.setf(ios_base::dec, ios_base::basefield).
§ 27.5.6.3
© ISO/IEC 2011 – All rights reserved
1011
ISO/IEC 14882:2011(E)
2
Returns: str304 . 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. 27.5.6.5
Error reporting
[error.reporting]
error_code make_error_code(io_errc e); 1
Returns: error_code(static_cast(e), iostream_category()). error_condition make_error_condition(io_errc e);
2
Returns: error_condition(static_cast(e), iostream_category()). const error_category& iostream_category(); 304) 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); — 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.
§ 27.6.2
© ISO/IEC 2011 – All rights reserved
1013
ISO/IEC 14882:2011(E)
— 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(); 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
1014
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
// 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: 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: § 27.6.3
© ISO/IEC 2011 – All rights reserved
1015
ISO/IEC 14882:2011(E)
— 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:305 — 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(). 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. 305) 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
1016
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.4
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.4
© ISO/IEC 2011 – All rights reserved
1017
ISO/IEC 14882:2011(E)
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.2
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);
§ 27.6.3.3.2
1018
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.2
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);
§ 27.6.3.4.2
© ISO/IEC 2011 – All rights reserved
1019
ISO/IEC 14882:2011(E)
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();306 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.307
2
Default behavior: Returns zero.
3
Remarks: Uses traits::eof(). streamsize xsgetn(char_type* s, streamsize n);
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.308
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. 306) The morphemes of showmanyc are “es-how-many-see”, not “show-manic”. 307) 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.” 308) 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
1020
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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(). 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. § 27.6.3.4.4
© ISO/IEC 2011 – All rights reserved
1021
ISO/IEC 14882:2011(E)
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.
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 accomodate 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 specified309 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.310
7
Default behavior: Returns traits::eof(). 309) 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. 310) 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.6.3.4.5
1022
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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>>( 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:
§ 27.7.2.1
1024
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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); 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*);
§ 27.7.2.1
© ISO/IEC 2011 – All rights reserved
1025
ISO/IEC 14882:2011(E)
template basic_istream& operator>>(basic_istream&, signed char*); } 1
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.
2
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.
3
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.
4
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();
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.2
1026
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.311 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: 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))312 ~sentry();
6
Effects: None. explicit operator bool() const;
7
Effects: Returns ok_. 311) 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. 312) The sentry constructor and destructor can also perform additional implementation-dependent operations.
§ 27.7.2.1.3
© ISO/IEC 2011 – All rights reserved
1027
ISO/IEC 14882:2011(E)
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 on313 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. 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; 313) This is done without causing an ios::failure to be thrown.
§ 27.7.2.2.2
1028
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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).314 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. basic_istream& operator>> (ios_base& (*pf)(ios_base&));
5
Effects: Calls pf(*this).315 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); 314) See, for example, the function signature ws(basic_istream&) (27.7.2.4). 315) See, for example, the function signature dec(ios_base&) (27.5.6.3).
§ 27.7.2.2.3
© ISO/IEC 2011 – All rights reserved
1029
ISO/IEC 14882:2011(E)
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. 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
§ 27.7.2.2.3
1030
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 on316 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);
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.317 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.318 Characters are extracted and stored until any of the following occurs: — n is less than one or n - 1 characters are stored; 316) This is done without causing an ios::failure to be thrown. 317) Note that this function is not overloaded on types signed char and unsigned char. 318) Note that this function is not overloaded on types signed char and unsigned char.
§ 27.7.2.3
© ISO/IEC 2011 – All rights reserved
1031
ISO/IEC 14882:2011(E)
— 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);
16
Effects: Calls get(sb, widen(’\n’))
17
Returns: Value returned by the call. 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.319 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);320 3. n is less than one or n - 1 characters are stored (in which case the function calls setstate( failbit)). 319) Note that this function is not overloaded on types signed char and unsigned char. 320) Since the final input character is “extracted,” it is counted in the gcount(), even though it is not stored.
§ 27.7.2.3
1032
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
19
These conditions are tested in the order shown.321
20
If the function extracts no characters, it calls setstate(failbit) (which may throw ios_base:: failure (27.5.5.4)).322
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 ] 323) Note that this function is not overloaded on types signed char and unsigned char.
§ 27.7.2.3
1034
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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. 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]
§ 27.7.2.5
© ISO/IEC 2011 – All rights reserved
1035
ISO/IEC 14882:2011(E)
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); }; } 1
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]
§ 27.7.2.5.3
1036
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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; typedef typename traits::off_type off_type; traits_type; typedef traits // 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 {
§ 28.12.1
© ISO/IEC 2011 – All rights reserved
1113
ISO/IEC 14882:2011(E)
public: typedef typedef typedef typedef typedef typedef
basic_regex match_results std::ptrdiff_t const value_type* const value_type& std::forward_iterator_tag
regex_type; value_type; difference_type; pointer; reference; 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; 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: § 28.12.1.2
1114
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
— 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.3
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 ] § 28.12.1.4
© ISO/IEC 2011 – All rights reserved
1115
ISO/IEC 14882:2011(E)
regex_iterator operator++(int); 9
Effects: regex_iterator tmp = *this; ++(*this); return tmp;
28.12.2
Class template regex_token_iterator
[re.tokiter]
1
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.
2
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.
3
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.
4
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.
5
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.
6
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();
§ 28.12.2
1116
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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, 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
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.
8
[ 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 ]
9
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.
§ 28.12.2.1
© ISO/IEC 2011 – All rights reserved
1117
ISO/IEC 14882:2011(E)
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, 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;
§ 28.12.2.3
1118
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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).
6
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
Modified ECMAScript regular expression grammar
[re.grammar]
1
The regular expression grammar recognized by basic_regex objects constructed with the ECMAScript flag is that specified by ECMA-262, except as specified below.
2
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.
3
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 :]
§ 28.13
© ISO/IEC 2011 – All rights reserved
1119
ISO/IEC 14882:2011(E)
ClassAtomCollatingElement :: [. ClassName .] ClassAtomEquivalence :: [= ClassName =] ClassName :: ClassNameCharacter ClassNameCharacter ClassName ClassNameCharacter :: SourceCharacter but not one of "." "=" ":" 5
The productions ClassAtomExClass, ClassAtomCollatingElement and ClassAtomEquivalence provide functionality equivalent to that of the same features in regular expressions in POSIX.
6
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.
7
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: \d and [[:digit:]] \D and [^[:digit:]] \s and [[:space:]] \S and [^[:space:]] \w and [_[:alnum:]] \W and [^_[:alnum:]]
8
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.
9
The results from multiple calls to traits_inst.lookup_classname can be bitwise OR’ed together and subsequently passed to traits_inst.isctype.
10
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.
11
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.
12
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 ]
13
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. § 28.13
1120
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
14
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 30.4.1.1 1
In general
[thread.mutex.requirements] [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
1
Mutex requirements
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 § 30.4.1.2
© ISO/IEC 2011 – All rights reserved
1149
ISO/IEC 14882:2011(E)
description, m denotes an object of a mutex type. 2
The mutex types shall meet the Lockable requirements (30.2.5.3).
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.
4
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. — 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
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 ]
6
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.
§ 30.4.1.2
1150
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.1
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
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().
2
[ 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 ]
3
The class mutex shall satisfy all the Mutex requirements (30.4.1). (Clause 9).
4
[ 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 ]
It shall be a standard-layout class
§ 30.4.1.2.1
© ISO/IEC 2011 – All rights reserved
1151
ISO/IEC 14882:2011(E)
5
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 }; } 1
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.
2
The class recursive_mutex shall satisfy all the Mutex requirements (30.4.1). It shall be a standard-layout class (Clause 9).
3
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.
4
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
Timed mutex types
[thread.timedmutex.requirements]
1
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).
2
The timed mutex types shall meet the TimedLockable requirements (30.2.5.4).
3
The expression m.try_lock_for(rel_time) shall be well-formed and have the following semantics:
§ 30.4.1.3
1152
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
4
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
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();
§ 30.4.1.3.1
© ISO/IEC 2011 – All rights reserved
1153
ISO/IEC 14882:2011(E)
typedef implementation-defined native_handle_type; // See 30.2.3 native_handle_type native_handle(); // See 30.2.3 }; } 1
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).
2
The class timed_mutex shall satisfy all of the TimedMutex requirements (30.4.1.3). It shall be a standardlayout class (Clause 9).
3
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; 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
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).
2
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). § 30.4.1.3.2
1154
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
3
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.
4
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
Locks
[thread.lock]
1
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 ]
2
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.1
Class template lock_guard
[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:
§ 30.4.2.1
© ISO/IEC 2011 – All rights reserved
1155
ISO/IEC 14882:2011(E)
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); 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();
§ 30.4.2.2
1156
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
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).
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; 1
Effects: Constructs an object of type unique_lock.
2
Postconditions: pm == 0 and owns == false. 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. § 30.4.2.2.1
© ISO/IEC 2011 – All rights reserved
1157
ISO/IEC 14882:2011(E)
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). 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.1
1158
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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. 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 § 30.4.2.2.2
© ISO/IEC 2011 – All rights reserved
1159
ISO/IEC 14882:2011(E)
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.3
Generic locking algorithms
[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 § 30.4.3
1160
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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. [ Example: // global flag, regular function void init(); std::once_flag flag; void f() {
§ 30.4.4.2
© ISO/IEC 2011 – All rights reserved
1161
ISO/IEC 14882:2011(E)
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,verifier); } };
— end example ]
30.5
Condition variables
[thread.condition]
1
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.
2
Condition variables permit concurrent invocation of the wait, wait_for, wait_until, notify_one and notify_all member functions.
3
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 3. the reacquisition of the lock.
4
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.
5
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 };
§ 30.5
1162
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
} 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; 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);
§ 30.5.1
© ISO/IEC 2011 – All rights reserved
1163
ISO/IEC 14882:2011(E)
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 theads. 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.
§ 30.5.1
1164
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
— 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);
19
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.
§ 30.5.1
© ISO/IEC 2011 – All rights reserved
1165
ISO/IEC 14882:2011(E)
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 — 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 evaluates to true regardless of whether the timeout was triggered. — end note ] § 30.5.1
1166
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.2 1
Class condition_variable_any
[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);
§ 30.5.2
© ISO/IEC 2011 – All rights reserved
1167
ISO/IEC 14882:2011(E)
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 ]
6
Effects: Destroys the object. void notify_one() noexcept;
7
Effects: If any threads are blocked waiting for *this, unblocks one of those theads. 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.
§ 30.5.2
1168
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
— 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. — 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: § 30.5.2
© ISO/IEC 2011 – All rights reserved
1169
ISO/IEC 14882:2011(E)
— 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));
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 };
§ 30.6.1
1170
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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); }
§ 30.6.1
© ISO/IEC 2011 – All rights reserved
1171
ISO/IEC 14882:2011(E)
2
The enum type launch is an implementation-defined 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.3
Class future_error
[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
Shared state
[futures.state]
1
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 ]
2
[ 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 ]
3
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.
§ 30.6.4
1172
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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. 4
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.
5
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 — makes its shared state ready; — second, the provider releases its shared state.
8
An 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.
9
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.
10
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.
11
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);
§ 30.6.5
© ISO/IEC 2011 – All rights reserved
1173
ISO/IEC 14882:2011(E)
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>; } 1
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.
2
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). § 30.6.5
1174
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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. — 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();
§ 30.6.5
© ISO/IEC 2011 – All rights reserved
1175
ISO/IEC 14882:2011(E)
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: — 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
Class template future
[futures.unique_future]
1
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.
2
[ Note: Member functions of future do not synchronize with themselves or with member functions of shared_future. — end note ]
3
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();
§ 30.6.6
1176
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
// 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;
5
Effects: constructs an empty future object that does not refer to an shared state.
6
Postcondition: valid() == false. 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. Postcondition: — valid() returns the same value as rhs.valid() prior to the assignment. — rhs.valid() == false. shared_future share();
§ 30.6.6
© ISO/IEC 2011 – All rights reserved
1177
ISO/IEC 14882:2011(E)
11
Returns: shared_future(std::move(*this)).
12
Postcondition: valid() == false. R future::get(); R& future::get(); void future::get();
13
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.
14
Effects: wait()s until the shared state is ready, then retrieves the value stored in the shared state.
15
Returns: — future::get() returns the value stored in the object’s shared state. If the type of the value is MoveAssignable the returned value is moved, otherwise it is copied. — future::get() returns the reference stored as value in the object’s shared state. — future::get() returns nothing.
16
Throws: the stored exception, if an exception was stored in the shared state.
17
Postcondition: valid() == false. bool valid() const noexcept;
18
Returns: true only if *this refers to a shared state. void wait() const;
19
Effects: blocks until the shared state is ready. template future_status wait_for(const chrono::duration& rel_time) const;
20
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.
21
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;
22
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.
23
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.6
1178
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
30.6.7
Class template shared_future
[futures.shared_future]
1
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.
2
[ Note: Member functions of shared_future do not synchronize with themselves, but they synchronize with the shared shared state. — end note ]
3
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 ] 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).
§ 30.6.7
© ISO/IEC 2011 – All rights reserved
1179
ISO/IEC 14882:2011(E)
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: — 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
§ 30.6.7
1180
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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. 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 template function 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);
§ 30.6.8
© ISO/IEC 2011 – All rights reserved
1181
ISO/IEC 14882:2011(E)
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): — 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 (g, 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 (g, 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: § 30.6.8
1182
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
— 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: 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
Class template packaged_task
[futures.task]
1
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.
2
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(packaged_task&) = delete; packaged_task& operator=(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();
§ 30.6.9
© ISO/IEC 2011 – All rights reserved
1183
ISO/IEC 14882:2011(E)
// execution void operator()(ArgTypes... ); void make_ready_at_thread_exit(ArgTypes...); void reset(); }; template 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. § 30.6.9.1
1184
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
bool valid() const noexcept; 11
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
© ISO/IEC 2011 – All rights reserved
1185
ISO/IEC 14882:2011(E)
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
1186
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Annex A (informative) Grammar summary 1
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
[gram]
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
§ A.2
© ISO/IEC 2011 – All rights reserved
1187
ISO/IEC 14882:2011(E)
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 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 pp-number pp-number pp-number pp-number
digit identifier-nondigit e sign E sign .
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 n o p q r A B C D E N O P Q R
f s F S
g t G T
h u H U
i v I V
j w J W
k x K X
l y L Y
m z M Z _
digit: one of 0 1 2 3 4 5 6 7 8 9
§ A.2
1188
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
preprocessing-op-or-punc: one { } [ :: / > > ++ compl
## %:%: .* ˆ -= >>= -not
( ;
) :
& *=
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
§ A.2
© ISO/IEC 2011 – All rights reserved
1189
ISO/IEC 14882:2011(E)
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 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
§ A.2
1190
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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.2
© ISO/IEC 2011 – All rights reserved
1191
ISO/IEC 14882:2011(E)
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 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
§ A.4
1192
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
capture: identifier & identifier this lambda-declarator: ( parameter-declaration-clause ) mutableopt exception-specificationopt attribute-specifier-seqopt trailing-return-typeopt 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
§ A.4
© ISO/IEC 2011 – All rights reserved
1193
ISO/IEC 14882:2011(E)
new-placement: ( expression-list ) new-type-id: type-specifier-seq new-declaratoropt new-declarator: ptr-operator new-declaratoropt noptr-new-declarator 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 relational-expression relational-expression relational-expression
< shift-expression > shift-expression = shift-expression
equality-expression: relational-expression equality-expression == relational-expression equality-expression != relational-expression and-expression: equality-expression and-expression & equality-expression
§ A.4
1194
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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 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
§ A.12
1204
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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
§ A.14
© ISO/IEC 2011 – All rights reserved
1205
ISO/IEC 14882:2011(E)
group-part: if-section control-line text-line # non-directive if-section: if-group elif-groupsopt else-groupopt endif-line if-group: # if # ifdef # ifndef
constant-expression new-line groupopt identifier new-line groupopt 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 # define # define # define # define # undef # line # error # pragma # new-line
pp-tokens new-line identifier replacement-list new-line identifier lparen identifier-listopt ) replacement-list new-line identifier lparen ... ) replacement-list new-line identifier lparen identifier-list, ... ) replacement-list new-line identifier new-line pp-tokens new-line pp-tokensopt new-line pp-tokensopt new-line
text-line: pp-tokensopt new-line 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.14
1206
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Annex B (informative) Implementation quantities
[implimits]
1
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.
2
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]. — Functions registered by atexit() [32].
© ISO/IEC 2011 – All rights reserved
1207
ISO/IEC 14882:2011(E)
— 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 [1 024]. — Handlers per try block [256]. — Throw specifications on a single function declaration [256]. — Number of placeholders (20.8.9.1.3) [10].
1208
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Annex C (informative) Compatibility C.1 1
C++ and ISO C
[diff ] [diff.iso]
This subclause lists the differences between C++ and ISO C, by the chapters of this document.
C.1.1
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: § C.1.1
© ISO/IEC 2011 – All rights reserved
1209
ISO/IEC 14882:2011(E)
char* p = "abc"; void f(char*) { char* p = (char*)"abc"; f(p); f((char*)"def"); }
// valid in C, invalid in C++ // OK: cast added // 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
§ C.1.2
1210
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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. 4.10 Change: Only pointers to non-const and non-volatile objects may be implicitly converted to void* Rationale: This improves type safety. Effect on original feature: Deletion of semantically well-defined feature. Difficulty of converting: Could be automated. A C program containing such an implicit conversion from, e.g., pointer-to-const-object to void* will receive a diagnostic message. The correction is to add an explicit cast. How widely used: Seldom.
C.1.4
Clause 5: expressions
[diff.expr]
5.2.2 Change: Implicit declaration of functions is not allowed § C.1.4
© ISO/IEC 2011 – All rights reserved
1211
ISO/IEC 14882:2011(E)
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, 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 § C.1.5
1212
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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. 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.
§ C.1.6
© ISO/IEC 2011 – All rights reserved
1213
ISO/IEC 14882:2011(E)
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 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. § C.1.6
1214
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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. § C.1.7
© ISO/IEC 2011 – All rights reserved
1215
ISO/IEC 14882:2011(E)
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 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. § C.1.8
1216
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 and struct X are at the same scope
struct Y; struct X { struct Y { /∗ ... ∗/ } y; };
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 renamed. How widely used: Seldom.
C.1.9
Clause 12: special member functions
[diff.special]
12.8 Change: Copying volatile objects § C.1.9
© ISO/IEC 2011 – All rights reserved
1217
ISO/IEC 14882:2011(E)
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. 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. § C.2.1
1218
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
#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. § C.2.5
© ISO/IEC 2011 – All rights reserved
1219
ISO/IEC 14882:2011(E)
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. 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 terminate() (without calling unexpected()) if their exception specification is noexcept or noexcept(true). For a throwing virtual destructor of a derived class, 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>, , , , § C.2.7
1220
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
, , , , <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. 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;
// single-object delete // array delete
§ C.2.8
© ISO/IEC 2011 – All rights reserved
1221
ISO/IEC 14882:2011(E)
return 0; }
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 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 behavor 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
§ C.2.12
1222
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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). 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 § C.2.12
© ISO/IEC 2011 – All rights reserved
1223
ISO/IEC 14882:2011(E)
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, 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
§ C.2.15
1224
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
C standard library
[diff.library]
1
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).
2
The C++ standard library provides 57 standard macros from the C library, as shown in Table 149.
3
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). Table 149 — Standard macros assert BUFSIZ CLOCKS_PER_SEC EDOM EILSEQ EOF ERANGE errno EXIT_FAILURE EXIT_SUCCESS FILENAME_MAX FOPEN_MAX
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 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
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
5
The C++ standard library provides 20 standard types from the C library, as shown in Table 151.
6
The C++ standard library provides 2 standard structs from the C library, as shown in Table 152.
7
The C++ standard library provides 209 standard functions from the C library, as shown in Table 153. § C.3
© ISO/IEC 2011 – All rights reserved
1225
ISO/IEC 14882:2011(E)
Table 151 — Standard types clock_t div_t FILE fpos_t jmp_buf
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
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
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
§ C.3
1226
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
C.3.1 1
Modifications 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
1
Type wchar_t
Header
Macro NULL
[diff.null]
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
[diff.header.iso646.h]
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
1
[diff.wchar.t]
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
1
[diff.mods.to.headers]
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 18.5 describes the changes.
2
Header : The following functions have different behavior: — longjmp 18.10 describes the changes.
§ C.3.4
© ISO/IEC 2011 – All rights reserved
1227
ISO/IEC 14882:2011(E)
C.3.4.1 1
[diff.offsetof ]
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
1
Macro offsetof(type, member-designator)
Memory allocation functions
[diff.malloc]
The functions calloc, malloc, and realloc are restricted in this International Standard. 20.6.13 describes the changes.
§ C.3.4.2
1228
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
Annex D (normative) Compatibility features
[depr]
1
This Clause describes features of the C++ Standard that are specified for compatibility with existing implementations.
2
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
Implicit declaration of copy functions
[depr.impldec]
Dynamic exception specifications
[depr.except.spec]
The use of dynamic-exception-specifications is deprecated.
D.5 1
[depr.register]
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
register keyword
The use of the register keyword as a storage-class-specifier (7.1.1) is deprecated.
D.3 1
[depr.incr.bool]
The use of an operand of type bool with the ++ operator is deprecated (see 5.3.2 and 5.2.6).
D.2 1
Increment operator with bool operand
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
<math.h> <setjmp.h>
<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).
§ D.5
© ISO/IEC 2011 – All rights reserved
1229
ISO/IEC 14882:2011(E)
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
Old iostreams members
[depr.ios.members]
The following member names are in addition to names specified in Clause 27: 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
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.
3
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.
4
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.
5
The type streamoff is an implementation-defined type that satisfies the requirements of off_type in 27.2.2.
6
The type streampos is an implementation-defined type that satisfies the requirements of pos_type in 27.2.2.
7
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 };
§ D.6
1230
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 }; 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,
§ D.7.1
© ISO/IEC 2011 – All rights reserved
1231
ISO/IEC 14882:2011(E)
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 virtual int_type virtual int_type virtual pos_type
overflow (int_type c = EOF); pbackfail(int_type c = EOF); underflow(); 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
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.
2
[ 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. — end note ]
3
[ 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; § D.7.1
1232
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
— 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. — end note ] 4
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. 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.
4
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).
§ D.7.1.1
© ISO/IEC 2011 – All rights reserved
1233
ISO/IEC 14882:2011(E)
Table 157 — strstreambuf(charT*, streamsize, charT*) effects Element strmode alsize palloc pfree
Value 0 an unspecified value a null pointer a null pointer
— If n < 0, N is INT_MAX.337 5
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. 337) The function signature strlen(const char*) is declared in . (18.3).
(21.7).
The macro INT_MAX is defined in
§ D.7.1.2
1234
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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: — 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++.
2
Returns (unsigned char)c. — If c == EOF, there is no character to append.
3
Returns a value other than EOF.
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.338 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: — If c != EOF, if the input sequence has a putback position available, and if (char)c == gnext[-1], assigns gnext - 1 to gnext.
10
Returns c. — If c != EOF, if the input sequence has a putback position available, and if strmode & constant is zero, assigns c to *--gnext.
11
Returns c. — If c == EOF and if the input sequence has a putback position available, assigns gnext - 1 to gnext.
12
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: 338) An implementation should consider alsize in making this decision.
§ D.7.1.3
© ISO/IEC 2011 – All rights reserved
1235
ISO/IEC 14882:2011(E)
— If the input sequence has a read position available, the function signals success by returning (unsigned char)*gnext. — 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. 16
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. 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);
§ D.7.1.3
1236
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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. — If the function positions neither sequence, the positioning operation fails.
24
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(): — 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. § D.7.2.1
© ISO/IEC 2011 – All rights reserved
1237
ISO/IEC 14882:2011(E)
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.2
Member functions
[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).
§ D.7.3.1
1238
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
— 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)).339 D.7.3.2
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 339) The function signature strlen(const char*) is declared in (21.7).
§ D.7.4
© ISO/IEC 2011 – All rights reserved
1239
ISO/IEC 14882:2011(E)
— sb, the strstreambuf object. D.7.4.1
strstream constructors
[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
1240
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
}; } namespace std { template struct binary_function { typedef Arg1 first_argument_type; typedef Arg2 second_argument_type; typedef Result result_type; }; }
D.8.2 1
Function adaptors
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
1
[depr.adaptors]
Adaptors for pointers to functions
[depr.function.pointer.adaptors]
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
© ISO/IEC 2011 – All rights reserved
1241
ISO/IEC 14882:2011(E)
D.8.2.2 1
Adaptors for pointers to members
[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. 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). § D.8.2.2
1242
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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; };
12
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
§ D.9
© ISO/IEC 2011 – All rights reserved
1243
ISO/IEC 14882:2011(E)
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
[depr.lib.bind.1st]
bind1st
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); 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
bind2nd
[depr.lib.bind.2nd]
§ D.9.4
1244
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
Class template auto_ptr
[auto.ptr]
1
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).
2
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(); // D.10.1.2 members: X& operator*() const throw(); X* operator->() const throw(); X* get() const throw(); 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();
§ D.10.1
© ISO/IEC 2011 – All rights reserved
1245
ISO/IEC 14882:2011(E)
}; 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. ~auto_ptr() throw();
13
Requires: The expression delete get() is well formed.
14
Effects: delete get().
§ D.10.1.1
1246
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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.11 D.11.1
Violating exception-specifications Type unexpected_handler
[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.
§ D.11.1
© ISO/IEC 2011 – All rights reserved
1247
ISO/IEC 14882:2011(E)
2
Required behavior: An unexpected_handler shall not return. See also 15.5.2.
3
Default behavior: The implementation’s default unexpected_handler calls 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
1248
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
© ISO/IEC 2011 – All rights reserved
1249
ISO/IEC 14882:2011(E)
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
1250
alg.replace 25.3.5 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
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
array.cons 23.3.2.2 array.data 23.3.2.5 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
© ISO/IEC 2011 – All rights reserved
basic.compound 3.9.2 basic.def 3.1 basic.def.odr 3.2 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
1251
ISO/IEC 14882:2011(E)
bitset.members 20.5.2 bitset.operators 20.5.4 bitwise.operations 20.8.7 byte.strings 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
1252
class.expl.init 12.6.1 class.free 12.5 class.friend 11.3 class.gslice 26.6.6 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
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
container.requirements.general 23.2.1 containers 23 containers.general 23.1 contents 17.6.1.1 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
© ISO/IEC 2011 – All rights reserved
dcl.attr.noreturn 7.6.3 dcl.constexpr 7.1.5 dcl.dcl 7 dcl.decl 8 dcl.enum 7.2 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
1253
ISO/IEC 14882:2011(E)
defns.diagnostic defns.dynamic.type defns.dynamic.type.prvalue defns.handler defns.ill.formed 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
1254
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 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
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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
© ISO/IEC 2011 – All rights reserved
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 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
1255
ISO/IEC 14882:2011(E)
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 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.2 func.bind.isbind 20.8.9.1.1 func.bind.place 20.8.9.1.3 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
1256
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 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
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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
© ISO/IEC 2011 – All rights reserved
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 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
1257
ISO/IEC 14882:2011(E)
iterator.primitives 24.4 iterator.range 24.6.5 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 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
1258
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 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
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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
© ISO/IEC 2011 – All rights reserved
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 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
1259
ISO/IEC 14882:2011(E)
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 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
1260
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 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
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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
© ISO/IEC 2011 – All rights reserved
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 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
1261
ISO/IEC 14882:2011(E)
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 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 20.12.5 sequence.reqmts 23.2.3 sequences 23.3 sequences.general 23.3.1 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
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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
© ISO/IEC 2011 – All rights reserved
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 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
1263
ISO/IEC 14882:2011(E)
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 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
1264
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 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
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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 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
© ISO/IEC 2011 – All rights reserved
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 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
1265
ISO/IEC 14882:2011(E)
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 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.modifers 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.modifers 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
1266
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 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
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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
27.4.3
X xref F Y Z
© ISO/IEC 2011 – All rights reserved
1267
ISO/IEC 14882:2011(E)
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, 229 label specifier, 130 ::, 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, 416, 417 ## operator, 417 #define, 416 #elif, 413 #else, 414 #endif, 414 #error, see preprocessing directives, error #if, 413, 450
1268
#ifdef, 414 #ifndef, 414 #include, 414, 436 #line, see preprocessing directives, line control #pragma, see preprocessing directives, pragma #undef, 418, 446 %, see remainder operator &, see operator, address-of, see bitwise AND operator, see declarator, reference &&, see logical AND operator ˆ, see bitwise exclusive OR operator _ _ DATE _ _, 421 _ _ FILE _ _, 422 _ _ LINE _ _, 422 _ _ STDC _ _, 422 implementation-defined, 422 _ _ STDCPP_STRICT_POINTER_SAFETY _ _, 422 implementation-defined, 422 _ _ STDCPP_THREADS _ _, 422 implementation-defined, 422 _ _ STDC_HOSTED _ _, 422 implementation-defined, 422 _ _ STDC_ISO_10646 _ _, 422 implementation-defined, 422 _ _ STDC_MB_MIGHT_NEQ_WC _ _, 422 implementation-defined, 422 _ _ STDC_VERSION _ _, 422 implementation-defined, 422 _ _ TIME _ _, 422 _ _ VA_ARGS _ _, 415 _ _cplusplus, 421 \, see backslash {} block statement, 130 class declaration, 216 class definition, 216 enum declaration, 157 initializer list, 205 , see destructor ~ _, see character, underscore |, see bitwise inclusive OR operator ||, see logical OR operator ~, see operator, one’s complement 0, see also zero, null null character, 31
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
string terminator, 31 abort, 65, 136 abstract-declarator, 183, 1201 abstract-pack-declarator, 184, 1201 access control, 246–256 base class, 249 base class member, 233 class member, 100 default, 246 default argument, 247 friend function, 251 member name, 246 multiple access, 256 nested class, 256 overloading and, 292 private, 246 protected, 246, 254 public, 246 union default member, 216 using-declaration and, 170 virtual function, 255 access-specifier, 233, 1203 access control anonymous union, 228 member function and, 257 overloading resolution and, 237 access specifier, 248, 249 addition operator, 119 additive-expression, 119, 1194 address, 77, 122 address of member function unspecified, 450 aggregate, 205 aggregate initialization, 205 algorithm stable, 428, 451 alias namespace, 164 alias template, 351 alias-declaration, 140, 1197 alignment extended, 80 fundamental, 80 alignment-specifier, 177, 1200 alignment requirement implementation-defined, 80 allocation alignment storage, 113 implementation defined bit-field, 229 unspecified, 221
© ISO/IEC 2011 – All rights reserved
allocation functions, 66 allowing an exception, see exception handling, allowing an exception alternative token, see token, alternative ambiguity base class member, 236 class conversion, 239 declaration type, 142 declaration versus cast, 184 declaration versus expression, 138 function declaration, 203 member access, 236 overloaded function, 292 parentheses and, 112 Amendment 1, 447 and-expression, 123, 1194 appertain, 178 argc, 62 argument, 2, 449, 450, 486 access checking and default, 247 binding of default, 196 evaluation of default, 196, 197 example of default, 195, 196 function call expression, 2 function-like macro, 2 overloaded operator and default, 314 reference, 99 scope of default, 197 template, 327 template instantiation, 2 throw expression, 2 type checking of default, 196 arguments implementation-defined order of evaluation of function, 197 argument and name hiding default, 197 argument and virtual function default, 198 argument list empty, 192 variable, 192 argument passing, 99 reference and, 209 argument substitution, see macro, argument substitution argument type unknown, 192 argv, 62 arithmetic pointer, 120
1269
ISO/IEC 14882:2011(E)
unsigned, 75 array, 193 bound, 190 const, 77 delete, 115 multidimensional, 191 new, 113 overloading and pointer versus, 290 sizeof, 111 storage of, 191 array as aggregate, 757 contiguous storage, 756 initialization, 757, 758 tuple interface to, 759 zero sized, 759 array size default, 190 arrow operator, see operator, class member access as-if rule, 8 asm implementation-defined, 173 asm-definition, 173, 1199 assembler, 173 , 436 assignment and lvalue, 125 conversion by, 126 copy, see assignment operator, copy move, see assignment operator, move, 427 reference, 209 assignment operator copy, 257, 281–284 hidden, 283 implicitly declared, 282 implicitly defined, 283 inaccessible, 284 trivial, 283 virtual bases and, 284 move, 257, 281–284 hidden, 283 implicitly declared, 282 implicitly defined, 283 inaccessible, 284 trivial, 283 virtual bases and, 284 overloaded, 314 assignment-expression, 126, 1195 assignment-operator, 126, 1195 associative containers exception safety, 744
1270
requirements, 744 unordered, see unordered associative containers asynchronous provider, 1173 asynchronous return object, 1172 atexit, 65 atomic operations, see operation, atomic attribute, 177–181 alignment, 178 carries dependency, 180 noreturn, 179 syntax and semantics, 177 attribute, 177, 1200 attribute-argument-clause, 177, 1200 attribute-declaration, 140, 1197 attribute-list, 177, 1200 attribute-namespace, 177, 1200 attribute-scoped-token, 177, 1200 attribute-specifier, 177, 1199 attribute-specifier-seq, 177, 1199 attribute-token, 177, 1200 automatic storage duration, 66 awk, 1087 backslash character, 27 bad_alloc, 114 bad_cast, 103 bad_exception, 410 bad_typeid, 104 bad_typeid::what implementation-defined, 475 balanced-token, 177, 1200 balanced-token-seq, 177, 1200 base class overloading and, 291 base class subobject, 8 base-clause, 233, 1203 base-specifier, 233, 1203 base-specifier-list, 233, 1203 base-type-specifier, 233, 1203 BaseCharacteristic, 585 base class, 233, 234 direct, 233 indirect, 233 private, 249 protected, 249 public, 249 base class virtual, see virtual base class basic_ios::failure argument implementation-defined, 1009 begin unordered associative containers, 752
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
behavior conditionally-supported, 2, 6 default, 426, 430 implementation-defined, 3, 8 locale-specific, 3 observable, 8, 9 on receipt of signal, 9 required, 427, 430 undefined, 4, 5, 9 unspecified, 5, 8, 9 Ben, 292 Bernoulli distributions, 940–944 bernoulli_distribution discrete probability function, 940 binary function, 571 binary operator overloaded, 314 BinaryTypeTrait, 585 binary operator interpretation of, 314 bind directly, 211 binding reference, 209 binomial_distribution discrete probability function, 941 bit-field, 229 address of, 229 alignment of, 229 implementation-defined sign of, 229 implementation defined alignment of, 229 type of, 229 unnamed, 229 zero width of, 229 block, 425 initialization in, 137 block scope, 41 block statement, see statement, compound block-declaration, 140, 1197 block structure, 137 body function, 198 Boolean, 229 Boolean literal, 31 boolean literal, see literal, boolean boolean-literal, 31, 1191 Boolean type, 75 bound arguments, 578 bound, of array, 190 brace-or-equal-initializer, 202, 1202 braced-init-list, 202, 1202 bucket
© ISO/IEC 2011 – All rights reserved
unordered associative containers, 752 bucket_count unordered associative containers, 752 bucket_size unordered associative containers, 752 buckets, 745 byte, 7, 111 C linkage to, 174 standard, 1 standard library, 1 Unicode TR, 1 c-char, 26, 1190 c-char-sequence, 26, 1190 call operator function, 313 pseudo destructor, 100 call signature, 570 call wrapper, 570, 571 forwarding, 571 simple, 571 type, 570 Callable, 581 callable object, 570, 581 callable type, 570 capture, 92, 1193 capture-default, 92, 1192 capture-list, 92, 1192 captured, 94 by copy, 95 by reference, 95 carries a dependency, 13 carry subtract_with_carry_engine, 929 , 436 cast base class, 105 const, 107, 117 derived class, 105 dynamic, 102, 474 construction and, 277 destruction and, 277 integer to pointer, 106 lvalue, 104, 106 pointer-to-function, 107 pointer-to-member, 106, 107 pointer to integer, 106 reference, 104, 107 reinterpret, 106, 117 integer to pointer, 106
1271
ISO/IEC 14882:2011(E)
lvalue, 106 pointer to integer, 106 pointer-to-function, 107 pointer-to-member, 107 reference, 107 static, 104, 117 lvalue, 104 reference, 104 undefined pointer-to-function, 107 cast-expression, 117, 1194 casting, 100 catch, 400 cauchy_distribution probability density function, 951 cbegin unordered associative containers, 752 cend unordered associative containers, 752 , 446 char implementation-defined sign of, 75 char-like object, 628 char-like type, 628 char16_t, 27 char16_t character, 27 char32_t, 27 char32_t character, 27 char_class_type regular expression traits, 1077 character, 425 decimal-point, 433 multibyte, 3 signed, 75 source file, 17 underscore, 446 in identifier, 23 character literal, see literal, character character set, 18–19 basic execution, 7 basic source, 17, 18 character string literal, 417 character-literal, 26, 1190 character string, 29 checking point of error, 354 syntax, 354 chi_squared_distribution probability density function, 950 class, 76, 216–232 abstract, 244 base, 447, 452
1272
cast to incomplete, 118 constructor and abstract, 245 definition, 36 derived, 452 linkage of, 59 linkage specification, 175 member function, see member function, class pointer to abstract, 245 polymorphic, 240 scope of enumerator, 160 standard-layout, 217 trivial, 216 unnamed, 147 class-head, 216, 1202 class-head-name, 216, 1202 class-key, 216, 1202 class-name, 216, 1202 class-or-decltype, 233, 1203 class-specifier, 216, 1202 class-virt-specifier, 216, 1202 class local, see local class class name, 183 elaborated, 156, 219 point of declaration, 219 scope of, 218 typedef, 147, 220 class nested, see nested class class object assignment to, 126 const, 77 member, 221 sizeof, 111 class object copy, see copy constructor class object initialization, see constructor clear unordered associative containers, 751 , 433 closure object, 92 closure type, 92 collating element, 1076 comment, 20–22 /* */, 21 //, 21 comparison pointer, 122 pointer to function, 122 undefined pointer, 120, 122 unspecified pointer, 122 void* pointer, 121 compatible, see exception specification, compatible compilation
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
separate, 17 compiler control line, see preprocessing directives complete object, 8 complete object of, 8 completely defined, 220 component, 426 compound-statement, 130, 1195 concatenation macro argument, see ## string, 30 condition, 131, 1196 conditions rules for, 131 conditional-expression throw-expression in, 124 conditional-expression, 124, 1195 conditionally-supported behavior seebehavior, conditionally-supported, 1 conflict, 12 conformance requirements, 5–6, 9 class templates, 5 classes, 5 general, 5–6 library, 5 method of description, 5 consistency linkage, 143 linkage specification, 175 type declaration, 61 const, 77 constructor and, 225, 258 destructor and, 225, 265 linkage of, 59, 143 overloading and, 291 const_cast, see cast, const const_local_iterator, 746 unordered associative containers, 746 constant, 24, 89 enumeration, 158 null pointer, 85 constant iterator, 830 constant-expression, 127, 1195 constexpr function, 148 construction, 275–278 dynamic cast and, 277 member access, 275 move, 427 pointer to member or base, 276 typeid operator, 277 virtual function call, 276 constructor, 257
© ISO/IEC 2011 – All rights reserved
address of, 259 array of class objects and, 270 converting, 263 copy, 257, 259, 260, 278–281, 433 elision, 284 implicitly declared, 279 implicitly defined, 281 inaccessible, 284 trivial, 280 default, 257, 258 exception handling, see exception handling, constructors and destructors explicit call, 259 implicitly called, 259 implicitly defined, 258 inheritance of, 258 inheriting, 286–288 move, 257, 259, 278–281 elision, 284 implicitly declared, 280 implicitly defined, 281 inaccessible, 284 trivial, 280 non-trivial, 258 random number distribution requirement, 921 random number engine requirement, 917, 918 type of, 259 union, 227 unspecified argument to, 114 constructor, conversion by, see conversion, user-defined constructor, default, see default constructor const-object undefined change to, 152 context non-deduced, 391 contextually converted to bool, see conversion, contextual continue and handler, 400 and try block, 400 control line, see preprocessing directives control-line, 412, 1206 conventions, 431 lexical, 17–33 conversion argument, 192 array-to-pointer, 82 bool, 84 boolean, 86 class, 262 contextual, 81
1273
ISO/IEC 14882:2011(E)
derived-to-base, 303 floating point, 84 floating to integral, 85 function-to-pointer, 82 implementation defined pointer integer, 106 implicit, 81, 262 implicit user-defined, 262 inheritance of user-defined, 265 integer rank, 86 integral, 84 integral to floating, 85 lvalue-to-rvalue, 82, 1212 narrowing, 215 overload resolution and pointer, 312 overload resolution and, 301 pointer, 85 pointer to member, 85 void*, 86 qualification, 82–83 return type, 137 standard, 81–86 static user-defined, 265 to signed, 84 to unsigned, 84 type of, 264 user-defined, 262, 263 usual arithmetic, 88 virtual user-defined, 265 conversion operator, see conversion, user defined conversion rank, 304 conversion-declarator, 263, 1203 conversion-function-id, 263, 1203 conversion-type-id, 263, 1203 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, 917 copy elision, see constructor, copy, elision; constructor, move, elision copy-initialization, 204 CopyInsertable into X, 732 count unordered associative containers, 752 , 192 , 111, 120 , 464 , 65, 435 , 433
1274
ctor-initializer, 271, 1203 <cuchar>, 447 cv-qualifier, 77 cv-qualifier, 183, 1201 cv-qualifier-seq, 183, 1201 , 447 , 447 d-char, 29, 1191 d-char-sequence, 29, 1191 DAG multiple inheritance, 235, 236 non-virtual base class, 236 virtual base class, 235, 236 data race, 15 data member, see member deadlock, 426 deallocation, see delete deallocation functions, 66 decay, see conversion, array to pointer; conversion, function to pointer DECAY_COPY, 1143 decimal-literal, 24, 1189 decl-specifier, 142, 1197 decl-specifier-seq, 142, 1197 declaration, 34, 140–181 array, 190 asm, 173 bit-field, 229 class name, 35 constant pointer, 187 default argument, 195–198 definition versus, 34 ellipsis in function, 99, 192 enumerator point of, 40 extern, 35 extern reference, 209 forward, 144 forward class, 219 function, 35, 192 local class, 231 member, 220 multiple, 61 name, 34 opaque enum, 35 overloaded, 289 overloaded name and friend, 253 parameter, 35, 192 parentheses in, 184, 186 pointer, 187 reference, 188
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
register, 143 static member, 35 storage class, 142 type, 186 typedef, 35 typedef as type, 145 declaration, 140, 1196 declaration-seq, 140, 1196 declaration-statement, 137, 1196 declaration hiding, see name hiding declarative region, 38 declarator, 35, 141, 182–215 array, 190 function, 191–195 meaning of, 186–198 multidimensional array, 191 pointer, 186 pointer to member, 189 reference, 187 declarator, 182, 1200 declarator-id, 183, 1201 decltype-specifier, 153, 1198 decrement operator overloaded, see overloading, decrement operator default access control, see access control, default default constructor random number distribution requirement, 921 seed sequence requirement, 915 default-initialization, 203 defaulted, 200 default argument overload resolution and, 301 default initializers overloading and, 291 deferred function, 1182 definition, 35 altermate, 447 class, 216, 220 class name as type, 218 constructor, 199 declaration as, 141 empty class, 216 function, 198–202 deleted, 201 explicitly-defaulted, 199 local class, 231 member function, 222 namespace, 161 nested class, 229 pure virtual function, 244 scope of class, 218
© ISO/IEC 2011 – All rights reserved
static member, 226 virtual function, 243 definitions, 2–5 delete, 66, 115, 116, 268 array, 115 destructor and, 116, 266 object, 115 operator, 447 overloading and, 68 type of, 268 undefined, 116 delete-expression, 115, 1194 deleter, 540 dependency-ordered before, 13 deprecated features, 102, 110 dereferencing, see also indirection derivation, see inheritance derived class most, see most derived class derived object most, see most derived object derived class, 233–245 destruction, 275–278 dynamic cast and, 277 member access, 275 pointer to member or base, 276 typeid operator, 277 virtual function call, 276 destructor, 265, 433 default, 265 exception handling, see exception handling, constructors and destructors explicit call, 266 implicit call, 266 implicitly defined, 265 non-trivial, 265 program termination and, 266 pure virtual, 266 union, 227 virtual, 266 diagnosable rules, 5 diagnostic message, see message, diagnostic digit, 23, 1188 digit-sequence, 28, 1190 digraph, see token, alternative, 21 directed acyclic graph, see DAG directive, preprocessing, see preprocessing directives discard random number engine requirement, 918 discard_block_engine generation algorithm, 930
1275
ISO/IEC 14882:2011(E)
state, 930 textual representation, 931 transition algorithm, 930 discarded-value expression, 89 discrete probability function bernoulli_distribution, 940 binomial_distribution, 941 discrete_distribution, 954 geometric_distribution, 942 negative_binomial_distribution, 943 poisson_distribution, 944 uniform_int_distribution, 938 discrete_distribution discrete probability function, 954 weights, 954 distribution, see random number distribution dominance virtual base class, 238 dot operator, see operator, class member access dynamic binding, see virtual function dynamic initialization, 63 dynamic type, see type, dynamic dynamic-exception-specification, 405, 1205 dynamic_cast, see cast, dynamic
endif-line, 411, 1206 engine, see random number engine engine adaptor, see random number engine adaptor engines with predefined parameters default_random_engine, 934 knuth_b, 934 minstd_rand, 933 minstd_rand0, 933 mt19937, 934 mt19937_64, 934 ranlux24, 934 ranlux24_base, 934 ranlux48, 934 ranlux48_base, 934 entity, 34 enum, 76 overloading and, 290 type of, 157, 159 underlying type, 159 enum-base, 158, 1198 enum-head, 158, 1198 enum-key, 158, 1198 enum-name, 157, 1198 enum-specifier, 158, 1198 enumeration, 157, 158 ECMA-262, 1 linkage of, 59 ECMAScript, 1087, 1119 scoped, 158 egrep, 1087 unscoped, 158 elaborated-type-specifier, 156, 1198 enumeration scope, 43 elaborated type specifier, see class name, elaborated enumeration type elif-group, 411, 1206 conversion to, 105 elif-groups, 411, 1206 static_cast elision conversion to, 105 copy, see constructor, copy, elision; constructor, enumerator move, elision definition, 36 copy constructor, see constructor, copy, elision value of, 158 move constructor, see constructor, move, elision enumerator, 158, 1199 ellipsis enumerator-definition, 158, 1199 conversion sequence, 99, 305 enumerator-list, 158, 1199 overload resolution and, 301 enum name else-group, 411, 1206 typedef, 147 EmplaceConstructible into X from args, 733 environment empty future object, 1177 program, 62 empty shared_future object, 1179 epoch, 607 empty-declaration, 140, 1197 equal_range encoding unordered associative containers, 752 multibyte, 31 equality-expression, 122, 1194 encoding-prefix, 28, 1190 equivalence end template type, 333 unordered associative containers, 752 type, 145, 218 end-of-file, 524 equivalent-key group, 745
1276
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
equivalent parameter declarations, 290 overloading and, 290 erase unordered associative containers, 751 escape-sequence, 26, 1190 escape character, see backslash escape sequence undefined, 27 Evaluation, 10 evaluation order of argument, 99 unspecified order of, 11, 64 unspecified order of argument, 99 unspecified order of function call, 99 example array, 190 class definition, 221 const, 187 constant pointer, 187 constructor, 259 constructor and initialization, 270 declaration, 35, 194 declarator, 184 definition, 35 delete, 268 derived class, 233 destructor and delete, 268 ellipsis, 192 enumeration, 159 explicit destructor call, 267 explicit qualification, 237 friend, 219 friend function, 251 function declaration, 193 function definition, 199 linkage consistency, 143 local class, 231 member function, 224, 251 nested type name, 231 nested class, 230 nested class definition, 230, 256 nested class forward declaration, 230 pointer to member, 189 pure virtual function, 244 scope of delete, 268 scope resolution operator, 237 static member, 226 subscripting, 190 typedef, 145 type name, 184 unnamed parameter, 199
© ISO/IEC 2011 – All rights reserved
variable parameter list, 192 virtual function, 242, 243 exception arithmetic, 87 undefined arithmetic, 87 <exception>, 475 exception handling, 400–410 allowing an exception, 407 constructors and destructors, 403 exception object, 402 constructor, 402 destructor, 402 function try block, 401 goto, 400 handler, 400, 402–405, 452 array in, 403 incomplete type in, 403 match, 404–405 pointer to function in, 403 rvalue reference in, 403 memory, 402 nearest handler, 402 rethrow, 402, 403 rethrowing, 402 switch, 400 terminate() called, 402, 403, 407 throwing, 401, 402 try block, 400 unexpected() called, 407 exception object, see exception handling, exception object exception specification, 405–408 compatible, 406 incomplete type and, 406 noexcept constant expression and, 406 virtual function and, 406 exception-declaration, 400, 1205 exception-specification, 405, 1205 exception::what message implementation-defined, 476 exclusive-or-expression, 123, 1195 execution agent, 1141 exit, 62, 64, 136 explicit-instantiation, 371, 1205 explicit-specialization, 373, 1205 explicitly captured, 94 explicit type conversion, see casting exponent-part, 28, 1190 exponential_distribution probability density function, 945
1277
ISO/IEC 14882:2011(E)
expression, 87–129 additive operators, 119 alignof, 116 assignment and compound assignment, 125 bitwise AND, 123 bitwise exclusive OR, 123 bitwise inclusive OR, 123 cast, 100, 117–118 class member access, 100 comma, 127 conditional operator, 124 constant, 127 const cast, 107 decrement, 102, 110 delete, 115 dynamic cast, 102 equality operators, 122 function call, 98 increment, 102, 110 lambda, 92–97 left-shift-operator, 121 logical AND, 123 logical OR, 124 multiplicative operators, 119 new, 111 noexcept, 116 order of evaluation of, 9 parenthesized, 90 pointer-to-member, 118 pointer to member constant, 109 postfix, 97–109 primary, 89–97 pseudo-destructor call, 100 reference, 87 reinterpret cast, 106 relational operators, 121 right-shift-operator, 121 rvalue reference, 87 sizeof, 111 static cast, 104 type identification, 103 unary, 109–117 unary operator, 109 expression, 127, 1195 expression-list, 97, 1193 expression-statement, 130, 1195 extended alignment, 80 extended integer type, 75 extended signed integer type, 75 extended unsigned integer type, 75 extension-namespace-definition, 161, 1199
1278
extern, 142 linkage of, 143 extern "C", 436, 447 extern "C++", 436, 447 external linkage, 59 extreme_value_distribution probability density function, 947 file, source, see source file final overrider, 240 find unordered associative containers, 751 finite state machine, 1076 fisher_f_distribution probability density function, 952 floating literal, see literal, floating floating-literal, 28, 1190 floating-point literal, see literal, floating floating-suffix, 28, 1190 floating point type, 76 implementation-defined, 76 for scope of declaration in, 135 for-init-statement, 133, 1196 for-range-declaration, 133, 1196 for-range-initializer, 133, 1196 formal argument, see parameter format specifier, 1076 forwarding call wrapper, 571 fractional-constant, 28, 1190 free store, 267 freestanding implementation, 6 free store, see also new, delete friend virtual and, 243 access specifier and, 253 class access and, 251 inheritance and, 253 local class and, 254 template and, 341 friend function access and, 251 inline, 253 linkage of, 253 member function and, 251 friend function nested class, 231 full-expression, 10 function, see also friend function; member function; inline function; virtual function, 193 allocation, 67, 113
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
comparison, 426 conversion, 263 deallocation, 67, 116, 268 definition, 36 global, 446, 450 handler, 426 linkage specification overloaded, 176 modifier, 426 observer, 427 operator, 313 overload resolution and, 293 plain old, 482 pointer to member, 119 replacement, 427 reserved, 427 viable, 293 virtual member, 447, 450 function invocation substitution, 149 function object, 566 binders, 577–579 mem_fn, 579–580 reference_wrapper, 571 type, 566 wrapper, 580–584 function pointer type, 77 function try block, see exception handling, function try block function, overloaded, see overloading function, virtual, see virtual function function-definition, 198, 1201 function-like macro, see macro, function-like function-specifier, 144, 1197 function-try-block, 400, 1205 functions candidate, 365 function argument, see argument function call, 99 recursive, 99 undefined, 107 function call operator overloaded, 315 function parameter, see parameter function prototype, 41 function return, see return function return type, see return type fundamental alignment, 80 fundamental type destructor and, 267 fundamental type conversion, see conversion, userdefined future
© ISO/IEC 2011 – All rights reserved
shared state, 1172 gamma_distribution probability density function, 945 generate seed sequence requirement, 916 generated destructor, see destructor, default generation algorithm discard_block_engine, 930 independent_bits_engine, 931 linear_congruential_engine, 926 mersenne_twister_engine, 927 shuffle_order_engine, 933 subtract_with_carry_engine, 929 geometric_distribution discrete probability function, 942 global, 42 global namespace, 42 global namespace scope, 42 global scope, 42 glvalue, 78 goto and handler, 400 and try block, 400 initialization and, 137 grammar regular expression, 1119 grep, 1087 group, 411, 1205 group-part, 411, 1206 h-char, 22, 1188 h-char-sequence, 22, 1188 handler, see exception handling, handler handler, 400, 1205 handler-seq, 400, 1205 happens before, 14 hash instantiation restrictions, 584 hash code, 745 hash function, 745 hash tables, see unordered associative containers hash_function unordered associative containers, 749 hasher unordered associative containers, 746 header C, 447, 450, 1229 C library, 436 C++ library, 434 name, 22
1279
ISO/IEC 14882:2011(E)
header-name, 22, 1188 hex-quad, 19, 1187 hexadecimal-digit, 25, 1189 hexadecimal-escape-sequence, 26, 1190 hexadecimal-literal, 25, 1189 hiding, see name hiding high-order bit, 7 hosted implementation, 6
independent_bits_engine generation algorithm, 931 state, 931 textual representation, 932 transition algorithm, 931 indeterminately sequenced, 11 indirection, 109 inheritance, 233 init-declarator, 182, 1200 id init-declarator-list, 182, 1200 qualified, 91 initialization, 62, 202–215 id-expression, 90 aggregate, 205 id-expression, 89, 1192 array, 205 identifier, 22–23, 90, 141 array of class objects, 208, 270 identifier, 22, 1188 automatic, 137, 138 identifier-list, 412, 1206 automatic object, 202 identifier-nondigit, 22, 1188 base class, 271, 272 if-group, 411, 1206 character array, 208 if-section, 411, 1206 character array, 208 ill-formed program, see program, ill-formed class member, 203 immolation class object, see also constructor, 205, 269–275 self, 376 const, 152, 205 implementation const member, 272 freestanding, 435 constant, 62 hosted, 435 constructor and, 269 implementation limits, see limits, implementation copy, 204 implementation-defined, 447, 455, 466, 472, 474–477, default, 202 1002, 1055, 1227 default constructor and, 269 implementation-defined behavior, see behavior, implemen- definition and, 141 tation-defined direct, 204 implementation-dependent, 1027 dynamic, 62 implementation-generated, 35 explicit, 269 implicit object parameter, 293 jump past, 137 implicitly captured, 94 list-initialization, 211–215 implicitly-declared default constructor, see construclocal static, 138 tor, default, 258 member, 271 implicit conversion, see conversion, implicit member function call during, 274 implied object argument, 293 member object, 272 implicit conversion sequences, 294 order of, 62, 234 non-static member function and, 294 order of base class, 273 inclusion order of member, 273 conditional, see preprocessing directive, condiorder of virtual base class, 273 tional inclusion overloaded assignment and, 270 source file, see preprocessing directives, sourceparameter, 98 file inclusion reference, 188, 209 inclusive-or-expression, 123, 1195 reference member, 272 incomplete, 119 run-time, 62 increment static and thread, 62 bool, 102, 110 static member, 226 increment operator static object, 62 overloaded, see overloading, increment operator static object, 202
1280
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
union, 208, 228 virtual base class, 281 initializer base class, 199 member, 199 pack expansion, 275 scope of member, 274 temporary and declarator, 261 initializer, 202, 1202 initializer-clause, 202, 1202 initializer-list, 202, 1202 initializer-list constructor seed sequence requirement, 915 , 480 injected-class-name, 216 inline, 450 inline linkage of, 59 inline function, 145 insert unordered associative containers, 750, 751 instantiation explicit, 370 point of, 364 template implicit, 367 instantiation units, 18 integer literal, see literal, integer integer representation, 69 integer-literal, 24, 1189 integer-suffix, 25, 1189 integer type, 76 integral type, 76 sizeof, 75 inter-thread happens before, 13 internal linkage, 59 interval boundaries piecewise_constant_distribution, 955 piecewise_linear_distribution, 957 invocation macro, 416 isctype regular expression traits, 1078 iteration-statement, 133, 136, 1196 Jessie, 263 jump-statement, 136, 1196 key_eq unordered associative containers, 749 key_equal unordered associative containers, 746
© ISO/IEC 2011 – All rights reserved
key_type unordered associative containers, 746 keyword, 23–24 label, 137 case, 130, 132 default, 130, 132 scope of, 41, 130 labeled-statement, 130, 1195 lambda-capture, 92, 1192 lambda-declarator, 92, 1193 lambda-expression, 92, 1192 lambda-introducer, 92, 153, 1192 lattice, see DAG, subobject layout bit-field, 229 class object, 221, 234 layout-compatible type, 159 layout-compatible type, 74 left shift undefined, 121 left shift operator, 121 lexical conventions, see conventions, lexical library C standard, 425, 432, 434, 436, 1225, 1227, 1229 C++ standard, 424, 447, 449, 452 library clauses, 6 lifetime, 69 limits implementation, 3 , 456 line splicing, 17 linear_congruential_engine generation algorithm, 926 modulus, 926 state, 926 textual representation, 927 transition algorithm, 926 linkage, 34, 59–61 const and, 59 external, 59, 436, 446, 447 implementation-defined object, 176 inline and, 59 internal, 59 no, 59, 60 static and, 59 linkage specification, see specification, linkage linkage-specification, 174, 1199 literal, 24–33, 89 base of integer, 25 boolean, 31
1281
ISO/IEC 14882:2011(E)
char16_t, 26 char32_t, 26 character, 26 constant, 24 decimal, 25 double, 28 float, 28 floating, 28 hexadecimal, 25 char, 27 integer, 24, 25 long, 25 long double, 28 multicharacter, 27 implementation-defined value of, 27 narrow-character, 26 octal, 25 pointer, 31 string, 28, 29 char16_t, 29, 30 char32_t, 29, 30 implementation-defined, 30 narrow, 29, 30 type of, 30 undefined change to, 30 wide, 29, 30 type of character, 26 type of floating point, 28 type of integer, 25 unsigned, 25 user defined, 31 literal, 24, 1189 literal type, 74 literal-operator-id, 316, 1204 load_factor unordered associative containers, 753 local lambda expression, 94 local variable, 41 local_iterator, 746 unordered associative containers, 746 locale, 1076, 1077, 1079, 1087 locale-specific behavior, see behavior, locale-specific local class friend, 254 member function in, 223 scope of, 231 local scope, see block scope local variable destruction of, 136, 137 logical-and-expression, 123, 1195 logical-or-expression, 124, 1195
1282
lognormal_distribution probability density function, 949 long typedef and, 142 long-long-suffix, 25, 1189 long-suffix, 25, 1189 lookup argument-dependent, 49 class member, 57 class member, 52 elaborated type specifier, 56–57 member name, 236 name, 34, 45–59 namespace aliases and, 59 namespace member, 53 qualified name, 51–56 template name, 352 unqualified name, 45 using-directives and, 59 lookup_classname regular expression traits, 1121 lookup_classname regular expression traits, 1078 lookup_collatename regular expression traits, 1078 low-order bit, 7 lowercase, 432 lparen, 412, 1206 lvalue, 78, 1212 lvalue reference, 76, 188 macro argument substitution, 416 function-like, 415, 416 arguments, 416 masking, 450 name, 415 object-like, 415, 416 pragma operator, 423 predefined, 421 replacement, 415–420 replacement list, 415 rescanning and replacement, 418 scope of definition, 418 main(), 62 implementation-defined linkage of, 62 implementation-defined parameters to, 62 parameters to, 62 return from, 62, 64 match_results as sequence, 1103
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
matched, 1076 max random number distribution requirement, 921 uniform random number generator requirement, 916 max_bucket_count unordered associative containers, 752 max_load_factor unordered associative containers, 753 mean normal_distribution, 948 poisson_distribution, 944 mem-initializer, 271, 1204 mem-initializer-id, 271, 1204 mem-initializer-list, 271, 1203 member class static, 66 enumerator, 160 static, 225 template and static, 336 member access operator overloaded, 315 member function call undefined, 223 class, 222 const, 224, 225 constructor and, 259 destructor and, 266 friend, 253 inline, 222 local class, 231 nested class, 256 nonstatic, 223 overload resolution and, 293 static, 225, 226 this, 224 union, 227 volatile, 224 member names, 41 member subobject, 8 member-declaration, 220, 1202 member-declarator, 220, 1203 member-declarator-list, 220, 1203 member-specification, 220, 1202 members, 41 member data static, 226 member pointer to, see pointer to member memory location, 7 memory model, 7 memory management, see also new, delete
© ISO/IEC 2011 – All rights reserved
mersenne_twister_engine generation algorithm, 927 state, 927 textual representation, 928 transition algorithm, 927 message diagnostic, 2, 5 min random number distribution requirement, 921 uniform random number generator requirement, 916 modification order, 12 most derived class, 8 most derived object, 8 bit-field, 8 zero size subobject, 8 move class object, see constructor, move; assignment, move MoveInsertable into X, 733 multi-pass guarantee, 833 multibyte character, see character, multibyte multicharacter literal, see literal, multicharacter multiple threads, see threads, multiple multiple inheritance, 233, 234 virtual and, 243 multiplicative-expression, 119, 1194 mutable, 142 mutable iterator, 830 mutex types, 1149 name, 23, 34, 90 address of cv-qualified, 109 dependent, 358, 364 elaborated enum, 156 global, 42 length of, 23 macro, see macro, name point of declaration, 39 predefined macro, see macro, predefined qualified, 51 reserved, 446 scope of, 38 unqualified, 45 name hiding function, 292 overloading versus, 292 using-declaration and, 169 named-namespace-definition, 161, 1199 namespace, 434, 1229
1283
ISO/IEC 14882:2011(E)
alias, 164 definition, 161 global, 446 member definition, 163 unnamed, 162 namespace-alias, 164, 1199 namespace-alias-definition, 164, 1199 namespace-body, 161, 1199 namespace-definition, 161, 1199 namespace-name, 161, 1199 namespaces, 161–173 name class, see class name name hiding, 39, 44, 91, 137 class definition, 218 user-defined conversion and, 262 name space label, 130 narrowing conversion, 215 NDEBUG, 436 negative_binomial_distribution discrete probability function, 943 nested-name-specifier, 91, 1192 nested class local class, 231 scope of, 229 , 467 new, 66, 111, 113 array of class objects and, 114 constructor and, 114 default constructor and, 114 exception and, 114 initialization and, 114 operator, 447 scoping and, 112 storage allocation, 112 type of, 267 unspecified constructor and, 114 unspecified order of evaluation, 114 new-declarator, 112, 1194 new-expression, 112, 1193 new-initializer, 112, 1194 new-line, 412, 1206 new-placement, 112, 1194 new-type-id, 112, 1194 new_handler, 67 no linkage, 59 noexcept-expression, 116, 1194 noexcept-specification, 406, 1205 non-directive, 412, 1206 non-throwing, 408 nondigit, 23, 1188
1284
nonzero-digit, 25, 1189 noptr-abstract-declarator, 183, 1201 noptr-abstract-pack-declarator, 184, 1201 noptr-declarator, 182, 1200 noptr-new-declarator, 112, 1194 normal distributions, 948–953 normal_distribution mean, 948 probability density function, 948 standard deviation, 948 normative references, see references, normative notation syntax, 6 notify_all_at_thread_exit, 1163 NTBS, 433, 1064, 1237, 1239 static, 433 NTCTS, 427 NTMBS, 433 static, 433 number hex, 27 octal, 27 numeric_limits, 456 numeric_limits, 76 object, see also object model, 7, 34 byte copying and, 73 complete, 8 definition, 36 delete, 115 destructor static, 64 destructor and placement of, 267 linkage specification, 176 local static, 66 undefined deleted, 68 unnamed, 259 object expression, 101 object model, 7–8 object pointer type, 77 object representation, 73 object type, 7, 74 object, exception, see exception handling, exception object object-like macro, see macro, object-like object class, see also class object object lifetime, 69–72 object temporary, see temporary object type, 74 observable behavior, see behavior, observable octal-digit, 25, 1189 octal-escape-sequence, 26, 1190
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
octal-literal, 24, 1189 odr-used, 36 one-definition rule, 36–38 opaque-enum-declaration, 158, 1198 operation atomic, 12–15 operator, 24, 314 *=, 125 +=, 110, 125 -=, 125 /=, 125 =, 125 %=, 125 &=, 125 ˆ=, 125 |=, 125 additive, 119 address-of, 109 assignment, 125, 433 bitwise, 123 bitwise AND, 123 bitwise exclusive OR, 123 bitwise inclusive OR, 123 cast, 109, 183 class member access, 100 comma, 127 conditional expression, 124 copy assignment, see assignment, copy decrement, 102, 109, 110 division, 119 equality, 122 function call, 98, 313 greater than, 121 greater than or equal to, 121 increment, 102, 109, 110 indirection, 109 inequality, 122 less than, 121 less than or equal to, 121 logical AND, 123 logical negation, 109, 110 logical OR, 124 move assignment, see assignment, move multiplication, 119 multiplicative, 119 one’s complement, 109, 110 overloaded, 87, 313 pointer to member, 118 pragma, see macro, pragma operator precedence of, 9
© ISO/IEC 2011 – All rights reserved
relational, 121 remainder, 119 scope resolution, 91, 113, 223, 233, 244 side effects and comma, 127 side effects and logical AND, 124 side effects and logical OR, 124 sizeof, 109, 111 subscripting, 98, 313 unary, 109 unary minus, 109, 110 unary plus, 109, 110 operator, 313, 1204 operator delete, see also delete, 113, 116, 268 operator new, see also new, 113 operator overloading, see overloading, operator operator!= random number distribution requirement, 922 random number engine requirement, 918 operator() random number distribution requirement, 921 random number engine requirement, 918 uniform random number generator requirement, 916 operator-function-id, 313, 1204 operator> random number distribution requirement, 922 random number engine requirement, 919 operator , see delete operator left shift, see left shift operator operator right shift, see right shift operator operator use scope resolution, 226 optimization of temporary, see elimination of temporary order of evaluation in expression, see expression, order of evaluation of ordering function template partial, 349 order of execution base class constructor, 259 base class destructor, 265 constructor and static objects, 271 constructor and array, 269 destructor, 265 destructor and array, 266
1285
ISO/IEC 14882:2011(E)
member constructor, 259 member destructor, 265 original-namespace-definition, 161, 1199 original-namespace-name, 161, 1199 over-aligned type, 80 overflow, 87 undefined, 87 overloaded function, see overloading overloaded operator, see overloading, operator overloadedfunction address of, 311 overloaded function address of, 110 overloaded operator inheritance of, 314 overloading, 192, 218, 289–320, 347 access control and, 292 address of overloaded function, 311 argument lists, 293–300 assignment operator, 314 binary operator, 314 built-in operators and, 317 candidate functions, 293–300 declaration matching, 291 declarations, 289 example of, 289 function call operator, 315 member access operator, 315 operator, 313–317 prohibited, 289 resolution, 292–311 best viable function, 301–314 contexts, 293 function call syntax, 295–297 function template, 397 implicit conversions and, 303–311 initialization, 299, 300 operators, 297 scoping ambiguity, 237 template, 349 template name, 352 viable functions, 300–314 subscripting operator, 315 unary operator, 314 user-defined literal, 316 using directive and, 173 using-declaration and, 169 overloads floating point, 913 overrider final, 240
1286
own, 540 pair tuple interface to, 504 param random number distribution requirement, 921 seed sequence requirement, 916 param_type random number distribution requirement, 921 parameter, 3 catch clause, 3 function, 3 function-like macro, 3 reference, 188 scope of, 41 template, 3, 35 void, 192 parameter declaration, 35 parameter-declaration, 192, 1201 parameter-declaration-clause, 192, 1201 parameter-declaration-list, 192, 1201 parameterized type, see template parameters macro, 416 parameters-and-qualifiers, 183, 1200 parameter list variable, 99, 192 period, 433 phases of translation, see translation, phases piecewise construction, 506 piecewise_constant_distribution interval boundaries, 955 probability density function, 955 weights, 955 piecewise_linear_distribution interval boundaries, 957 probability density function, 957 weights at boundaries, 957 placement syntax new, 113 pm-expression, 118, 1194 POD class, 217 POD struct, 217 POD union, 217 POF, 482 point of declaration, 39 pointer, see also void* safely-derived, 68–69 to traceable object, 452 to traceable object, 68 zero, 85
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
pointer literal, see literal, pointer pointer, integer representation of safely-derived, 69 pointer-literal, 31, 1191 pointer to member, 76, 118 Poisson distributions, 944–948 poisson_distribution discrete probability function, 944 mean, 944 POSIX, 1 extended regular expressions, 1087 regular expressions, 1087 postfix-expression, 97, 1193 postfix ++ and -overloading, 316 postfix ++, 102 postfix --, 102 potential scope, 38 potentially evaluated, 36 pp-number, 22, 1188 pp-tokens, 412, 1206 precedence of operator, see operator, precedence of prefix L, 27, 30 prefix ++ and -overloading, 316 prefix ++, 110 prefix --, 110 preprocessing directive, 411 conditional inclusion, 413 preprocessing directives, 411–423 error, 421 header inclusion, 414 line control, 420 macro replacement, see macro, replacement null, 421 pragma, 421 source-file inclusion, 414 preprocessing-file, 411, 1205 preprocessing-op-or-punc, 24, 1189 preprocessing-token, 20, 1188 primary equivalence class, 1077 primary-expression, 89, 1192 private, see access control, private probability density function cauchy_distribution, 951 chi_squared_distribution, 950 exponential_distribution, 945 extreme_value_distribution, 947 fisher_f_distribution, 952 gamma_distribution, 945 lognormal_distribution, 949
© ISO/IEC 2011 – All rights reserved
normal_distribution, 948 piecewise_constant_distribution, 955 piecewise_linear_distribution, 957 student_t_distribution, 953 uniform_real_distribution, 939 weibull_distribution, 946 program, 59 ill-formed, 3 start, 62–64 termination, 64–65 well-formed, 5, 9 program execution, 8–11 abstract machine, 8–9 as-if rule, see as-if rule promotion bool to int, 84 floating point, 84 integral, 83 protected, see access control, protected protection, see access control, 452 prvalue, 78 pseudo-destructor-name, 100 pseudo-destructor-name, 98, 1193 ptr-abstract-declarator, 183, 1201 ptr-declarator, 182, 1200 ptr-operator, 183, 1201 ptrdiff_t, 120 implementation defined type of, 120 public, see access control, public punctuator, 24 pure-specifier, 220, 1203 q-char, 22, 1188 q-char-sequence, 22, 1188 qualification explicit, 51 qualified-id, 91, 1192 qualified-namespace-specifier, 164, 1199 r-char, 29, 1191 r-char-sequence, 29, 1191 random number distribution bernoulli_distribution, 940 binomial_distribution, 941 chi_squared_distribution, 950 discrete_distribution, 954 exponential_distribution, 945 extreme_value_distribution, 947 fisher_f_distribution, 952 gamma_distribution, 945 geometric_distribution, 942
1287
ISO/IEC 14882:2011(E)
lognormal_distribution, 949 negative_binomial_distribution, 943 normal_distribution, 948 piecewise_constant_distribution, 955 piecewise_linear_distribution, 957 poisson_distribution, 944 requirements, 920–923 student_t_distribution, 953 uniform_int_distribution, 938 uniform_real_distribution, 939 random number distributions Bernoulli, 940–944 normal, 948–953 Poisson, 944–948 sampling, 954–959 uniform, 938–940 random number engine linear_congruential_engine, 926 mersenne_twister_engine, 927 requirements, 917–919 subtract_with_carry_engine, 928 with predefined parameters, 933–935 random number engine adaptor discard_block_engine, 930 independent_bits_engine, 931 shuffle_order_engine, 932 with predefined parameters, 933–935 random number generation, 914–959 distributions, 938–959 engines, 925–933 predefined engines and adaptors, 933–935 requirements, 914–923 synopsis, 923–925 utilities, 936–938 random number generator, see uniform random number generator random_device implementation leeway, 935 raw string literal, 29 raw-string, 29, 1191 reaching scope, 94 ready, 1103, 1173 redefinition typedef, 146 ref-qualifier, 183, 1201 reference, 76 assignment to, 126 call by, 99 lvalue, 76 null, 189 rvalue, 76
1288
sizeof, 111 reference collapsing, 189 reference-compatible, 209 reference-related, 209 references normative, 1 regex_iterator end-of-sequence, 1114 regex_token_iterator end-of-sequence, 1116 regex_traits specializations, 1090 region declarative, 34, 38 register, 142 regular expression, 1076–1121 grammar, 1119 matched, 1076 requirements, 1077 regular expression traits, 1119 char_class_type, 1077 isctype, 1078 lookup_classname, 1121 lookup_classname, 1078 lookup_collatename, 1078 requirements, 1077, 1090 transform, 1121 transform, 1078 transform_primary, 1121 transform_primary, 1078 translate, 1121 translate, 1078 translate_nocase, 1121 translate_nocase, 1078 rehash unordered associative containers, 753 reinterpret_cast, see cast, reinterpret relational-expression, 121, 1194 relaxed pointer safety, 69 release sequence, 13 remainder operator, see remainder operator replacement macro, see macro, replacement replacement-list, 412, 1206 representation object, 73 value, 73 requirements, 429 Allocator, 441 container, 728, 745, 757, 758, 1103
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
not required for unordered associated containers, 745 CopyAssignable, 437 CopyConstructible, 437 DefaultConstructible, 437 Destructible, 437 EqualityComparable, 437 Hash, 440 iterator, 829 LessThanComparable, 437 MoveAssignable, 437 MoveConstructible, 437 NullablePointer, 440 numeric type, 902 random number distribution, 920–923 random number engine, 917–919 regular expression traits, 1077, 1090 seed sequence, 915–916 sequence, 1103 uniform random number generator, 916–917 unordered associative container, 745 reraise, see exception handling, rethrow rescanning and replacement, see macro, rescanning and replacement reserved identifier, 23 reset, 540 reset random number distribution requirement, 921 resolution, see overloading, resolution restriction, 449, 450, 452 address of bit-field, 229 anonymous union, 228 bit-field, 229 constructor, 258, 259 destructor, 265 extern, 143 local class, 231 operator overloading, 313 overloading, 313 pointer to bit-field, 229 reference, 188 register, 143 static, 143 static member local class, 227 union, 227 result_type entity characterization based on, 914 result_type random number distribution requirement, 921 seed sequence requirement, 915
© ISO/IEC 2011 – All rights reserved
uniform random number generator requirement, 916 rethrow, see exception handling, rethrow return, 136 and handler, 400 and try block, 400 constructor and, 137 reference and, 209 return statement, see return return type, 193 overloading and, 289 right shift implementation defined, 121 right shift operator, 121 rounding, 85 rvalue, 78 lvalue conversion to, see conversion, lvalue to rvalue lvalue conversion to, 1212 rvalue reference, 76, 188 s-char, 29, 1191 s-char-sequence, 28, 1191 safely-derived pointer, 68 integer representation, 69 sampling distributions, 954–959 scalar type, 74 scope, 1, 34, 38–45, 141 anonymous union at namespace, 228 block, 41 class, 42 declarations and, 38–41 destructor and exit from, 136 enumeration, 43 exception declaration, 41 function, 41 function prototype, 41 global, 42 global namespace, 42 iteration-statement, 133 macro definition, see macro, scope of definition namespace, 41 name lookup and, 45–59 overloading and, 291 potential, 38 selection-statement, 131 template parameter, 43 scope name hiding and, 44 scope resolution operator, 51 seed random number engine requirement, 918
1289
ISO/IEC 14882:2011(E)
seed sequence, 915 requirements, 915–916 selection-statement, 131, 1196 semantics class member, 100 separate compilation, see compilation, separate separate translation, see compilation, separate sequence ambiguous conversion, 304 implicit conversion, 303 standard conversion, 81 sequence constructor seed sequence requirement, 915 Sequenced before, 11 sequencing operator, see comma operator setlocale, 433 shared state, see future, shared state shift-expression, 121, 1194 shift operator, see left shift operator, right shift operator short typedef and, 142 shuffle_order_engine generation algorithm, 933 state, 932 textual representation, 933 transition algorithm, 932 side effects, 8, 10–15, 124, 130, 261, 273, 284, 418, 452 visible, 14 visible sequence of, 14 sign, 28, 1190 signal, 9 signature, 4 signed typedef and, 142 signed integer type, 75 simple call wrapper, 571 simple-declaration, 140, 1197 simple-escape-sequence, 26, 1190 simple-template-id, 325, 1204 simple-type-specifier, 153, 1198 size seed sequence requirement, 916 size_t, 111 sizeof empty class, 216 smart pointers, 550–566 source file, 17, 436, 447 source file character, see character, source file space
1290
white, 20 specialization class template, 327 class template partial, 343 template, 366 template explicit, 373 special member function, see constructor, destructor, inline function, user-defined conversion, virtual function specification linkage, 174–177 extern, 174 implementation-defined, 174 nesting, 174 template argument, 379 specifications C standard library exception, 452 C++, 452 implementation-defined exception, 452 specifier, 142–157 friend, 452 constexpr, 147 constructor, 148 function, 148 cv-qualifier, 152 declaration, 142 explicit, 145 friend, 147 function, 144 inline, 145 missing storage class, 143 static, 143 storage class, 142 type, see type specifier typedef, 145 virtual, 145 specifier access, see access specifier stable algorithm, 428, 451 stack unwinding see exception handling, constructors and destructors, 403 standard structure of, 6 standard deviation normal_distribution, 948 standard-layout types, 74 standard-layout class, 217 standard-layout struct, 217 standard-layout union, 217 standard integer type, 75 standard signed integer type, 75
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
standard unsigned integer type, 75 start program, 62 startup program, 437, 447 state discard_block_engine, 930 independent_bits_engine, 931 linear_congruential_engine, 926 mersenne_twister_engine, 927 object, 427 shuffle_order_engine, 932 subtract_with_carry_engine, 929 statement, 130–139 continue in for, 134 break, 136 compound, 130 continue, 136 declaration, 137 declaration in if, 131 declaration in switch, 131 declaration in for, 135 declaration in switch, 133 declaration in while, 133 do, 133, 134 empty, 130 expression, 130 for, 133, 134 goto, 130, 136, 137 if, 131, 132 iteration, 133–136 jump, 136 labeled, 130 null, 130 selection, 131–133 switch, 131, 132, 136 while, 133 statement, 130, 1195 statement-seq, 130, 1195 static, 142 destruction of local, 138 linkage of, 59, 143 overloading and, 289 static initialization, 63 static storage duration, 66 static type, see type, static static_assert, 141 static_assert-declaration, 140, 1197 static_cast, see cast, static statment for, 135
© ISO/IEC 2011 – All rights reserved
<stddef.h>, 27, 30 <stdexcept>, 484 storage-class-specifier, 142, 1197 storage class, 34 storage duration, 65–69 automatic, 65, 66 class member, 69 dynamic, 65–69, 112 local object, 66 register, 66 static, 65, 66 thread, 65, 66 storage management, see new, delete stream arbitrary-positional, 425 repositional, 427 streambuf implementation-defined, 990 strict pointer safety, 69 string distinct, 30 null-terminated byte, 433 null-terminated character type, 427 null-terminated multibyte, 433 sizeof, 31 type of, 30 string literal, see literal, string string-literal, 28, 1190 stringize, see # struct standard-layout, 217 struct class versus, 216 structure, 216 structure tag, see class name student_t_distribution probability density function, 953 sub-expression, 1077 subobject, see also object model, 8 subscripting operator overloaded, 315 subsequence rule overloading, 309 subtract_with_carry_engine carry, 929 generation algorithm, 929 state, 929 textual representation, 929 transition algorithm, 929 subtraction implementation defined pointer, 120
1291
ISO/IEC 14882:2011(E)
subtraction operator, 119 suffix E, 28 e, 28 F, 28 f, 28 L, 25, 28 l, 25, 28 U, 25 u, 25 summary x C++ 2003, 1218 compatibility with ISO C, 1209 swappable, 439 swappable with, 438 switch and handler, 400 and try block, 400 synchronize with, 13 synonym, 164 type name as, 145 syntax class member, 100 target object, 570 template, 321–399 definition of, 321 function, 378 member function, 335 primary, 343 template, 321 template parameter, 35 template-argument, 325, 1205 template-argument-list, 325, 1204 template-declaration, 321, 1204 template-id, 325, 1204 template-name, 325, 1204 template-parameter, 322, 1204 template-parameter-list, 321, 1204 template name linkage of, 321 template parameter scope, 43 temporary, 260 constructor for, 260 destruction of, 260 destructor for, 260 elimination of, 260, 284 implementation-defined generation of, 260 order of destruction of, 261 terminate(), 409 called, 402, 403, 407, 409
1292
termination program, 62, 65 terminology pointer, 77 text-line, 412, 1206 textual representation discard_block_engine, 931 independent_bits_engine, 932 shuffle_order_engine, 933 subtract_with_carry_engine, 929 this, 89, 224 type of, 224 this pointer, see this thread, 12 thread of execution, 12 thread storage duration, 66 thread, blocked, 425 thread_local, 142 threads multiple, 12–15 throw, 400 throw-expression, 400, 1205 throwing, see exception handling, throwing timed mutex types, 1152 token, 21 alternative, 21 preprocessing, 20–21 token, 21, 1188 traceable pointer object, 68, 452 trailing-return-type, 183, 1200 trailing-type-specifier, 151, 1197 trailing-type-specifier-seq, 151, 1198 traits, 428 transfer ownership, 540 transform regular expression traits, 1121 transform regular expression traits, 1078 transform_primaryl regular expression traits, 1121 transform_primary regular expression traits, 1120 transform_primaryl regular expression traits, 1078 TransformationTrait, 586 transition algorithm discard_block_engine, 930 independent_bits_engine, 931 linear_congruential_engine, 926 mersenne_twister_engine, 927 shuffle_order_engine, 932
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
subtract_with_carry_engine, 929 translate regular expression traits, 1121 translate regular expression traits, 1078 translate_nocase regular expression traits, 1121 translate_nocase regular expression traits, 1078 translation phases, 17–18 separate, see compilation, separate translation unit, 17 translation units, 59 translation-unit, 59, 1192 translation unit, 59 name and, 34 trigraph sequence, 17, 19 trivial types, 74 trivially copyable class, 216 trivially copyable types, 74 trivial class, 216 trivial class type, 114 trivial type, 114 truncation, 85 try, 400 try block, see exception handling, try block try-block, 400, 1205 tuple and pair, 504 type, 34, 72–78 arithmetic, 76 array, 76, 193 bitmask, 431, 432 Boolean, 75 char, 75 char16_t, 75 char32_t, 75 character, 75 character container, 425 class and, 216 compound, 76 const, 151 destination, 204 double, 76 dynamic, 2, 3 enumerated, 76, 431 enumeration underlying, 159 example of incomplete, 73 extended integer, 75 extended signed integer, 75
© ISO/IEC 2011 – All rights reserved
extended unsigned integer, 75 float, 76 floating point, 75 function, 76, 191–193 fundamental, 75 sizeof, 75 incomplete, 36, 37, 40, 73, 82, 98, 100–102, 104, 109, 111, 116, 126, 233 int, 75 integral, 75 long, 75 long double, 76 long long, 75 multi-level mixed pointer and pointer to member, 83 multi-level pointer to member, 83 over-aligned, 80 POD, 74 pointer, 76 polymorphic, 240 short, 75 signed char, 75 signed integer, 75 standard integer, 75 standard signed integer, 75 standard unsigned integer, 75 static, 4 trivially copyable, 73 underlying wchar_t, 75 unsigned, 75 unsigned char, 75 unsigned int, 75 unsigned long, 75 unsigned long long, 75 unsigned short, 75 unsigned integer, 75 void, 76 volatile, 151 wchar_t, 75 type generator, see template type specifier auto, 156 const, 152 elaborated, 156 simple, 153 volatile, 152 type-id, 183, 1201 type-id-list, 405, 1205 type-name, 153, 1198 type-parameter, 322, 1204 type-specifier
1293
ISO/IEC 14882:2011(E)
bool, 153 wchar_t, 153 type-specifier, 151, 1197 type-specifier-seq, 151, 1198 type_info, 103 typedef function, 193 typedef overloading and, 290 typedef-name, 145, 1197 typeid, 103 construction and, 277 destruction and, 277 , 473 typename, 156 typename-specifier, 353, 1205 types implementation-defined, 431 implementation-defined exception, 452 type checking argument, 99 type conversion, explicit, see casting type name, 183 nested, 231 scope of, 231 type pun, 107 type specifier auto, 153 char, 153 char16_t, 153 char32_t, 153 decltype, 153, 155 double, 153 elaborated, 56 enum, 156 float, 153 int, 153 long, 153 short, 153 signed, 153 unsigned, 153 void, 153 volatile, 153 ud-suffix, 32, 1191 unary function, 571 unary operator overloaded, 314 unary-expression, 109, 1193 unary-operator, 109, 1193 UnaryTypeTrait, 585
1294
unary operator interpretation of, 314 unblock, 428 uncaught_exception(), 410 undefined, 427, 446, 447, 449, 964, 965, 968–971, 976, 980, 1005 undefined behavior, see behavior, undefined, 859 underlying type, 75 unevaluated operand, 88 unexpected(), 407, 410 called, 407 Unicode required set, 422 uniform distributions, 938–940 uniform random number generator requirements, 916–917 uniform_int_distribution discrete probability function, 938 uniform_real_distribution probability density function, 939 union standard-layout, 217 union, 76, 227 class versus, 216 anonymous, 228 global anonymous, 228 unique pointer, 540 unit translation, 436, 446 universal character name, 17 universal-character-name, 19, 1187 unnamed-namespace-definition, 161, 1199 unordered associative containers, 745–819 begin, 752 bucket, 752 bucket_count, 752 bucket_size, 752 cbegin, 752 cend, 752 clear, 751 complexity, 745 const_local_iterator, 746 count, 752 end, 752 equal_range, 752 equality function, 745 equivalent keys, 745, 809, 816 erase, 751 exception safety, 754 find, 751 hash function, 745 hash_function, 749
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
hasher, 746 insert, 750, 751 iterator invalidation, 754 iterators, 753 key_eq, 749 key_equal, 746 key_type, 746 lack of comparison operators, 745 load_factor, 753 local_iterator, 746 max_bucket_count, 752 max_load_factor, 753 rehash, 753 requirements, 745, 754 unique keys, 745, 805, 813 unordered_map element access, 808 unique keys, 805 unordered_multimap equivalent keys, 809 unordered_multiset equivalent keys, 816 unordered_set unique keys, 813 unqualified-id, 89, 1192 unsequenced, 11 unsigned typedef and, 142 unsigned-suffix, 25, 1189 unsigned integer type, 75 unspecified, 468, 469, 473, 888, 1053, 1233, 1235 unspecified behavior, see behavior, unspecified, 969 unwinding stack, 403 uppercase, 432, 446 user-defined literal, see literal, user defined overloaded, 316 user-defined-character-literal, 31, 1191 user-defined-floating-literal, 31, 1191 user-defined-integer-literal, 31, 1191 user-defined-literal, 31, 1191 user-defined-string-literal, 31, 1191 user-provided, 200 Uses-allocator construction, 532 using-declaration, 165–171 using-declaration, 165, 1199 using-directive, 171–173 using-directive, 171, 1199 usual arithmetic conversions, see conversion, usual arithmetic
© ISO/IEC 2011 – All rights reserved
valid, 38 valid but unspecified state, 428 value, 73 call by, 99 null member pointer, 85 null pointer, 85 undefined unrepresentable integral, 85 value category, 78 value computation, 10–11, 14, 15, 102, 114, 124, 126, 127, 261 value representation, 73 value-initialization, 203 ValueSwappable, 439 variable, 34 indeterminate uninitialized, 202 virt-specifier, 220, 1203 virt-specifier-seq, 220, 1203 virtual base class, 235 virtual function, 240–244 pure, 244, 245 virtual function call, 244 constructor and, 276 destructor and, 276 undefined pure, 245 visibility, 45 visible, 45 void* type, 77 void&, 188 volatile, 77 constructor and, 225, 258 destructor and, 225, 265 implementation-defined, 153 overloading and, 291 waiting function, 1172 wchar_t, 27, 30, 667 implementation-defined, 75 weak result type, 570 weibull_distribution probability density function, 946 weights discrete_distribution, 954 piecewise_constant_distribution, 955 weights at boundaries piecewise_linear_distribution, 957 well-formed program, see program, well-formed white space, 21 wide-character, 27 X(X&), see copy constructor
1295
ISO/IEC 14882:2011(E)
xvalue, 78 zero division by undefined, 87 remainder undefined, 87 undefined division by, 119 zero-initialization, 202
1296
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
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, 183, 1201 abstract-pack-declarator, 184, 1201 access-specifier, 233, 1203 additive-expression, 119, 1194 alias-declaration, 140, 1197 alignment-specifier, 177, 1200 and-expression, 123, 1194 asm-definition, 173, 1199 assignment-expression, 126, 1195 assignment-operator, 126, 1195 attribute, 177, 1200 attribute-argument-clause, 177, 1200 attribute-declaration, 140, 1197 attribute-list, 177, 1200 attribute-namespace, 177, 1200 attribute-scoped-token, 177, 1200 attribute-specifier, 177, 1199 attribute-specifier-seq, 177, 1199 attribute-token, 177, 1200 balanced-token, 177, 1200 balanced-token-seq, 177, 1200 base-clause, 233, 1203 base-specifier, 233, 1203 base-specifier-list, 233, 1203 base-type-specifier, 233, 1203 block-declaration, 140, 1197 boolean-literal, 31, 1191 brace-or-equal-initializer, 202, 1202 braced-init-list, 202, 1202 c-char, 26, 1190 c-char-sequence, 26, 1190 capture, 92, 1193 capture-default, 92, 1192 capture-list, 92, 1192 cast-expression, 117, 1194 character-literal, 26, 1190 class-head, 216, 1202 class-head-name, 216, 1202 class-key, 216, 1202 class-name, 216, 1202 class-or-decltype, 233, 1203
© ISO/IEC 2011 – All rights reserved
class-specifier, 216, 1202 class-virt-specifier, 216, 1202 compound-statement, 130, 1195 condition, 131, 1196 conditional-expression, 124, 1195 constant-expression, 127, 1195 control-line, 412, 1206 conversion-declarator, 263, 1203 conversion-function-id, 263, 1203 conversion-type-id, 263, 1203 ctor-initializer, 271, 1203 cv-qualifier, 183, 1201 cv-qualifier-seq, 183, 1201 d-char, 29, 1191 d-char-sequence, 29, 1191 decimal-literal, 24, 1189 decl-specifier, 142, 1197 decl-specifier-seq, 142, 1197 declaration, 140, 1196 declaration-seq, 140, 1196 declaration-statement, 137, 1196 declarator, 182, 1200 declarator-id, 183, 1201 decltype-specifier, 153, 1198 delete-expression, 115, 1194 digit, 23, 1188 digit-sequence, 28, 1190 dynamic-exception-specification, 405, 1205 elaborated-type-specifier, 156, 1198 elif-group, 411, 1206 elif-groups, 411, 1206 else-group, 411, 1206 empty-declaration, 140, 1197 encoding-prefix, 28, 1190 endif-line, 411, 1206 enum-base, 158, 1198 enum-head, 158, 1198 enum-key, 158, 1198 enum-name, 157, 1198 enum-specifier, 158, 1198 enumerator, 158, 1199
1297
ISO/IEC 14882:2011(E)
enumerator-definition, 158, 1199 enumerator-list, 158, 1199 equality-expression, 122, 1194 escape-sequence, 26, 1190 exception-declaration, 400, 1205 exception-specification, 405, 1205 exclusive-or-expression, 123, 1195 explicit-instantiation, 371, 1205 explicit-specialization, 373, 1205 exponent-part, 28, 1190 expression, 127, 1195 expression-list, 97, 1193 expression-statement, 130, 1195 extension-namespace-definition, 161, 1199 floating-literal, 28, 1190 floating-suffix, 28, 1190 for-init-statement, 133, 1196 for-range-declaration, 133, 1196 for-range-initializer, 133, 1196 fractional-constant, 28, 1190 function-definition, 198, 1201 function-specifier, 144, 1197 function-try-block, 400, 1205 group, 411, 1205 group-part, 411, 1206 h-char, 22, 1188 h-char-sequence, 22, 1188 handler, 400, 1205 handler-seq, 400, 1205 header-name, 22, 1188 hex-quad, 19, 1187 hexadecimal-digit, 25, 1189 hexadecimal-escape-sequence, 26, 1190 hexadecimal-literal, 25, 1189 id-expression, 89, 1192 identifier, 22, 1188 identifier-list, 412, 1206 identifier-nondigit, 22, 1188 if-group, 411, 1206 if-section, 411, 1206 inclusive-or-expression, 123, 1195 init-declarator, 182, 1200 init-declarator-list, 182, 1200 initializer, 202, 1202 initializer-clause, 202, 1202 initializer-list, 202, 1202 integer-literal, 24, 1189
1298
integer-suffix, 25, 1189 iteration-statement, 133, 1196 jump-statement, 136, 1196 labeled-statement, 130, 1195 lambda-capture, 92, 1192 lambda-declarator, 92, 1193 lambda-expression, 92, 1192 lambda-introducer, 92, 1192 linkage-specification, 174, 1199 literal, 24, 1189 literal-operator-id, 316, 1204 logical-and-expression, 123, 1195 logical-or-expression, 124, 1195 long-long-suffix, 25, 1189 long-suffix, 25, 1189 lparen, 412, 1206 mem-initializer, 271, 1204 mem-initializer-id, 271, 1204 mem-initializer-list, 271, 1203 member-declaration, 220, 1202 member-declarator, 220, 1203 member-declarator-list, 220, 1203 member-specification, 220, 1202 multiplicative-expression, 119, 1194 named-namespace-definition, 161, 1199 namespace-alias, 164, 1199 namespace-alias-definition, 164, 1199 namespace-body, 161, 1199 namespace-definition, 161, 1199 namespace-name, 161, 1199 nested-name-specifier, 91, 1192 new-declarator, 112, 1194 new-expression, 112, 1193 new-initializer, 112, 1194 new-line, 412, 1206 new-placement, 112, 1194 new-type-id, 112, 1194 noexcept-expression, 116, 1194 noexcept-specification, 406, 1205 non-directive, 412, 1206 nondigit, 23, 1188 nonzero-digit, 25, 1189 noptr-abstract-declarator, 183, 1201 noptr-abstract-pack-declarator, 184, 1201 noptr-declarator, 182, 1200 noptr-new-declarator, 112, 1194 octal-digit, 25, 1189
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
octal-escape-sequence, 26, 1190 octal-literal, 24, 1189 opaque-enum-declaration, 158, 1198 operator, 313, 1204 operator-function-id, 313, 1204 original-namespace-definition, 161, 1199 original-namespace-name, 161, 1199 parameter-declaration, 192, 1201 parameter-declaration-clause, 192, 1201 parameter-declaration-list, 192, 1201 parameters-and-qualifiers, 183, 1200 pm-expression, 118, 1194 pointer-literal, 31, 1191 postfix-expression, 97, 1193 pp-number, 22, 1188 pp-tokens, 412, 1206 preprocessing-file, 411, 1205 preprocessing-op-or-punc, 24, 1189 preprocessing-token, 20, 1188 primary-expression, 89, 1192 pseudo-destructor-name, 98, 1193 ptr-abstract-declarator, 183, 1201 ptr-declarator, 182, 1200 ptr-operator, 183, 1201 pure-specifier, 220, 1203 q-char, 22, 1188 q-char-sequence, 22, 1188 qualified-id, 91, 1192 qualified-namespace-specifier, 164, 1199 r-char, 29, 1191 r-char-sequence, 29, 1191 raw-string, 29, 1191 ref-qualifier, 183, 1201 relational-expression, 121, 1194 replacement-list, 412, 1206 s-char, 29, 1191 s-char-sequence, 28, 1191 selection-statement, 131, 1196 shift-expression, 121, 1194 sign, 28, 1190 simple-declaration, 140, 1197 simple-escape-sequence, 26, 1190 simple-template-id, 325, 1204 simple-type-specifier, 153, 1198 statement, 130, 1195 statement-seq, 130, 1195 static_assert-declaration, 140, 1197
© ISO/IEC 2011 – All rights reserved
storage-class-specifier, 142, 1197 string-literal, 28, 1190 template-argument, 325, 1205 template-argument-list, 325, 1204 template-declaration, 321, 1204 template-id, 325, 1204 template-name, 325, 1204 template-parameter, 322, 1204 template-parameter-list, 321, 1204 text-line, 412, 1206 throw-expression, 400, 1205 token, 21, 1188 trailing-return-type, 183, 1200 trailing-type-specifier, 151, 1197 trailing-type-specifier-seq, 151, 1198 translation-unit, 59, 1192 try-block, 400, 1205 type-id, 183, 1201 type-id-list, 405, 1205 type-name, 153, 1198 type-parameter, 322, 1204 type-specifier, 151, 1197 type-specifier-seq, 151, 1198 typedef-name, 145, 1197 typename-specifier, 353, 1205 ud-suffix, 32, 1191 unary-expression, 109, 1193 unary-operator, 109, 1193 universal-character-name, 19, 1187 unnamed-namespace-definition, 161, 1199 unqualified-id, 89, 1192 unsigned-suffix, 25, 1189 user-defined-character-literal, 31, 1191 user-defined-floating-literal, 31, 1191 user-defined-integer-literal, 31, 1191 user-defined-literal, 31, 1191 user-defined-string-literal, 31, 1191 using-declaration, 165, 1199 using-directive, 171, 1199 virt-specifier, 220, 1203 virt-specifier-seq, 220, 1203
1299
ISO/IEC 14882:2011(E)
Index of library names <scoped_allocator>, 620 _Exit, 465 __alignas_is_defined, 482 __bool_true_false_are_defined, 481, 482 _1, 578 a cauchy_distribution, 952 extreme_value_distribution, 948 uniform_int_distribution, 939 uniform_real_distribution, 940 weibull_distribution, 947 abort, 65, 136, 436, 465, 466, 472, 477 abs, 972, 985 complex, 911 accumulate, 982 acos, 972, 985 complex, 912 acosh, 985 complex, 912 address allocator, 536 addressof, 538 adjacent_difference, 983 adjacent_find, 875 advance, 840 , 863 align, 531 all bitset, 523 all_of, 873 allocate allocator, 536 allocator_traits, 534 scoped_allocator_adaptor, 623 allocate_shared, 557 allocator, 1107 allocator, 535 address, 536 allocate, 536 constructor, 536 deallocate, 536 destructor, 536 max_size, 536 operator!=, 537
1300
operator==, 536 allocator_arg, 532 allocator_arg_t, 532 allocator_traits, 532 allocate, 534 const_pointer, 533 const_void_pointer, 533 constructor, 534 deallocate, 534 destructor, 534 difference_type, 534 max_size, 534 pointer, 533 propagate_on_container_copy_assignment, 534 propagate_on_container_move_assignment, 534 propagate_on_container_swap, 534 rebind_alloc, 534 select_on_container_copy_construction, 535 size_type, 534 void_pointer, 533 alpha gamma_distribution, 946 always_noconv codecvt, 692 any bitset, 523 any_of, 874 append basic_string, 648, 649 apply valarray, 969 arg, 913 complex, 911 <array>, 754 array, 756, 757, 759 begin, 757 data, 758 end, 757 fill, 758 get, 759 max_size, 757 size, 757, 758 swap, 758, 759 asin, 972, 985 complex, 912
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
asinh, 985 complex, 912 , 436 assign deque, 762 list, 775 basic_regex, 1095, 1096 basic_string, 650 deque, 762 error_code, 495 error_condition, 497 forward_list, 767 function, 583 list, 775 vector, 781 async, 1181 at basic_string, 648 map, 792 unordered_map, 808 at_quick_exit, 465, 467 atan, 972, 985 complex, 912 atan2, 972, 985 atanh, 985 complex, 912 atexit, 65, 436, 465, 466 , 1122 atomic type atomic_compare_exchange_strong, 1134 atomic_compare_exchange_strong_explicit, 1134 atomic_compare_exchange_weak, 1134 atomic_compare_exchange_weak_explicit, 1134 atomic_exchange, 1134 atomic_exchange_explicit, 1134 atomic_fetch_, 1136 atomic_is_lock_free, 1133 atomic_load, 1134 atomic_load_explicit, 1134 atomic_store, 1134 atomic_store_explicit, 1134 compare_exchange_strong, 1134 compare_exchange_strong_explicit, 1134 compare_exchange_weak, 1134 compare_exchange_weak_explicit, 1134 constructor, 1133 exchange, 1134 fetch_, 1136 load, 1134
© ISO/IEC 2011 – All rights reserved
operator @=, 1136 operator C , 1134 operator++, 1137 operator--, 1137 operator=, 1134 store, 1134 atomic_compare_exchange_strong atomic type, 1134 shared_ptr, 565 atomic_compare_exchange_strong_explicit atomic type, 1134 shared_ptr, 565 atomic_compare_exchange_weak atomic type, 1134 shared_ptr, 565 atomic_compare_exchange_weak_explicit atomic type, 1134 shared_ptr, 565 atomic_exchange atomic type, 1134 shared_ptr, 564 atomic_exchange_explicit atomic type, 1134 shared_ptr, 565 atomic_fetch_ atomic type, 1136 atomic_flag clear, 1138 atomic_flag_clear, 1138 atomic_flag_clear_explicit, 1138 atomic_flag_test_and_set, 1138 atomic_flag_test_and_set_explicit, 1138 atomic_is_lock_free atomic type, 1133 shared_ptr, 564 atomic_load atomic type, 1134 shared_ptr, 564 atomic_load_explicit atomic type, 1134 shared_ptr, 564 atomic_signal_fence, 1139 atomic_store atomic type, 1134 shared_ptr, 564 atomic_store_explicit atomic type, 1134 shared_ptr, 564 atomic_thread_fence, 1138 auto_ptr, 554, 1245 auto_ptr, 1246
1301
ISO/IEC 14882:2011(E)
auto_ptr_ref, 1247 constructor, 1246, 1247 destructor, 1246 operator=, 1246 auto_ptr_ref auto_ptr, 1247 operator auto_ptr, 1247 operator=, 1247 b cauchy_distribution, 952 extreme_value_distribution, 948 uniform_int_distribution, 939 uniform_real_distribution, 940 weibull_distribution, 947 back basic_string, 648 back_insert_iterator, 847 back_insert_iterator, 847 back_inserter, 848 bad basic_ios, 1009 bad_alloc, 114, 468, 471, 472 bad_alloc, 471, 472 bad_alloc::what implementation-defined, 472 bad_array_new_length, 472 bad_array_new_length, 472 bad_cast, 103, 473, 474 bad_cast, 474 bad_cast::what implementation-defined, 474 bad_exception, 476 bad_exception, 476, 477 bad_exception::what implementation-defined, 477 bad_function_call, 580 bad_function_call, 580 bad_typeid, 104, 473, 474 bad_typeid, 474, 475 bad_weak_ptr, 550 bad_weak_ptr, 550 what, 550 base move_iterator, 853 reverse_iterator, 843 basic_filebuf, 990, 1061 basic_filebuf, 1063 constructor, 1063 destructor, 1063 operator=, 1063
1302
swap, 1063, 1064 basic_filebuf, 1061 basic_filebuf<wchar_t>, 1061 basic_fstream, 990, 1072 basic_fstream, 1073 constructor, 1073 operator=, 1073 swap, 1073 basic_ifstream, 990, 1068 basic_ifstream, 1069 constructor, 1069 operator=, 1069 swap, 1069 basic_ifstream, 1061 basic_ifstream<wchar_t>, 1061 basic_ios, 990, 1005 basic_ios, 1006 constructor, 1006 destructor, 1006 exceptions, 1010 fill, 1007 init, 1006 move, 1008 rdbuf, 1007 set_rdbuf, 1009 swap, 1008 tie, 1007 basic_ios, 995 basic_ios<wchar_t>, 995 basic_iostream, 1035 basic_iostream, 1036 constructor, 1036 destructor, 1036 operator=, 1036 swap, 1037 basic_istream, 990, 1024 basic_istream, 1026 constructor, 1026 destructor, 1026, 1027 get, 1031, 1032, 1035 operator, 1049 basic_ofstream, 990, 1070 basic_ofstream, 1071 constructor, 1071 operator=, 1071 swap, 1071 basic_ofstream, 1061 basic_ofstream<wchar_t>, 1061 basic_ostream, 990, 1102 basic_ostream, 1039 constructor, 1039 destructor, 1039, 1040 operator, 1049 basic_regex, 1079, 1092, 1119 assign, 1095, 1096 basic_regex, 1094, 1095 constants, 1093, 1094 constructor, 1094, 1095 flag_type, 1096 getloc, 1097 imbue, 1097 mark_count, 1096 operator=, 1095 swap, 1097 basic_streambuf, 990, 1014 basic_streambuf, 1016 constructor, 1016 destructor, 1016 operator=, 1018 setbuf, 1055 swap, 1018 basic_streambuf, 1013 basic_streambuf<wchar_t>, 1013
© ISO/IEC 2011 – All rights reserved
basic_string, 638, 659, 1049 append, 648, 649 assign, 650 at, 648 back, 648 begin, 646 capacity, 647 cbegin, 646 cend, 646 clear, 647 compare, 659 constructor, 642–644 copy, 655 crbegin, 646 crend, 646 empty, 647 end, 646 erase, 652 find, 655, 656 find_first_not_of, 657, 658 find_first_of, 656, 657 find_last_not_of, 658 find_last_of, 657 front, 648 get_allocator, 655 getline, 664 insert, 651, 652 length, 646 max_size, 646 operator!=, 661, 662 operator+, 659–661 operator+=, 648 operator, 663 operator[], 647 pop_back, 653 push_back, 649 rbegin, 646 rend, 646 replace, 653, 654 reserve, 647 resize, 647 rfind, 656 shrink_to_fit, 647 size, 646
1303
ISO/IEC 14882:2011(E)
substr, 658 swap, 655, 663 basic_stringbuf, 990, 1050 basic_stringbuf, 1051 constructor, 1051 operator=, 1052 str, 1053 swap, 1052 basic_stringbuf, 1049 basic_stringbuf<wchar_t>, 1049 basic_stringstream, 990, 1058 basic_stringstream, 1059 constructor, 1060 operator=, 1060 str, 1060 swap, 1060 before type_info, 473 before_begin forward_list, 767 begin, 480 array, 757 basic_string, 646 initializer_list, 480 match_results, 1106 valarray, 980 begin(C&), 862 begin(initializer_list<E>), 481 begin(T (&)[N]), 862 bernoulli_distribution, 940 constructor, 941 p, 941 beta gamma_distribution, 946 bidirectional_iterator_tag, 839 binary_function, 572, 1241 binary_negate, 576 binary_search, 891 bind, 577–579 bind1st, 1244 bind2nd, 1244 binder1st, 1244 binder2nd, 1244 binomial_distribution, 941 constructor, 942 p, 942 t, 942 bit_and, 575 bit_or, 576 bit_xor, 576 , 518
1304
bitset, 518 bitset, 520, 521 flip, 522 operator[], 523, 524 reset, 522 set, 521, 522 boolalpha, 1010 byte_string wstring_convert, 681 c_str basic_string, 655 cacos complex, 912 cacosh complex, 912 call_once, 1161 calloc, 539, 1228 capacity basic_string, 647 vector, 782 casin complex, 912 casinh complex, 912 , 436 catan complex, 912 catanh complex, 912 category error_code, 495 error_condition, 497 locale, 674 cauchy_distribution, 951 a, 952 b, 952 constructor, 951 cbefore_begin forward_list, 767 cbegin basic_string, 646 cbrt, 985 , 914 cend basic_string, 646 cerr, 993 , 446 , 903 CHAR_BIT, 464 char_class_type
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
regex_traits, 1090 CHAR_MAX, 464 char_traits, 630–633 char_type, 630 int_type, 630 off_type, 630 pos_type, 630 state_type, 630 char_type char_traits, 630 chi_squared_distribution, 950 constructor, 951 n, 951 chrono, 605 cin, 993 , 1227 classic locale, 679 classic_table ctype, 690 clear atomic_flag, 1138 basic_ios, 1009 basic_string, 647 error_code, 495 error_condition, 497 forward_list, 769 , 1234 , 433, 1227 clock, 481, 482 clock_t, 482 CLOCKS_PER_SEC, 482 clog, 994 close basic_filebuf, 1065, 1074 basic_ifstream, 1070 basic_ofstream, 1072 messages, 721 code future_error, 1172 system_error, 499 codecvt, 691, 725 always_noconv, 692 do_always_noconv, 694 do_encoding, 694 do_in, 693 do_length, 694 do_max_length, 695 do_out, 693 do_unshift, 694 encoding, 692
© ISO/IEC 2011 – All rights reserved
in, 692 length, 693 max_length, 693 out, 692 unshift, 692 codecvt_byname, 695 collate, 706 compare, 707 do_compare, 707 do_hash, 708 do_transform, 707 hash, 707 transform, 707 collate_byname, 708 combine locale, 678 common_type, 609, 613 compare basic_string, 659 collate, 707 sub_match, 1098 compare_exchange_strong atomic type, 1134 compare_exchange_strong_explicit atomic type, 1134 compare_exchange_weak atomic type, 1134 compare_exchange_weak_explicit atomic type, 1134 , 904 complex, 906 complex, 908 imag, 908 operator-, 910 operator/, 910 real, 908 condition wait, 1165, 1169 wait_for, 1166, 1167 wait_until, 1166 , 1162 condition_variable constructor, 1164 destructor, 1164 notify_all, 1164 notify_one, 1164 wait, 1164 wait_until, 1165 condition_variable_any constructor, 1168 destructor, 1168
1305
ISO/IEC 14882:2011(E)
notify_all, 1168 notify_one, 1168 wait, 1168 wait_for, 1169, 1170 wait_until, 1169, 1170 conj, 913 complex, 911 const_mem_fun1_ref_t, 1243 const_mem_fun1_t, 1243 const_mem_fun_ref_t, 1243 const_mem_fun_t, 1242 const_pointer allocator_traits, 533 const_pointer_cast shared_ptr, 559 const_void_pointer allocator_traits, 533 construct scoped_allocator_adaptor, 623–625 converted wstring_convert, 681 copy, 878 basic_string, 655 copy_backward, 879 copy_n, 878 copyfmt basic_ios, 1008 copysign, 985 cos, 972, 985 complex, 912 cosh, 972, 985 complex, 912 count, 876 bitset, 523 duration, 612 count_if, 876 cout, 993 crbegin basic_string, 646 cref reference_wrapper, 573 crend basic_string, 646 , 446, 481, 482 cshift valarray, 969 , 481, 482 , 481, 482 , 446, 481, 482 , 481, 482 , 1227, 1228
1306
, 464 , 993, 994, 1061, 1064, 1065, 1227 , 435, 481, 482, 1227, 1230 , 433, 1227, 1234, 1239 , 984 , 481, 482, 672, 1227 ctype, 685 do_is, 686 do_narrow, 687 do_scan_not, 687 do_tolower, 687 do_toupper, 687 do_widen, 687 is, 686 narrow, 686 scan_is, 686 scan_not, 686 tolower, 686 toupper, 686 widen, 686 ctype, 688 classic_table, 690 constructor, 689 ctype, 689 destructor, 689 do_narrow, 691 do_tolower, 691 do_toupper, 691 do_widen, 691 is, 690 narrow, 690 scan_is, 690 scan_not, 690 table, 690 tolower, 690 toupper, 690 widen, 690 ctype_base, 684 do_scan_is, 687 ctype_byname, 688 <cuchar>, 447 curr_symbol moneypunct, 719 current_exception, 478 , 447, 1227 data basic_string, 655 array, 758 vector, 783 date_order
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
time_get, 709 DBL_DIG, 464 DBL_EPSILON, 464 DBL_MANT_DIG, 464 DBL_MAX, 464 DBL_MAX_10_EXP, 464 DBL_MAX_EXP, 464 DBL_MIN, 464 DBL_MIN_10_EXP, 464 DBL_MIN_EXP, 464 deallocate allocator, 536 allocator_traits, 534 scoped_allocator_adaptor, 623 dec, 1011, 1042 DECIMAL_DIG, 464 decimal_point moneypunct, 719 numpunct, 705 declare_no_pointers, 530 declare_reachable, 530 declval, 504 default_delete default_delete, 542 operator(), 542 default_error_condition error_category, 492, 493 error_code, 495 default_random_engine, 934 defaultfloat, 1012 delete operator, 539 operator, 447, 469, 470 denorm_absent, 462 denorm_indeterminate, 462 denorm_min numeric_limits, 460 denorm_present, 462 densitities piecewise_constant_distribution, 957 piecewise_linear_distribution, 959 <deque>, 755 deque, 759 assign, 762 deque, 762 shrink_to_fit, 763 swap, 764 detach thread, 1147 difference_type allocator_traits, 534
© ISO/IEC 2011 – All rights reserved
pointer_traits, 530 digits numeric_limits, 458 digits10 numeric_limits, 458 discard_block_engine, 930 constructor, 931 discrete_distribution, 954 constructor, 954, 955 probabilities, 955 distance, 840 div, 985 divides, 573 do_always_noconv codecvt, 694 do_close message, 721 do_compare collate, 707 do_curr_symbol moneypunct, 719 do_date_order time_get, 711 do_decimal_point moneypunct, 719 numpunct, 706 do_encoding codecvt, 694 do_falsename numpunct, 706 do_frac_digits moneypunct, 720 do_get messages, 721 money_get, 715 num_get, 697, 699 time_get, 712 do_get_date time_get, 711 do_get_monthname time_get, 711 do_get_time time_get, 711 do_get_weekday time_get, 711 do_get_year time_get, 711 do_grouping moneypunct, 719 numpunct, 706 do_hash
1307
ISO/IEC 14882:2011(E)
collate, 708 do_in codecvt, 693 do_is ctype, 686 do_length codecvt, 694 do_max_length codecvt, 695 do_narrow, 690 ctype, 687 ctype, 691 do_neg_format moneypunct, 720 do_negative_sign moneypunct, 719 do_open messages, 721 do_out codecvt, 693 do_pos_format moneypunct, 720 do_positive_sign moneypunct, 719 do_put money_put, 717 num_put, 701, 704 time_put, 713 do_scan_is ctype_base, 687 do_scan_not ctype, 687 do_thousands_sep moneypunct, 719 numpunct, 706 do_tolower ctype, 687 ctype, 691 do_toupper ctype, 687 ctype, 691 do_transform collate, 707 do_truename numpunct, 706 do_unshift codecvt, 694 do_widen, 690 ctype, 687 ctype, 691 domain_error, 484, 485
1308
domain_error, 485 duration constructor, 611 count, 612 max, 613 min, 613 operator!=, 614 operator*, 613 operator*=, 612 operator+, 612, 617 operator++, 612 operator+=, 612 operator-, 612, 617 operator-=, 612 operator--, 612 operator/, 614 operator/=, 612 operator), 481 end(T (&)[N]), 862 endl, 1042, 1045 ends, 1045 entropy random_device, 935 eof basic_ios, 1009 epptr basic_streambuf, 1019 epsilon numeric_limits, 458 eq char_traits, 656–658 equal, 876 istreambuf_iterator, 860 equal_range, 891 equal_to, 574 equivalent error_category, 492, 493 erase deque, 763 list, 776 basic_string, 652 vector, 783 erase_after forward_list, 769 erased forward_list, 769 erf, 985 erfc, 985 errc, 489 error_category, 489, 492 default_error_condition, 492, 493 equivalent, 492, 493 message, 492 name, 492, 493 operator!=, 492 operator, 786 map, 788 constructor, 791 find, 792 insert, 792 map, 791 operator, 525 merge, 892 list, 777 forward_list, 771 mersenne_twister_engine, 927 constructor, 928 message do_close, 721 error_category, 492 error_code, 495 error_condition, 497 messages, 720 close, 721 do_get, 721 do_open, 721 get, 721 open, 721 messages_byname, 722 min, 897 duration, 613 duration_values, 609 numeric_limits, 457 time_point, 617 valarray, 969 min_element, 898
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
min_exponent numeric_limits, 459 min_exponent10 numeric_limits, 459 minmax, 898 minmax_element, 899 minstd_rand, 933 minstd_rand0, 933 minus, 573 mismatch, 876 mod, 985 modf, 985 modulus, 573 money_get, 714 do_get, 715 get, 715 money_put, 716 do_put, 717 put, 717 moneypunct, 717 curr_symbol, 719 decimal_point, 719 do_curr_symbol, 719 do_decimal_point, 719 do_frac_digits, 720 do_grouping, 719 do_neg_format, 720 do_negative_sign, 719 do_pos_format, 720 do_positive_sign, 719 do_thousands_sep, 719 frac_digits, 719 grouping, 719 negative_sign, 719 positive_sign, 719 thousands_sep, 719 moneypunct_byname, 720 move, 503 basic_ios, 1008 movemove, 879 move_backward, 879 move_if_noexcept, 504 move_iterator, 851 base, 853 constructor, 852 move_iterator, 852 operator!=, 854 operator*, 853 operator+, 854, 855 operator++, 853 operator+=, 854
© ISO/IEC 2011 – All rights reserved
operator-, 854, 855 operator-=, 854 operator->, 853 operator--, 853 operator=, 855 operator[], 854 mt19937, 934 mt19937_64, 934 multimap, 793 find, 796 insert, 796 multimap, 796 operator auto_ptr, 1247
1320
istream_iterator, 857 move_iterator, 853 regex_iterator, 1115 regex_token_iterator, 1119 reverse_iterator, 843 shared_ptr, 556 unique_ptr, 546 operator-atomic type, 1137 duration, 612 move_iterator, 853 reverse_iterator, 844 operator/ complex, 910 duration, 614 valarray, 970 operator/= complex, 909 duration, 612 gslice_array, 977 indirect_array, 980 mask_array, 978 slice_array, 974 valarray, 968 operator< pair, 507 basic_string, 662 duration, 614 error_category, 492 error_code, 495 error_condition, 497 move_iterator, 854 queue, 822 reverse_iterator, 845 shared_ptr, 557, 558 stack, 828 sub_match, 1098–1102 thread::id, 1145 time_point, 617 tuple, 517 type_index, 626 unique_ptr, 549, 550 valarray, 971 operator basic_istream, 1029 basic_string, 663
1322
istream, 1028–1030 valarray, 970 operator>>= gslice_array, 977 indirect_array, 980 mask_array, 978 slice_array, 974 valarray, 968 operator[] basic_string, 647 bitset, 523, 524 indirect_array, 979 map, 791, 792 mask_array, 978 match_results, 1106 move_iterator, 854 reverse_iterator, 845 unique_ptr, 548 unordered_map, 808, 809 unordered_multimap, 812 valarray, 965–967 operator% duration, 614 valarray, 970 operator%= duration, 612, 613 gslice_array, 977 indirect_array, 980 mask_array, 978 slice_array, 974 valarray, 968 operator& bitset, 524 valarray, 970 operator&= bitset, 521 gslice_array, 977 indirect_array, 980 mask_array, 978 slice_array, 974 valarray, 968 operator&& valarray, 970, 971 operatorˆ bitset, 524 valarray, 970 operatorˆ= bitset, 521 gslice_array, 977 indirect_array, 980 mask_array, 978
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
slice_array, 974 valarray, 968 operator˜ bitset, 522 valarray, 967 operators== locale, 678 operator| bitset, 524 valarray, 970 operator|= bitset, 521 gslice_array, 977 indirect_array, 980 mask_array, 978 slice_array, 974 valarray, 968 operator|| valarray, 970, 971 , 1023 ostream, 990, 1023 ostream_iterator, 857 constructor, 858 destructor, 858 operator*, 858 operator++, 858 operator=, 858 ostreambuf_iterator, 861 constructor, 861, 862 ostringstream, 990, 1049 ostrstream, 1238 constructor, 1238 ostrstream, 1238 out codecvt, 692 out_of_range, 486, 520, 522, 523, 638 out_of_range, 486 out_of_range_error, 484 outer_allocator scoped_allocator_adaptor, 623 output_iterator_tag, 839 overflow basic_filebuf, 1066 basic_streambuf, 1022 basic_stringbuf, 1053 strstreambuf, 1235 overflow_error, 484, 487, 488, 520, 522 overflow_error, 488 owner_before shared_ptr, 557, 561 owns_lock
© ISO/IEC 2011 – All rights reserved
unique_lock, 1160 p bernoulli_distribution, 941 binomial_distribution, 942 geometric_distribution, 943 negative_binomial_distribution, 944 packaged_task constructor, 1184 destructor, 1184 get_future, 1185 make_ready_at_thread_exit, 1185 operator(), 1185 operator=, 1184 reset, 1185 swap, 1184, 1186 valid, 1185 pair, 504, 512–514 get, 508 operator=, 506 pair, 505, 506 swap, 507 param seed_seq, 937 partial_sort, 888 partial_sort_copy, 888 partial_sum, 982 partition, 885 partition_copy, 886 partition_point, 886 pbackfail basic_filebuf, 1065 basic_streambuf, 1021 basic_stringbuf, 1053 strstreambuf, 1235 pbase basic_streambuf, 1019 pbump basic_streambuf, 1019 pcount ostrstream, 1239 strstream, 1240 strstreambuf, 1234 peek basic_istream, 1034 piecewise_constant_distribution, 955 constructor, 956 densitities, 957 intervals, 957 piecewise_construct, 508 piecewise_construct_t, 508
1323
ISO/IEC 14882:2011(E)
piecewise_linear_distribution, 957 constructor, 958 densitities, 959 intervals, 958 placeholders, 578 plus, 573 pointer allocator_traits, 533 pointer_to pointer_traits, 530 pointer_to_binary_function, 1241 pointer_to_unary_function, 1241 pointer_traits, 529 difference_type, 530 element_type, 529 pointer_to, 530 rebind, 530 poisson_distribution, 944 constructor, 944 mean, 944 polar complex, 911 pop priority_queue, 825 forward_list, 768 pop_back basic_string, 653 pop_heap, 896 pos_type char_traits, 630 position match_results, 1106 positive_sign moneypunct, 719 pow, 913, 972, 985 complex, 912 pptr basic_streambuf, 1019 precision ios_base, 684, 1001 prefix match_results, 1106 prev, 841 prev_permutation, 900 priority_queue, 823 emplace, 825 priority_queue, 824 swap, 825 probabilities discrete_distribution, 955 proj
1324
complex, 911 promise constructor, 1174 destructor, 1174 get_future, 1175 operator=, 1175 set_exception, 1175 set_exception_at_thread_exit, 1176 set_value, 1175 set_value_at_thread_exit, 1175 swap, 1175, 1176 propagate_on_container_copy_assignment allocator_traits, 534 scoped_allocator_adaptor, 622 propagate_on_container_move_assignment allocator_traits, 534 scoped_allocator_adaptor, 622 propagate_on_container_swap allocator_traits, 534 scoped_allocator_adaptor, 622 proxy istreambuf_iterator, 859 ptr_fun, 1241 ptrdiff_t, 454 pubimbue basic_streambuf, 1016 pubseekoff basic_streambuf, 1017 pubseekpos basic_streambuf, 1017 pubsetbuf basic_streambuf, 1017 pubsync basic_streambuf, 1017 push priority_queue, 825 push_back basic_string, 649 push_front forward_list, 768 push_heap, 895 put basic_ostream, 1044 money_put, 717 num_put, 701 time_put, 713 put_money, 1048 put_time, 1049 putback basic_istream, 1034 putenv, 481
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
pword ios_base, 1003 , 820 queue, 820 swap, 823 quick_exit, 465, 467 quiet_NaN numeric_limits, 460 radix numeric_limits, 458 raise, 482 , 923–925 random_access_iterator_tag, 839 random_device, 935 constructor, 935 entropy, 935 operator(), 935 random_shuffle, 885 range_error, 484, 487 range_error, 487 ranlux24, 934 ranlux24_base, 934 ranlux48, 934 ranlux48_base, 934 ratio, 602 ratio_equal, 604 ratio_greater, 605 ratio_greater_equal, 605 ratio_less, 604 ratio_less_equal, 605 ratio_not_equal, 604 raw_storage_iterator constructor, 537 operator*, 537 operator++, 537 operator=, 537 rbegin basic_string, 646 rdbuf basic_filebuf, 1074 basic_ifstream, 1069 basic_ios, 1007 basic_istringstream, 1056 basic_ofstream, 1071 basic_ostringstream, 1058 basic_stringstream, 1060 istrstream, 1238 ostrstream, 1239 strstream, 1240
© ISO/IEC 2011 – All rights reserved
wbuffer_convert, 684 rdstate basic_ios, 1009 read basic_istream, 1034 readsome basic_istream, 1034 real, 913 complex, 908, 911 realloc, 539, 1228 rebind pointer_traits, 530 rebind_alloc allocator_traits, 534 ref reference_wrapper, 573 reference_wrapper, 571 cref, 573 get, 572 operator T&, 572 operator(), 572 operator=, 572 ref, 573 reference_wrapper, 572 , 1079 regex, 1079 regex_constants, 1086 error_type, 1088, 1089 match_flag_type, 1086 syntax_option_type, 1086 regex_error, 1089, 1092, 1120 constructor, 1089 regex_iterator, 1113 increment, 1115 operator!=, 1115 operator*, 1115 operator++, 1115, 1116 operator->, 1115 operator==, 1114 regex_iterator, 1114 regex_match, 1108–1110 regex_replace, 1112, 1113 regex_search, 1110, 1111 regex_token_iterator, 1116 end-of-sequence, 1116 operator!=, 1118 operator*, 1118 operator++, 1119 operator->, 1119 operator==, 1116, 1118 regex_token_iterator, 1117
1325
ISO/IEC 14882:2011(E)
regex_traits, 1089 char_class_type, 1090 isctype, 1091 length, 1090 lookup_classname, 1091 lookup_collatename, 1090 transform, 1090 transform_primary, 1090 translate, 1090 translate_nocase, 1090 value, 1091 register_callback ios_base, 1003 regular expression traits isctype, 1120 lookup_classname, 1120 lookup_collatename, 1120 transform_primary, 1120 rel_ops, 500 release auto_ptr, 1247 unique_lock, 1160 unique_ptr, 547 remainder, 985 remove, 882 list, 777 forward_list, 770 remove_copy, 882 remove_copy_if, 882 remove_if, 882 forward_list, 770 remquo, 985 rend basic_string, 646 rep system_clock, 618 replace, 881 basic_string, 653, 654 replace_copy, 881 replace_copy_if, 881 replace_if, 881 reserve basic_string, 647 vector, 782 reset auto_ptr, 1247 bitset, 522 packaged_task, 1185 shared_ptr, 556 unique_ptr, 547, 549 weak_ptr, 561
1326
resetiosflags, 1046 resize deque, 763 list, 775 basic_string, 647 forward_list, 769 valarray, 969 vector, 782 rethrow_exception, 478 rethrow_if_nested nested_exception, 480 return_temporary_buffer, 538 returned nested_exception, 479 reverse, 884 list, 778 forward_list, 771 reverse_copy, 884 reverse_iterator, 841 reverse_iterator, 843 base, 843 constructor, 843 operator++, 844 operator--, 844 rfind basic_string, 656 right, 1011 rint, 985 rotate, 884 rotate_copy, 884 round, 985 round_error numeric_limits, 458 round_indeterminate, 461 round_style numeric_limits, 461 round_to_nearest, 461 round_toward_infinity, 461 round_toward_neg_infinity, 461 round_toward_zero, 461 runtime_error, 484, 487 runtime_error, 487 s lognormal_distribution, 950 sbumpc basic_streambuf, 1017 scalbln, 985 scalbn, 985 scan_is ctype, 686
© ISO/IEC 2011 – All rights reserved
ISO/IEC 14882:2011(E)
basic_ostream, 1040 ctype, 690 constructor, 1027, 1040 scan_not <set>, 787 ctype, 686 set, 797 ctype, 690 bitset, 521, 522 SCHAR_MAX, 464 operator, 481 seekpos basic_filebuf, 1067 setlocale, 433 basic_streambuf, 1019 setp basic_stringbuf, 1055 basic_streambuf, 1019 strstreambuf, 1236 setprecision, 1047 select_on_container_copy_construction setstate allocator_traits, 535 basic_ios, 1009 scoped_allocator_adaptor, 625 setw, 1047 sentry sgetc basic_istream, 1027 basic_streambuf, 1017
© ISO/IEC 2011 – All rights reserved
1327
ISO/IEC 14882:2011(E)
sgetn basic_streambuf, 1017 share future, 1177 shared_from_this enable_shared_from_this, 563 shared_future constructor, 1179, 1180 destructor, 1180 get, 1180 operator=, 1180 valid, 1181 wait, 1181 wait_for, 1181 wait_until, 1181 shared_ptr, 551, 563 atomic_compare_exchange_strong, 565 atomic_compare_exchange_strong_explicit, 565 atomic_compare_exchange_weak, 565 atomic_compare_exchange_weak_explicit, 565 atomic_exchange, 564 atomic_exchange_explicit, 565 atomic_is_lock_free, 564 atomic_load, 564 atomic_load_explicit, 564 atomic_store, 564 atomic_store_explicit, 564 const_pointer_cast, 559 constructor, 553–555 destructor, 555 dynamic_pointer_cast, 559 get, 556 get_deleter, 559 operator bool, 557 operator!=, 558 operator*, 556 operator->, 556 operator, 1049 <staarg.h>, 481 stable_partition, 886 stable_sort, 888 <stack>, 826 stack, 826 swap, 828 start gslice, 976 slice, 973 state fpos, 1004 match_results, 1105 wbuffer_convert, 684 wstring_convert, 682 state_type char_traits, 630 wbuffer_convert, 684 wstring_convert, 682 static_pointer_cast shared_ptr, 558 <stdalign.h>, 481 <stdarg.h>, 481 <stdbool.h>, 481 stddev
© ISO/IEC 2011 – All rights reserved
normal_distribution, 949 <stdexcept>, 484 <stdlib.h>, 481, 1230 stod, 666 stof, 665, 666 stoi, 665, 666 stol, 665, 666 stold, 665, 666 stoll, 665, 666 store atomic type, 1134 stoul, 665, 666 stoull, 665, 666 str basic_istringstream, 1056, 1057 basic_ostringstream, 1058 basic_stringbuf, 1052, 1053 basic_stringstream, 1060 istrstream, 1238 match_results, 1106 ostrstream, 1239 strstream, 1240 strstreambuf, 1234 sub_match, 1098 strchr, 667 <streambuf>, 1013 streambuf, 990, 1013 streamoff, 995, 1004, 1230 streamsize, 996 ios_base, 1001 strftime, 713 stride gslice, 976 slice, 973 <string>, 634 stringbuf, 990, 1049 stringstream, 990 strlen, 1233, 1234, 1239 strpbrk, 667 strrchr, 667 strstr, 667 strstream, 1239 destructor, 1240 strstream, 1240 strstreambuf, 1231, 1233 strstreambuf, 1233 destructor, 1234 setg, 1234 student_t_distribution, 953 constructor, 953 mean, 953
1329
ISO/IEC 14882:2011(E)
sub_match, 1097 compare, 1098 constructor, 1098 length, 1098 operator basic_string, 1098 operator!=, 1098–1102 operator