1 Scope [intro.scope]

This document specifies requirements for implementations of the C++ programming language.
The first such requirement is that they implement the language, so this document also defines C++.
Other requirements and relaxations of the first requirement appear at various places within this document.
C++ is a general purpose programming language based on the C programming language as described in ISO/IEC 9899:2011 Programming languages — C (hereinafter referred to as the C standard).
In addition to the facilities provided by C, C++ provides additional data types, classes, templates, exceptions, namespaces, operator overloading, function name overloading, references, free store management operators, and additional library facilities.

2 Normative references [intro.refs]

The following documents are referred to in the text in such a way that some or all of their content constitutes requirements of this document.
For dated references, only the edition cited applies.
For undated references, the latest edition of the referenced document (including any amendments) applies.
  • Ecma International, ECMAScript Language Specification, Standard Ecma-262, third edition, 1999.
  • ISO/IEC 2382 (all parts), Information technology — Vocabulary
  • ISO/IEC 9899:2011, Programming languages — C
  • ISO/IEC 9899:2011/Cor.
    1:2012(E), Programming languages — C, Technical Corrigendum 1
  • ISO/IEC 9945:2003, Information Technology — Portable Operating System Interface (POSIX)
  • ISO/IEC 10646-1:1993, Information technology — Universal Multiple-Octet Coded Character Set (UCS) — Part 1: Architecture and Basic Multilingual Plane
  • ISO/IEC 10967-1:2012, Information technology — Language independent arithmetic — Part 1: Integer and floating point arithmetic
  • ISO/IEC/IEEE 60559:2011, Information technology — Microprocessor Systems — Floating-Point arithmetic
  • ISO 80000-2:2009, Quantities and units — Part 2: Mathematical signs and symbols to be used in the natural sciences and technology
The library described in Clause 7 of ISO/IEC 9899:2011 is hereinafter called the C standard library.1
The operating system interface described in ISO/IEC 9945:2003 is hereinafter called POSIX.
The ECMAScript Language Specification described in Standard Ecma-262 is hereinafter called ECMA-262.
The arithmetic specification described in ISO/IEC 10967-1:2012 is hereinafter called LIA-1.
With the qualifications noted in Clauses [language.support] through [thread] and in [diff.library], the C standard library is a subset of the C++ standard library.

3 Terms and definitions [intro.defs]

For the purposes of this document, the terms and definitions given in ISO/IEC 2382-1:1993, the terms, definitions, and symbols given in ISO 80000-2:2009, and the following apply.
ISO and IEC maintain terminological databases for use in standardization at the following addresses:
[definitions] defines additional terms that are used only in Clauses [library] through [thread] and Annex [depr].
Terms that are used only in a small portion of this document are defined where they are used and italicized where they are defined.

3.1 access [defns.access]

⟨execution-time action⟩ to read or modify the value of an object

3.2 argument [defns.argument]

⟨function call expression⟩ expression in the comma-separated list bounded by the parentheses ([expr.call])

3.3 argument [defns.argument.macro]

⟨function-like macro⟩ sequence of preprocessing tokens in the comma-separated list bounded by the parentheses ([cpp.replace])

3.4 argument [defns.argument.throw]

⟨throw expression⟩ the operand of throw ([expr.throw])

3.5 argument [defns.argument.templ]

⟨template instantiation⟩ constant-expression, type-id, or id-expression in the comma-separated list bounded by the angle brackets ([temp.arg])

3.6 block [defns.block]

a thread of execution that blocks is waiting for some condition (other than for the implementation to execute its execution steps) to be satisfied before it can continue execution past the blocking operation

3.7 conditionally-supported [defns.cond.supp]

program construct that an implementation is not required to support
[Note
:
Each implementation documents all conditionally-supported constructs that it does not support.
end note
]

3.8 diagnostic message [defns.diagnostic]

message belonging to an implementation-defined subset of the implementation's output messages

3.9 dynamic type [defns.dynamic.type]

⟨glvalue⟩ type of the most derived object ([intro.object]) to which the glvalue refers
[Example
:
If a pointer ([dcl.ptr]) p whose static type is “pointer to class B” is pointing to an object of class D, derived from B (Clause [class.derived]), the dynamic type of the expression *p is “D.
References ([dcl.ref]) are treated similarly.
end example
]

3.10 dynamic type [defns.dynamic.type.prvalue]

⟨prvalue⟩ static type of the prvalue expression

3.11 ill-formed program [defns.ill.formed]

program that is not well-formed ([defns.well.formed])

3.12 implementation-defined behavior [defns.impl.defined]

behavior, for a well-formed program construct and correct data, that depends on the implementation and that each implementation documents

3.13 implementation limits [defns.impl.limits]

restrictions imposed upon programs by the implementation

3.14 locale-specific behavior [defns.locale.specific]

behavior that depends on local conventions of nationality, culture, and language that each implementation documents

3.15 multibyte character [defns.multibyte]

sequence of one or more bytes representing a member of the extended character set of either the source or the execution environment
[Note
:
The extended character set is a superset of the basic character set ([lex.charset]).
end note
]

3.16 parameter [defns.parameter]

⟨function or catch clause⟩ object or reference declared as part of a function declaration or definition or in the catch clause of an exception handler that acquires a value on entry to the function or handler

3.17 parameter [defns.parameter.macro]

⟨function-like macro⟩ identifier from the comma-separated list bounded by the parentheses immediately following the macro name

3.18 parameter [defns.parameter.templ]

⟨template⟩ member of a template-parameter-list

3.19 signature [defns.signature]

⟨function⟩ name, parameter type list ([dcl.fct]), and enclosing namespace (if any)
[Note
:
Signatures are used as a basis for name mangling and linking.
end note
]

3.20 signature [defns.signature.templ]

⟨function template⟩ name, parameter type list ([dcl.fct]), enclosing namespace (if any), return type, and template parameter list

3.21 signature [defns.signature.spec]

⟨function template specialization⟩ signature of the template of which it is a specialization and its template arguments (whether explicitly specified or deduced)

3.22 signature [defns.signature.member]

⟨class member function⟩ name, parameter type list ([dcl.fct]), class of which the function is a member, cv-qualifiers (if any), and ref-qualifier (if any)

3.23 signature [defns.signature.member.templ]

⟨class member function template⟩ name, parameter type list ([dcl.fct]), class of which the function is a member, cv-qualifiers (if any), ref-qualifier (if any), return type (if any), and template parameter list

3.24 signature [defns.signature.member.spec]

⟨class member function template specialization⟩ signature of the member function template of which it is a specialization and its template arguments (whether explicitly specified or deduced)

3.25 static type [defns.static.type]

type of an expression ([basic.types]) resulting from analysis of the program without considering execution semantics
[Note
:
The static type of an expression depends only on the form of the program in which the expression appears, and does not change while the program is executing.
end note
]

3.26 unblock [defns.unblock]

satisfy a condition that one or more blocked threads of execution are waiting for

3.27 undefined behavior [defns.undefined]

behavior for which this International Standard imposes no requirements
[Note
:
Undefined behavior may be expected when this International Standard omits any explicit definition of behavior or when a program uses an erroneous construct or erroneous data.
Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed.
Evaluation of a constant expression never exhibits behavior explicitly specified as undefined ([expr.const]).
end note
]

3.28 unspecified behavior [defns.unspecified]

behavior, for a well-formed program construct and correct data, that depends on the implementation
[Note
:
The implementation is not required to document which behavior occurs.
The range of possible behaviors is usually delineated by this International Standard.
end note
]

3.29 well-formed program [defns.well.formed]

C++ program constructed according to the syntax rules, diagnosable semantic rules, and the one-definition rule ([basic.def.odr]).

4 General principles [intro]

4.1 Implementation compliance [intro.compliance]

The set of diagnosable rules consists of all syntactic and semantic rules in this International Standard except for those rules containing an explicit notation that “no diagnostic is required” or which are described as resulting in “undefined behavior”.
Although this International Standard states only requirements on C++ implementations, those requirements are often easier to understand if they are phrased as requirements on programs, parts of programs, or execution of programs.
Such requirements have the following meaning:
  • If a program contains no violations of the rules in this International Standard, a conforming implementation shall, within its resource limits, accept and correctly execute2 that program.
  • If a program contains a violation of any diagnosable rule or an occurrence of a construct described in this International Standard as “conditionally-supported” when the implementation does not support that construct, a conforming implementation shall issue at least one diagnostic message.
  • If a program contains a violation of a rule for which no diagnostic is required, this International Standard places no requirement on implementations with respect to that program.
[Note
:
During template argument deduction and substitution, certain constructs that in other contexts require a diagnostic are treated differently; see [temp.deduct].
end note
]
For classes and class templates, the library Clauses specify partial definitions.
Private members (Clause [class.access]) are not specified, but each implementation shall supply them to complete the definitions according to the description in the library Clauses.
For functions, function templates, objects, and values, the library Clauses specify declarations.
Implementations shall supply definitions consistent with the descriptions in the library Clauses.
The names defined in the library have namespace scope ([basic.namespace]).
A C++ translation unit ([lex.phases]) obtains access to these names by including the appropriate standard library header ([cpp.include]).
The templates, classes, functions, and objects in the library have external linkage ([basic.link]).
The implementation provides definitions for standard library entities, as necessary, while combining translation units to form a complete C++ program ([lex.phases]).
Two kinds of implementations are defined: a hosted implementation and a freestanding implementation.
For a hosted implementation, this International Standard defines the set of available libraries.
A freestanding implementation is one in which execution may take place without the benefit of an operating system, and has an implementation-defined set of libraries that includes certain language-support libraries ([compliance]).
A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program.
Implementations are required to diagnose programs that use such extensions that are ill-formed according to this International Standard.
Having done so, however, they can compile and execute such programs.
Each implementation shall include documentation that identifies all conditionally-supported constructs that it does not support and defines all locale-specific characteristics.3
“Correct execution” can include undefined behavior, depending on the data being processed; see Clause [intro.defs] and [intro.execution].
This documentation also defines implementation-defined behavior; see [intro.execution].

4.2 Structure of this document [intro.structure]

Clauses [lex] through [cpp] describe the C++ programming language.
That description includes detailed syntactic specifications in a form described in [syntax].
For convenience, Annex [gram] repeats all such syntactic specifications.
Clauses [language.support] through [thread] and Annex [depr] (the library clauses) describe the C++ standard library.
That description includes detailed descriptions of the entities and macros that constitute the library, in a form described in Clause [library].
Annex [implimits] recommends lower bounds on the capacity of conforming implementations.
Annex [diff] summarizes the evolution of C++ since its first published description, and explains in detail the differences between C++ and C.
Certain features of C++ exist solely for compatibility purposes; Annex [depr] describes those features.
Throughout this document, each example is introduced by “[Example: ” and terminated by “end example]”.
Each note is introduced by “[Note: ” and terminated by “end note]”.
Examples and notes may be nested.

4.3 Syntax notation [syntax]

In the syntax notation used in this document, syntactic categories are indicated by italic type, and literal words and characters in constant width type.
Alternatives are listed on separate lines except in a few cases where a long set of alternatives is marked by the phrase “one of”.
If the text of an alternative is too long to fit on a line, the text is continued on subsequent lines indented from the first one.
An optional terminal or non-terminal symbol is indicated by the subscript “”, so
{ expression }
indicates an optional expression enclosed in braces.
Names for syntactic categories have generally been chosen according to the following rules:
  • X-name is a use of an identifier in a context that determines its meaning (e.g., class-name, typedef-name).
  • X-id is an identifier with no context-dependent meaning (e.g., qualified-id).
  • X-seq is one or more X's without intervening delimiters (e.g., declaration-seq is a sequence of declarations).
  • X-list is one or more X's separated by intervening commas (e.g., identifier-list is a sequence of identifiers separated by commas).

4.4 The C++ memory model [intro.memory]

The fundamental storage unit in the C++ memory model is the byte.
A byte is at least large enough to contain any member of the basic execution character set ([lex.charset]) and the eight-bit code units of the Unicode UTF-8 encoding form and is composed of a contiguous sequence of bits,4 the number of which is implementation-defined.
The least significant bit is called the low-order bit; the most significant bit is called the high-order bit.
The memory available to a C++ program consists of one or more sequences of contiguous bytes.
Every byte has a unique address.
[Note
:
The representation of types is described in [basic.types].
end note
]
A memory location is either an object of scalar type or a maximal sequence of adjacent bit-fields all having nonzero width.
[Note
:
Various features of the language, such as references and virtual functions, might involve additional memory locations that are not accessible to programs but are managed by the implementation.
end note
]
Two or more threads of execution ([intro.multithread]) can access separate memory locations without interfering with each other.
[Note
:
Thus a bit-field and an adjacent non-bit-field are in separate memory locations, and therefore can be concurrently updated by two threads of execution without interference.
The same applies to two bit-fields, if one is declared inside a nested struct declaration and the other is not, or if the two are separated by a zero-length bit-field declaration, or if they are separated by a non-bit-field declaration.
It is not safe to concurrently update two bit-fields in the same struct if all fields between them are also bit-fields of nonzero width.
end note
]
[Example
:
A structure declared as
struct {
  char a;
  int b:5,
  c:11,
  :0,
  d:8;
  struct {int ee:8;} e;
}
contains four separate memory locations: The field a and bit-fields d and e.ee are each separate memory locations, and can be modified concurrently without interfering with each other.
The bit-fields b and c together constitute the fourth memory location.
The bit-fields b and c cannot be concurrently modified, but b and a, for example, can be.
end example
]
The number of bits in a byte is reported by the macro CHAR_­BIT in the header <climits>.

4.5 The C++ object model [intro.object]

The constructs in a C++ program create, destroy, refer to, access, and manipulate objects.
An object is created by a definition ([basic.def]), by a new-expression, when implicitly changing the active member of a union ([class.union]), or when a temporary object is created ([conv.rval], [class.temporary]).
An object occupies a region of storage in its period of construction ([class.cdtor]), throughout its lifetime ([basic.life]), and in its period of destruction ([class.cdtor]).
[Note
:
A function is not an object, regardless of whether or not it occupies storage in the way that objects do.
end note
]
The properties of an object are determined when the object is created.
An object can have a name (Clause [basic]).
An object has a storage duration ([basic.stc]) which influences its lifetime ([basic.life]).
An object has a type ([basic.types]).
Some objects are polymorphic ([class.virtual]); the implementation generates information associated with each such object that makes it possible to determine that object's type during program execution.
For other objects, the interpretation of the values found therein is determined by the type of the expressions (Clause [expr]) used to access them.
Objects can contain other objects, called subobjects.
A subobject can be a member subobject ([class.mem]), a base class subobject (Clause [class.derived]), or an array element.
An object that is not a subobject of any other object is called a complete object.
If an object is created in storage associated with a member subobject or array element e (which may or may not be within its lifetime), the created object is a subobject of e's containing object if:
  • the lifetime of e's containing object has begun and not ended, and
  • the storage for the new object exactly overlays the storage location associated with e, and
  • the new object is of the same type as e (ignoring cv-qualification).
[Note
:
If the subobject contains a reference member or a const subobject, the name of the original subobject cannot be used to access the new object ([basic.life]).
end note
]
[Example
:
struct X { const int n; };
union U { X x; float f; };
void tong() {
  U u = {{ 1 }};
  u.f = 5.f;                          // OK, creates new subobject of u ([class.union])
  X *p = new (&u.x) X {2};            // OK, creates new subobject of u
  assert(p->n == 2);                  // OK
  assert(*std::launder(&u.x.n) == 2); // OK
  assert(u.x.n == 2);                 // undefined behavior, u.x does not name new subobject
}
end example
]
If a complete object is created ([expr.new]) in storage associated with another object e of type “array of N unsigned char” or of type “array of N std​::​byte” ([cstddef.syn]), that array provides storage for the created object if:
  • the lifetime of e has begun and not ended, and
  • the storage for the new object fits entirely within e, and
  • there is no smaller array object that satisfies these constraints.
[Note
:
If that portion of the array previously provided storage for another object, the lifetime of that object ends because its storage was reused ([basic.life]).
end note
]
[Example
:
template<typename ...T>
struct AlignedUnion {
  alignas(T...) unsigned char data[max(sizeof(T)...)];
};
int f() {
  AlignedUnion<int, char> au;
  int *p = new (au.data) int;     // OK, au.data provides storage
  char *c = new (au.data) char(); // OK, ends lifetime of *p
  char *d = new (au.data + 1) char();
  return *c + *d; // OK
}

struct A { unsigned char a[32]; };
struct B { unsigned char b[16]; };
A a;
B *b = new (a.a + 8) B;      // a.a provides storage for *b
int *p = new (b->b + 4) int; // b->b provides storage for *p
                             // a.a does not provide storage for *p (directly),
                             // but *p is nested within a (see below)
end example
]
An object a is nested within another object b if:
  • a is a subobject of b, or
  • b provides storage for a, or
  • there exists an object c where a is nested within c, and c is nested within b.
For every object x, there is some object called the complete object of x, determined as follows:
  • If x is a complete object, then the complete object of x is itself.
  • Otherwise, the complete object of x is the complete object of the (unique) object that contains x.
If a complete object, a data member ([class.mem]), or an array element is of class type, its type is considered the most derived class, to distinguish it from the class type of any base class subobject; an object of a most derived class type or of a non-class type is called a most derived object.
Unless it is a bit-field ([class.bit]), a most derived object shall have a nonzero size and shall occupy one or more bytes of storage.
Base class subobjects may have zero size.
An object of trivially copyable or standard-layout type ([basic.types]) shall occupy contiguous bytes of storage.
Unless an object is a bit-field or a base class subobject of zero size, the address of that object is the address of the first byte it occupies.
Two objects a and b with overlapping lifetimes that are not bit-fields may have the same address if one is nested within the other, or if at least one is a base class subobject of zero size and they are of different types; otherwise, they have distinct addresses.5
[Example
:
static const char test1 = 'x';
static const char test2 = 'x';
const bool b = &test1 != &test2;      // always true
end example
]
[Note
:
C++ provides a variety of fundamental types and several ways of composing new types from existing types ([basic.types]).
end note
]
Under the “as-if” rule an implementation is allowed to store two objects at the same machine address or not store an object at all if the program cannot observe the difference ([intro.execution]).

4.6 Program execution [intro.execution]

The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine.
This International Standard places no requirement on the structure of conforming implementations.
In particular, they need not copy or emulate the structure of the abstract machine.
Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.6
Certain aspects and operations of the abstract machine are described in this International Standard as implementation-defined (for example, sizeof(int)).
These constitute the parameters of the abstract machine.
Each implementation shall include documentation describing its characteristics and behavior in these respects.7
Such documentation shall define the instance of the abstract machine that corresponds to that implementation (referred to as the “corresponding instance” below).
Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, evaluation of expressions in a new-initializer if the allocation function fails to allocate memory ([expr.new])).
Where possible, this International Standard defines a set of allowable behaviors.
These define the nondeterministic aspects of the abstract machine.
An instance of the abstract machine can thus have more than one possible execution for a given program and a given input.
Certain other operations are described in this International Standard as undefined (for example, the effect of attempting to modify a const object).
[Note
:
This International Standard imposes no requirements on the behavior of programs that contain undefined behavior.
end note
]
A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible executions of the corresponding instance of the abstract machine with the same program and the same input.
However, if any such execution contains an undefined operation, this International Standard places no requirement on the implementation executing that program with that input (not even with regard to operations preceding the first undefined operation).
An instance of each object with automatic storage duration ([basic.stc.auto]) is associated with each entry into its block.
Such an object exists and retains its last-stored value during the execution of the block and while the block is suspended (by a call of a function or receipt of a signal).
The least requirements on a conforming implementation are:
  • Accesses through volatile glvalues are evaluated strictly according to the rules of the abstract machine.
  • At program termination, all data written into files shall be identical to one of the possible results that execution of the program according to the abstract semantics would have produced.
  • The input and output dynamics of interactive devices shall take place in such a fashion that prompting output is actually delivered before a program waits for input.
    What constitutes an interactive device is implementation-defined.
These collectively are referred to as the observable behavior of the program.
[Note
:
More stringent correspondences between abstract and actual semantics may be defined by each implementation.
end note
]
[Note
:
Operators can be regrouped according to the usual mathematical rules only where the operators really are associative or commutative.8
For example, in the following fragment
int a, b;
/* ... */
a = a + 32760 + b + 5;
the expression statement behaves exactly the same as
a = (((a + 32760) + b) + 5);
due to the associativity and precedence of these operators.
Thus, the result of the sum (a + 32760) is next added to b, and that result is then added to 5 which results in the value assigned to a.
On a machine in which overflows produce an exception and in which the range of values representable by an int is [-32768, +32767], the implementation cannot rewrite this expression as
a = ((a + b) + 32765);
since if the values for a and b were, respectively, -32754 and -15, the sum a + b would produce an exception while the original expression would not; nor can the expression be rewritten either as
a = ((a + 32765) + b);
or
a = (a + (b + 32765));
since the values for a and b might have been, respectively, 4 and -8 or -17 and 12.
However on a machine in which overflows do not produce an exception and in which the results of overflows are reversible, the above expression statement can be rewritten by the implementation in any of the above ways because the same result will occur.
end note
]
A constituent expression is defined as follows:
[Example
:
struct A { int x; };
struct B { int y; struct A a; };
B b = { 5, { 1+1 } };
The constituent expressions of the initializer used for the initialization of b are 5 and 1+1.
end example
]
The immediate subexpressions of an expression e are
A subexpression of an expression e is an immediate subexpression of e or a subexpression of an immediate subexpression of e.
[Note
:
Expressions appearing in the compound-statement of a lambda-expression are not subexpressions of the lambda-expression.
end note
]
A full-expression is
If a language construct is defined to produce an implicit call of a function, a use of the language construct is considered to be an expression for the purposes of this definition.
Conversions applied to the result of an expression in order to satisfy the requirements of the language construct in which the expression appears are also considered to be part of the full-expression.
For an initializer, performing the initialization of the entity (including evaluating default member initializers of an aggregate) is also considered part of the full-expression.
[Example
:
struct S {
  S(int i): I(i) { }       // full-expression is initialization of I
  int& v() { return I; }
  ~S() noexcept(false) { }
private:
  int I;
};

S s1(1);                   // full-expression is call of S​::​S(int)
void f() {
  S s2 = 2;                // full-expression is call of S​::​S(int)
  if (S(3).v())            // full-expression includes lvalue-to-rvalue and
                           // int to bool conversions, performed before
                           // temporary is deleted at end of full-expression
  { }
  bool b = noexcept(S());  // exception specification of destructor of S
                           // considered for noexcept
  // full-expression is destruction of s2 at end of block
}
struct B {
      B(S = S(0));
   };
   B b[2] = { B(), B() };  // full-expression is the entire initialization
                           // including the destruction of temporaries
end example
]
[Note
:
The evaluation of a full-expression can include the evaluation of subexpressions that are not lexically part of the full-expression.
For example, subexpressions involved in evaluating default arguments ([dcl.fct.default]) are considered to be created in the expression that calls the function, not the expression that defines the default argument.
end note
]
Reading an object designated by a volatile glvalue ([basic.lval]), modifying an object, calling a library I/O function, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment.
Evaluation of an expression (or a subexpression) in general includes both value computations (including determining the identity of an object for glvalue evaluation and fetching a value previously assigned to an object for prvalue evaluation) and initiation of side effects.
When a call to a library I/O function returns or an access through a volatile glvalue is evaluated the side effect is considered complete, even though some external actions implied by the call (such as the I/O itself) or by the volatile access may not have completed yet.
Sequenced before is an asymmetric, transitive, pair-wise relation between evaluations executed by a single thread ([intro.multithread]), which induces a partial order among those evaluations.
Given any two evaluations A and B, if A is sequenced before B (or, equivalently, B is sequenced after A), then the execution of A shall precede the execution of B.
If A is not sequenced before B and B is not sequenced before A, then A and B are unsequenced.
[Note
:
The execution of unsequenced evaluations can overlap.
end note
]
Evaluations A and B are indeterminately sequenced when either A is sequenced before B or B is sequenced before A, but it is unspecified which.
[Note
:
Indeterminately sequenced evaluations cannot overlap, but either could be executed first.
end note
]
An expression X is said to be sequenced before an expression Y if every value computation and every side effect associated with the expression X is sequenced before every value computation and every side effect associated with the expression Y.
Every value computation and side effect associated with a full-expression is sequenced before every value computation and side effect associated with the next full-expression to be evaluated.9
Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.
[Note
:
In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations.
end note
]
The value computations of the operands of an operator are sequenced before the value computation of the result of the operator.
If a side effect on a memory location ([intro.memory]) is unsequenced relative to either another side effect on the same memory location or a value computation using the value of any object in the same memory location, and they are not potentially concurrent ([intro.multithread]), the behavior is undefined.
[Note
:
The next section imposes similar, but more complex restrictions on potentially concurrent computations.
end note
]
[Example
:
void g(int i) {
  i = 7, i++, i++;    // i becomes 9

  i = i++ + 1;        // the value of i is incremented
  i = i++ + i;        // the behavior is undefined
  i = i + 1;          // the value of i is incremented
}
end example
]
When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function.
For each function invocation F, for every evaluation A that occurs within F and every evaluation B that does not occur within F but is evaluated on the same thread and as part of the same signal handler (if any), either A is sequenced before B or B is sequenced before A.10
[Note
:
If A and B would not otherwise be sequenced then they are indeterminately sequenced.
end note
]
Several contexts in C++ cause evaluation of a function call, even though no corresponding function call syntax appears in the translation unit.
[Example
:
Evaluation of a new-expression invokes one or more allocation and constructor functions; see [expr.new].
For another example, invocation of a conversion function ([class.conv.fct]) can arise in contexts in which no function call syntax appears.
end example
]
The sequencing constraints on the execution of the called function (as described above) are features of the function calls as evaluated, whatever the syntax of the expression that calls the function might be.
If a signal handler is executed as a result of a call to the std​::​raise function, then the execution of the handler is sequenced after the invocation of the std​::​raise function and before its return.
[Note
:
When a signal is received for another reason, the execution of the signal handler is usually unsequenced with respect to the rest of the program.
end note
]
This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program.
For instance, an actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no side effects affecting the observable behavior of the program are produced.
This documentation also includes conditionally-supported constructs and locale-specific behavior.
Overloaded operators are never assumed to be associative or commutative.
As specified in [class.temporary], after a full-expression is evaluated, a sequence of zero or more invocations of destructor functions for temporary objects takes place, usually in reverse order of the construction of each temporary object.
In other words, function executions do not interleave with each other.

4.7 Multi-threaded executions and data races [intro.multithread]

A thread of execution (also known as a thread) is a single flow of control within a program, including the initial invocation of a specific top-level function, and recursively including every function invocation subsequently executed by the thread.
[Note
:
When one thread creates another, the initial call to the top-level function of the new thread is executed by the new thread, not by the creating thread.
end note
]
Every thread in a program can potentially access every object and function in a program.11
Under a hosted implementation, a C++ program can have more than one thread running concurrently.
The execution of each thread proceeds as defined by the remainder of this International Standard.
The execution of the entire program consists of an execution of all of its threads.
[Note
:
Usually the execution can be viewed as an interleaving of all its threads.
However, some kinds of atomic operations, for example, allow executions inconsistent with a simple interleaving, as described below.
end note
]
Under a freestanding implementation, it is implementation-defined whether a program can have more than one thread of execution.
For a signal handler that is not executed as a result of a call to the std​::​raise function, it is unspecified which thread of execution contains the signal handler invocation.
An object with automatic or thread storage duration ([basic.stc]) is associated with one specific thread, and can be accessed by a different thread only indirectly through a pointer or reference ([basic.compound]).

4.7.1 Data races [intro.races]

The value of an object visible to a thread T at a particular point is the initial value of the object, a value assigned to the object by T, or a value assigned to the object by another thread, according to the rules below.
[Note
:
In some cases, there may instead be undefined behavior.
Much of this section is motivated by the desire to support atomic operations with explicit and detailed visibility constraints.
However, it also implicitly supports a simpler view for more restricted programs.
end note
]
Two expression evaluations conflict if one of them modifies a memory location ([intro.memory]) and the other one reads or modifies the same memory location.
The library defines a number of atomic operations (Clause [atomics]) and operations on mutexes (Clause [thread]) that are specially identified as synchronization operations.
These operations play a special role in making assignments in one thread visible to another.
A synchronization operation on one or more memory locations is either a consume operation, an acquire operation, a release operation, or both an acquire and release operation.
A synchronization operation without an associated memory location is a fence and can be either an acquire fence, a release fence, or both an acquire and release fence.
In addition, there are relaxed atomic operations, which are not synchronization operations, and atomic read-modify-write operations, which have special characteristics.
[Note
:
For example, a call that acquires a mutex will perform an acquire operation on the locations comprising the mutex.
Correspondingly, a call that releases the same mutex will perform a release operation on those same locations.
Informally, performing a release operation on A forces prior side effects on other memory locations to become visible to other threads that later perform a consume or an acquire operation on A.
“Relaxed” atomic operations are not synchronization operations even though, like synchronization operations, they cannot contribute to data races.
end note
]
All modifications to a particular atomic object M occur in some particular total order, called the modification order of M.
[Note
:
There is a separate order for each atomic object.
There is no requirement that these can be combined into a single total order for all objects.
In general this will be impossible since different threads may observe modifications to different objects in inconsistent orders.
end note
]
A release sequence headed by a release operation A on an atomic object M is a maximal contiguous sub-sequence of side effects in the modification order of M, where the first operation is A, and every subsequent operation
  • is performed by the same thread that performed A, or
  • is an atomic read-modify-write operation.
Certain library calls synchronize with other library calls performed by another thread.
For example, an atomic store-release synchronizes with a load-acquire that takes its value from the store ([atomics.order]).
[Note
:
Except in the specified cases, reading a later value does not necessarily ensure visibility as described below.
Such a requirement would sometimes interfere with efficient implementation.
end note
]
[Note
:
The specifications of the synchronization operations define when one reads the value written by another.
For atomic objects, the definition is clear.
All operations on a given mutex occur in a single total order.
Each mutex acquisition “reads the value written” by the last mutex release.
end note
]
An evaluation A carries a dependency to an evaluation B if
  • the value of A is used as an operand of B, unless: or
  • A writes a scalar object or bit-field M, B reads the value written by A from M, and A is sequenced before B, or
  • for some evaluation X, A carries a dependency to X, and X carries a dependency to B.
[Note
:
“Carries a dependency to” is a subset of “is sequenced before”, and is similarly strictly intra-thread.
end note
]
An evaluation A is dependency-ordered before an evaluation B if
  • A performs a release operation on an atomic object M, and, in another thread, B performs a consume operation on M and reads a value written by any side effect in the release sequence headed by A, or
  • for some evaluation X, A is dependency-ordered before X and X carries a dependency to B.
[Note
:
The relation “is dependency-ordered before” is analogous to “synchronizes with”, but uses release/consume in place of release/acquire.
end note
]
An evaluation A inter-thread happens before an evaluation B if
  • A synchronizes with B, or
  • A is dependency-ordered before B, or
  • for some evaluation X
    • A synchronizes with X and X is sequenced before B, or
    • A is sequenced before X and X inter-thread happens before B, or
    • A inter-thread happens before X and X inter-thread happens before B.
[Note
:
The “inter-thread happens before” relation describes arbitrary concatenations of “sequenced before”, “synchronizes with” and “dependency-ordered before” relationships, with two exceptions.
The first exception is that a concatenation is not permitted to end with “dependency-ordered before” followed by “sequenced before”.
The reason for this limitation is that a consume operation participating in a “dependency-ordered before” relationship provides ordering only with respect to operations to which this consume operation actually carries a dependency.
The reason that this limitation applies only to the end of such a concatenation is that any subsequent release operation will provide the required ordering for a prior consume operation.
The second exception is that a concatenation is not permitted to consist entirely of “sequenced before”.
The reasons for this limitation are (1) to permit “inter-thread happens before” to be transitively closed and (2) the “happens before” relation, defined below, provides for relationships consisting entirely of “sequenced before”.
end note
]
An evaluation A happens before an evaluation B (or, equivalently, B happens after A) if:
  • A is sequenced before B, or
  • A inter-thread happens before B.
The implementation shall ensure that no program execution demonstrates a cycle in the “happens before” relation.
[Note
:
This cycle would otherwise be possible only through the use of consume operations.
end note
]
An evaluation A strongly happens before an evaluation B if either
  • A is sequenced before B, or
  • A synchronizes with B, or
  • A strongly happens before X and X strongly happens before B.
[Note
:
In the absence of consume operations, the happens before and strongly happens before relations are identical.
Strongly happens before essentially excludes consume operations.
end note
]
A visible side effect A on a scalar object or bit-field M with respect to a value computation B of M satisfies the conditions:
  • A happens before B and
  • there is no other side effect X to M such that A happens before X and X happens before B.
The value of a non-atomic scalar object or bit-field M, as determined by evaluation B, shall be the value stored by the visible side effect A.
[Note
:
If there is ambiguity about which side effect to a non-atomic object or bit-field is visible, then the behavior is either unspecified or undefined.
end note
]
[Note
:
This states that operations on ordinary objects are not visibly reordered.
This is not actually detectable without data races, but it is necessary to ensure that data races, as defined below, and with suitable restrictions on the use of atomics, correspond to data races in a simple interleaved (sequentially consistent) execution.
end note
]
The value of an atomic object M, as determined by evaluation B, shall be the value stored by some side effect A that modifies M, where B does not happen before A.
[Note
:
The set of such side effects is also restricted by the rest of the rules described here, and in particular, by the coherence requirements below.
end note
]
If an operation A that modifies an atomic object M happens before an operation B that modifies M, then A shall be earlier than B in the modification order of M.
[Note
:
This requirement is known as write-write coherence.
end note
]
If a value computation A of an atomic object M happens before a value computation B of M, and A takes its value from a side effect X on M, then the value computed by B shall either be the value stored by X or the value stored by a side effect Y on M, where Y follows X in the modification order of M.
[Note
:
This requirement is known as read-read coherence.
end note
]
If a value computation A of an atomic object M happens before an operation B that modifies M, then A shall take its value from a side effect X on M, where X precedes B in the modification order of M.
[Note
:
This requirement is known as read-write coherence.
end note
]
If a side effect X on an atomic object M happens before a value computation B of M, then the evaluation B shall take its value from X or from a side effect Y that follows X in the modification order of M.
[Note
:
This requirement is known as write-read coherence.
end note
]
[Note
:
The four preceding coherence requirements effectively disallow compiler reordering of atomic operations to a single object, even if both operations are relaxed loads.
This effectively makes the cache coherence guarantee provided by most hardware available to C++ atomic operations.
end note
]
[Note
:
The value observed by a load of an atomic depends on the “happens before” relation, which depends on the values observed by loads of atomics.
The intended reading is that there must exist an association of atomic loads with modifications they observe that, together with suitably chosen modification orders and the “happens before” relation derived as described above, satisfy the resulting constraints as imposed here.
end note
]
Two actions are potentially concurrent if
  • they are performed by different threads, or
  • they are unsequenced, at least one is performed by a signal handler, and they are not both performed by the same signal handler invocation.
The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, except for the special case for signal handlers described below.
Any such data race results in undefined behavior.
[Note
:
It can be shown that programs that correctly use mutexes and memory_­order_­seq_­cst operations to prevent all data races and use no other synchronization operations behave as if the operations executed by their constituent threads were simply interleaved, with each value computation of an object being taken from the last side effect on that object in that interleaving.
This is normally referred to as “sequential consistency”.
However, this applies only to data-race-free programs, and data-race-free programs cannot observe most program transformations that do not change single-threaded program semantics.
In fact, most single-threaded program transformations continue to be allowed, since any program that behaves differently as a result must perform an undefined operation.
end note
]
Two accesses to the same object of type volatile std​::​sig_­atomic_­t do not result in a data race if both occur in the same thread, even if one or more occurs in a signal handler.
For each signal handler invocation, evaluations performed by the thread invoking a signal handler can be divided into two groups A and B, such that no evaluations in B happen before evaluations in A, and the evaluations of such volatile std​::​sig_­atomic_­t objects take values as though all evaluations in A happened before the execution of the signal handler and the execution of the signal handler happened before all evaluations in B.
[Note
:
Compiler transformations that introduce assignments to a potentially shared memory location that would not be modified by the abstract machine are generally precluded by this International Standard, since such an assignment might overwrite another assignment by a different thread in cases in which an abstract machine execution would not have encountered a data race.
This includes implementations of data member assignment that overwrite adjacent members in separate memory locations.
Reordering of atomic loads in cases in which the atomics in question may alias is also generally precluded, since this may violate the coherence rules.
end note
]
[Note
:
Transformations that introduce a speculative read of a potentially shared memory location may not preserve the semantics of the C++ program as defined in this International Standard, since they potentially introduce a data race.
However, they are typically valid in the context of an optimizing compiler that targets a specific machine with well-defined semantics for data races.
They would be invalid for a hypothetical machine that is not tolerant of races or provides hardware race detection.
end note
]

4.7.2 Forward progress [intro.progress]

The implementation may assume that any thread will eventually do one of the following:
  • terminate,
  • make a call to a library I/O function,
  • perform an access through a volatile glvalue, or
  • perform a synchronization operation or an atomic operation.
[Note
:
This is intended to allow compiler transformations such as removal of empty loops, even when termination cannot be proven.
end note
]
Executions of atomic functions that are either defined to be lock-free ([atomics.flag]) or indicated as lock-free ([atomics.lockfree]) are lock-free executions.
  • If there is only one thread that is not blocked ([defns.block]) in a standard library function, a lock-free execution in that thread shall complete.
    [Note
    :
    Concurrently executing threads may prevent progress of a lock-free execution.
    For example, this situation can occur with load-locked store-conditional implementations.
    This property is sometimes termed obstruction-free.
    end note
    ]
  • When one or more lock-free executions run concurrently, at least one should complete.
    [Note
    :
    It is difficult for some implementations to provide absolute guarantees to this effect, since repeated and particularly inopportune interference from other threads may prevent forward progress, e.g., by repeatedly stealing a cache line for unrelated purposes between load-locked and store-conditional instructions. Implementations should ensure that such effects cannot indefinitely delay progress under expected operating conditions, and that such anomalies can therefore safely be ignored by programmers. Outside this document, this property is sometimes termed lock-free.
    end note
    ]
During the execution of a thread of execution, each of the following is termed an execution step:
  • termination of the thread of execution,
  • performing an access through a volatile glvalue, or
  • completion of a call to a library I/O function, a synchronization operation, or an atomic operation.
An invocation of a standard library function that blocks ([defns.block]) is considered to continuously execute execution steps while waiting for the condition that it blocks on to be satisfied.
[Example
:
A library I/O function that blocks until the I/O operation is complete can be considered to continuously check whether the operation is complete.
Each such check might consist of one or more execution steps, for example using observable behavior of the abstract machine.
end example
]
[Note
:
Because of this and the preceding requirement regarding what threads of execution have to perform eventually, it follows that no thread of execution can execute forever without an execution step occurring.
end note
]
A thread of execution makes progress when an execution step occurs or a lock-free execution does not complete because there are other concurrent threads that are not blocked in a standard library function (see above).
For a thread of execution providing concurrent forward progress guarantees, the implementation ensures that the thread will eventually make progress for as long as it has not terminated.
[Note
:
This is required regardless of whether or not other threads of executions (if any) have been or are making progress.
To eventually fulfill this requirement means that this will happen in an unspecified but finite amount of time.
end note
]
It is implementation-defined whether the implementation-created thread of execution that executes main ([basic.start.main]) and the threads of execution created by std​::​thread ([thread.thread.class]) provide concurrent forward progress guarantees.
[Note
:
General-purpose implementations are encouraged to provide these guarantees.
end note
]
For a thread of execution providing parallel forward progress guarantees, the implementation is not required to ensure that the thread will eventually make progress if it has not yet executed any execution step; once this thread has executed a step, it provides concurrent forward progress guarantees.
[Note
:
This does not specify a requirement for when to start this thread of execution, which will typically be specified by the entity that creates this thread of execution.
For example, a thread of execution that provides concurrent forward progress guarantees and executes tasks from a set of tasks in an arbitrary order, one after the other, satisfies the requirements of parallel forward progress for these tasks.
end note
]
For a thread of execution providing weakly parallel forward progress guarantees, the implementation does not ensure that the thread will eventually make progress.
[Note
:
Threads of execution providing weakly parallel forward progress guarantees cannot be expected to make progress regardless of whether other threads make progress or not; however, blocking with forward progress guarantee delegation, as defined below, can be used to ensure that such threads of execution make progress eventually.
end note
]
Concurrent forward progress guarantees are stronger than parallel forward progress guarantees, which in turn are stronger than weakly parallel forward progress guarantees.
[Note
:
For example, some kinds of synchronization between threads of execution may only make progress if the respective threads of execution provide parallel forward progress guarantees, but will fail to make progress under weakly parallel guarantees.
end note
]
When a thread of execution P is specified to block with forward progress guarantee delegation on the completion of a set S of threads of execution, then throughout the whole time of P being blocked on S, the implementation shall ensure that the forward progress guarantees provided by at least one thread of execution in S is at least as strong as P's forward progress guarantees.
[Note
:
It is unspecified which thread or threads of execution in S are chosen and for which number of execution steps.
The strengthening is not permanent and not necessarily in place for the rest of the lifetime of the affected thread of execution.
As long as P is blocked, the implementation has to eventually select and potentially strengthen a thread of execution in S.
end note
]
Once a thread of execution in S terminates, it is removed from S.
Once S is empty, P is unblocked.
[Note
:
A thread of execution B thus can temporarily provide an effectively stronger forward progress guarantee for a certain amount of time, due to a second thread of execution A being blocked on it with forward progress guarantee delegation.
In turn, if B then blocks with forward progress guarantee delegation on C, this may also temporarily provide a stronger forward progress guarantee to C.
end note
]
[Note
:
If all threads of execution in S finish executing (e.g., they terminate and do not use blocking synchronization incorrectly), then P's execution of the operation that blocks with forward progress guarantee delegation will not result in P's progress guarantee being effectively weakened.
end note
]
[Note
:
This does not remove any constraints regarding blocking synchronization for threads of execution providing parallel or weakly parallel forward progress guarantees because the implementation is not required to strengthen a particular thread of execution whose too-weak progress guarantee is preventing overall progress.
end note
]
An implementation should ensure that the last value (in modification order) assigned by an atomic or synchronization operation will become visible to all other threads in a finite period of time.

4.8 Acknowledgments [intro.ack]

The C++ programming language as described in this document is based on the language as described in Chapter R (Reference Manual) of Stroustrup: The C++ Programming Language (second edition, Addison-Wesley Publishing Company, ISBN 0-201-53992-6, copyright ©1991 AT&T).
That, in turn, is based on the C programming language as described in Appendix A of Kernighan and Ritchie: The C Programming Language (Prentice-Hall, 1978, ISBN 0-13-110163-3, copyright ©1978 AT&T).
Portions of the library Clauses of this document are based on work by P.
J.
Plauger, which was published as The Draft Standard C++ Library (Prentice-Hall, ISBN 0-13-117003-1, copyright ©1995 P.
J.
Plauger).
POSIX® is a registered trademark of the Institute of Electrical and Electronic Engineers, Inc.
ECMAScript® is a registered trademark of Ecma International.
All rights in these originals are reserved.

5 Lexical conventions [lex]

5.1 Separate translation [lex.separate]

The text of the program is kept in units called source files in this International Standard.
A source file together with all the headers ([headers]) and source files included ([cpp.include]) via the preprocessing directive #include, less any source lines skipped by any of the conditional inclusion ([cpp.cond]) preprocessing directives, is called a translation unit.
[Note
:
A C++ program need not all be translated at the same time.
end note
]
[Note
:
Previously translated translation units and instantiation units can be preserved individually or in libraries.
The separate translation units of a program communicate ([basic.link]) by (for example) calls to functions whose identifiers have external linkage, manipulation of objects whose identifiers have external linkage, or manipulation of data files.
Translation units can be separately translated and then later linked to produce an executable program ([basic.link]).
end note
]

5.2 Phases of translation [lex.phases]

The precedence among the syntax rules of translation is specified by the following phases.12
  1. 1.
    Physical source file characters are mapped, in an implementation-defined manner, to the basic source character set (introducing new-line characters for end-of-line indicators) if necessary.
    The set of physical source file characters accepted is implementation-defined.
    Any source file character not in the basic source character set ([lex.charset]) is replaced by the universal-character-name that designates that character.
    An implementation may use any internal encoding, so long as an actual extended character encountered in the source file, and the same extended character expressed in the source file as a universal-character-name (e.g., using the \uXXXX notation), are handled equivalently except where this replacement is reverted ([lex.pptoken]) in a raw string literal.
  2. 2.
    Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines.
    Only the last backslash on any physical source line shall be eligible for being part of such a splice.
    Except for splices reverted in a raw string literal, if a splice results in a character sequence that matches the syntax of a universal-character-name, the behavior is undefined.
    A source file that is not empty and that does not end in a new-line character, or that ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, shall be processed as if an additional new-line character were appended to the file.
  3. 3.
    The source file is decomposed into preprocessing tokens ([lex.pptoken]) and sequences of white-space characters (including comments).
    A source file shall not end in a partial preprocessing token or in a partial comment.13
    Each comment is replaced by one space character.
    New-line characters are retained.
    Whether each nonempty sequence of white-space characters other than new-line is retained or replaced by one space character is unspecified.
    The process of dividing a source file's characters into preprocessing tokens is context-dependent.
    [Example
    :
    see the handling of < within a #include preprocessing directive.
    end example
    ]
  4. 4.
    Preprocessing directives are executed, macro invocations are expanded, and _­Pragma unary operator expressions are executed.
    If a character sequence that matches the syntax of a universal-character-name is produced by token concatenation ([cpp.concat]), the behavior is undefined.
    A #include preprocessing directive causes the named header or source file to be processed from phase 1 through phase 4, recursively.
    All preprocessing directives are then deleted.
  5. 5.
    Each source character set member in a character literal or a string literal, as well as each escape sequence and universal-character-name in a character literal or a non-raw string literal, is converted to the corresponding member of the execution character set ([lex.ccon], [lex.string]); if there is no corresponding member, it is converted to an implementation-defined member other than the null (wide) character.14
  6. 6.
    Adjacent string literal tokens are concatenated.
  7. 7.
    White-space characters separating tokens are no longer significant.
    Each preprocessing token is converted into a token ([lex.token]).
    The resulting tokens are syntactically and semantically analyzed and translated as a translation unit.
    [Note
    :
    The process of analyzing and translating the tokens may occasionally result in one token being replaced by a sequence of other tokens ([temp.names]).
    end note
    ]
    [Note
    :
    Source files, translation units and translated translation units need not necessarily be stored as files, nor need there be any one-to-one correspondence between these entities and any external representation.
    The description is conceptual only, and does not specify any particular implementation.
    end note
    ]
  8. 8.
    Translated translation units and instantiation units are combined as follows:
    [Note
    :
    Some or all of these may be supplied from a library.
    end note
    ]
    Each translated translation unit is examined to produce a list of required instantiations.
    [Note
    :
    This may include instantiations which have been explicitly requested ([temp.explicit]).
    end note
    ]
    The definitions of the required templates are located.
    It is implementation-defined whether the source of the translation units containing these definitions is required to be available.
    [Note
    :
    An implementation could encode sufficient information into the translated translation unit so as to ensure the source is not required here.
    end note
    ]
    All the required instantiations are performed to produce instantiation units.
    [Note
    :
    These are similar to translated translation units, but contain no references to uninstantiated templates and no template definitions.
    end note
    ]
    The program is ill-formed if any instantiation fails.
  9. 9.
    All external entity references are resolved.
    Library components are linked to satisfy external references to entities not defined in the current translation.
    All such translator output is collected into a program image which contains information needed for execution in its execution environment.
Implementations must behave as if these separate phases occur, although in practice different phases might be folded together.
A partial preprocessing token would arise from a source file ending in the first portion of a multi-character token that requires a terminating sequence of characters, such as a header-name that is missing the closing " or >.
A partial comment would arise from a source file ending with an unclosed /* comment.
An implementation need not convert all non-corresponding source characters to the same execution character.

5.3 Character sets [lex.charset]

The basic source character set consists of 96 characters: the space character, the control characters representing horizontal tab, vertical tab, form feed, and new-line, plus the following 91 graphical characters:15
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
0 1 2 3 4 5 6 7 8 9
_ { } [ ] # ( ) < > % : ; . ? * + - / ^ & | ~ ! = , \ " '
The universal-character-name construct provides a way to name other characters.
hex-quad:
	hexadecimal-digit hexadecimal-digit hexadecimal-digit hexadecimal-digit
universal-character-name:
	\u hex-quad
	\U hex-quad hex-quad
The character designated by the universal-character-name \UNNNNNNNN is that character whose character short name in ISO/IEC 10646 is NNNNNNNN; the character designated by the universal-character-name \uNNNN is that character whose character short name in ISO/IEC 10646 is 0000NNNN.
If the hexadecimal value for a universal-character-name corresponds to a surrogate code point (in the range 0xD800–0xDFFF, inclusive), the program is ill-formed.
Additionally, if the hexadecimal value for a universal-character-name outside the c-char-sequence, s-char-sequence, or r-char-sequence of a character or string literal corresponds to a control character (in either of the ranges 0x00–0x1F or 0x7F–0x9F, both inclusive) or to a character in the basic source character set, the program is ill-formed.16
The basic execution character set and the basic execution wide-character set shall each contain all the members of the basic source character set, plus control characters representing alert, backspace, and carriage return, plus a null character (respectively, null wide character), whose value is 0.
For each basic execution character set, the values of the members shall be non-negative and distinct from one another.
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
The execution character set and the execution wide-character set are implementation-defined supersets of the basic execution character set and the basic execution wide-character set, respectively.
The values of the members of the execution character sets and the sets of additional members are locale-specific.
The glyphs for the members of the basic source character set are intended to identify characters from the subset of ISO/IEC 10646 which corresponds to the ASCII character set.
However, because the mapping from source file characters to the source character set (described in translation phase 1) is specified as implementation-defined, an implementation is required to document how the basic source characters are represented in source files.
A sequence of characters resembling a universal-character-name in an r-char-sequence does not form a universal-character-name.

5.4 Preprocessing tokens [lex.pptoken]

Each preprocessing token that is converted to a token ([lex.token]) shall have the lexical form of a keyword, an identifier, a literal, an operator, or a punctuator.
A preprocessing token is the minimal lexical element of the language in translation phases 3 through 6.
The categories of preprocessing token are: header names, identifiers, preprocessing numbers, character literals (including user-defined character literals), string literals (including user-defined string literals), preprocessing operators and punctuators, and single non-white-space characters that do not lexically match the other preprocessing token categories.
If a ' or a " character matches the last category, the behavior is undefined.
Preprocessing tokens can be separated by white space; this consists of comments ([lex.comment]), or white-space characters (space, horizontal tab, new-line, vertical tab, and form-feed), or both.
As described in Clause [cpp], in certain circumstances during translation phase 4, white space (or the absence thereof) serves as more than preprocessing token separation.
White space can appear within a preprocessing token only as part of a header name or between the quotation characters in a character literal or string literal.
If the input stream has been parsed into preprocessing tokens up to a given character:
  • If the next character begins a sequence of characters that could be the prefix and initial double quote of a raw string literal, such as R", the next preprocessing token shall be a raw string literal.
    Between the initial and final double quote characters of the raw string, any transformations performed in phases 1 and 2 (universal-character-names and line splicing) are reverted; this reversion shall apply before any d-char, r-char, or delimiting parenthesis is identified.
    The raw string literal is defined as the shortest sequence of characters that matches the raw-string pattern
  • Otherwise, if the next three characters are <​::​ and the subsequent character is neither : nor >, the < is treated as a preprocessing token by itself and not as the first character of the alternative token <:.
  • Otherwise, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token, even if that would cause further lexical analysis to fail, except that a header-name is only formed within a #include directive ([cpp.include]).
[Example
:
#define R "x"
const char* s = R"y";           // ill-formed raw string, not "x" "y"
end example
]
[Example
:
The program fragment 0xe+foo is parsed as a preprocessing number token (one that is not a valid floating or integer literal token), even though a parse as three preprocessing tokens 0xe, +, and foo might produce a valid expression (for example, if foo were a macro defined as 1).
Similarly, the program fragment 1E1 is parsed as a preprocessing number (one that is a valid floating literal token), whether or not E is a macro name.
end example
]
[Example
:
The program fragment x+++++y is parsed as x ++ ++ + y, which, if x and y have integral types, violates a constraint on increment operators, even though the parse x ++ + ++ y might yield a correct expression.
end example
]

5.5 Alternative tokens [lex.digraph]

Alternative token representations are provided for some operators and punctuators.17
In all respects of the language, each alternative token behaves the same, respectively, as its primary token, except for its spelling.18
The set of alternative tokens is defined in Table 1.
Table 1 — Alternative tokens
Alternative
Primary
Alternative
Primary
Alternative
Primary
<%
{
and
&&
and_­eq
&=
%>
}
bitor
|
or_­eq
|=
<:
[
or
||
xor_­eq
^=
:>
]
xor
^
not
!
%:
#
compl
~
not_­eq
!=
%:%:
##
bitand
&
These include “digraphs” and additional reserved words.
The term “digraph” (token consisting of two characters) is not perfectly descriptive, since one of the alternative preprocessing-tokens is %:%: and of course several primary tokens contain two characters.
Nonetheless, those alternative tokens that aren't lexical keywords are colloquially known as “digraphs”.
Thus the “stringized” values ([cpp.stringize]) of [ and <: will be different, maintaining the source spelling, but the tokens can otherwise be freely interchanged.

5.6 Tokens [lex.token]

token:
	identifier
	keyword
	literal
	operator
	punctuator
There are five kinds of tokens: identifiers, keywords, literals,19 operators, and other separators.
Blanks, horizontal and vertical tabs, newlines, formfeeds, and comments (collectively, “white space”), as described below, are ignored except as they serve to separate tokens.
[Note
:
Some white space is required to separate otherwise adjacent identifiers, keywords, numeric literals, and alternative tokens containing alphabetic characters.
end note
]
Literals include strings and character and numeric literals.

5.7 Comments [lex.comment]

The characters /* start a comment, which terminates with the characters */.
These comments do not nest.
The characters // start a comment, which terminates immediately before the next new-line character.
If there is a form-feed or a vertical-tab character in such a comment, only white-space characters shall appear between it and the new-line that terminates the comment; no diagnostic is required.
[Note
:
The comment characters //, /*, and */ have no special meaning within a // comment and are treated just like other characters.
Similarly, the comment characters // and /* have no special meaning within a /* comment.
end note
]

5.8 Header names [lex.header]

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 "
[Note
:
Header name preprocessing tokens only appear within a #include preprocessing directive (see [lex.pptoken]).
end note
]
The sequences in both forms of header-names are mapped in an implementation-defined manner to headers or to external source file names as specified in [cpp.include].
The appearance of either of the characters ' or \ or of either of the character sequences /* or // in a q-char-sequence or an h-char-sequence is conditionally-supported with implementation-defined semantics, as is the appearance of the character " in an h-char-sequence.20
Thus, a sequence of characters that resembles an escape sequence might result in an error, be interpreted as the character corresponding to the escape sequence, or have a completely different meaning, depending on the implementation.

5.9 Preprocessing numbers [lex.ppnumber]

Preprocessing number tokens lexically include all integer literal tokens ([lex.icon]) and all floating literal tokens ([lex.fcon]).
A preprocessing number does not have a type or a value; it acquires both after a successful conversion to an integer literal token or a floating literal token.

5.10 Identifiers [lex.name]

identifier:
	identifier-nondigit
	identifier identifier-nondigit
	identifier digit
identifier-nondigit:
	nondigit
	universal-character-name
nondigit: one of
	a b c d e f g h i j k l m
	n o p q r s t u v w x y z
	A B C D E F G H I J K L M
	N O P Q R S T U V W X Y Z _
digit: one of
	0 1 2 3 4 5 6 7 8 9
An identifier is an arbitrarily long sequence of letters and digits.
Each universal-character-name in an identifier shall designate a character whose encoding in ISO 10646 falls into one of the ranges specified in Table 2.
The initial element shall not be a universal-character-name designating a character whose encoding falls into one of the ranges specified in Table 3.
Upper- and lower-case letters are different.
All characters are significant.21
Table 2 — Ranges of characters 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-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
Table 3 — Ranges of characters disallowed initially (combining characters)
0300-036F
1DC0-1DFF
20D0-20FF
FE20-FE2F
The identifiers in Table 4 have a special meaning when appearing in a certain context.
When referred to in the grammar, these identifiers are used explicitly rather than using the identifier grammar production.
Unless otherwise specified, any ambiguity as to whether a given identifier has a special meaning is resolved to interpret the token as a regular identifier.
Table 4 — Identifiers with special meaning
override
final
In addition, some identifiers are reserved for use by C++ implementations and shall not be used otherwise; no diagnostic is required.
  • Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use.
  • Each identifier that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
On systems in which linkers cannot accept extended characters, an encoding of the universal-character-name may be used in forming valid external identifiers.
For example, some otherwise unused character or sequence of characters may be used to encode the \u in a universal-character-name.
Extended characters may produce a long external identifier, but C++ does not place a translation limit on significant characters for external identifiers.
In C++, upper- and lower-case letters are considered different for all identifiers, including external identifiers.

5.11 Keywords [lex.key]

The identifiers shown in Table 5 are reserved for use as keywords (that is, they are unconditionally treated as keywords in phase 7) except in an attribute-token:
Table 5 — Keywords
alignas
continue
friend
register
true
alignof
decltype
goto
reinterpret_­cast
try
asm
default
if
return
typedef
auto
delete
inline
short
typeid
bool
do
int
signed
typename
break
double
long
sizeof
union
case
dynamic_­cast
mutable
static
unsigned
catch
else
namespace
static_­assert
using
char
enum
new
static_­cast
virtual
char16_­t
explicit
noexcept
struct
void
char32_­t
export
nullptr
switch
volatile
class
extern
operator
template
wchar_­t
const
false
private
this
while
constexpr
float
protected
thread_­local
const_­cast
for
public
throw
[Note
:
The export and register keywords are unused but are reserved for future use.
end note
]
Furthermore, the alternative representations shown in Table 6 for certain operators and punctuators ([lex.digraph]) are reserved and shall not be used otherwise:
Table 6 — Alternative representations
and
and_­eq
bitand
bitor
compl
not
not_­eq
or
or_­eq
xor
xor_­eq

5.12 Operators and punctuators [lex.operators]

The lexical representation of C++ programs includes a number of preprocessing tokens which are used in the syntax of the preprocessor or are converted into tokens for operators and punctuators:
preprocessing-op-or-punc: one of
	{ 	} 	[ 	] 	# 	## 	( 	)
	<: 	:> 	<% 	%> 	%: 	%:%: 	; 	: 	...
	new 	delete 	? 	:: 	. 	.*
	+ 	- 	* 	/ 	% 	^	& 	| 	~
	! 	= 	< 	> 	+= 	-= 	*= 	/= 	%=
	^= 	&= 	|= 	<< 	>> 	>>= 	<<= 	== 	!=
	<= 	>= 	&& 	|| 	++ 	-- 	, 	->* 	->
	and 	and_eq 	bitand 	bitor 	compl 	not 	not_eq
	or 	or_eq 	xor 	xor_eq
Each preprocessing-op-or-punc is converted to a single token in translation phase 7 ([lex.phases]).

5.13 Literals [lex.literal]

5.13.1 Kinds of literals [lex.literal.kinds]

The term “literal” generally designates, in this International Standard, those tokens that are called “constants” in ISO C.

5.13.2 Integer literals [lex.icon]

An integer literal is a sequence of digits that has no period or exponent part, with optional separating single quotes that are ignored when determining its value.
An integer literal may have a prefix that specifies its base and a suffix that specifies its type.
The lexically first digit of the sequence of digits is the most significant.
A binary integer literal (base two) begins with 0b or 0B and consists of a sequence of binary digits.
An octal integer literal (base eight) begins with the digit 0 and consists of a sequence of octal digits.23
A decimal integer literal (base ten) begins with a digit other than 0 and consists of a sequence of decimal digits.
A hexadecimal integer literal (base sixteen) begins with 0x or 0X and consists of a sequence of hexadecimal digits, which include the decimal digits and the letters a through f and A through F with decimal values ten through fifteen.
[Example
:
The number twelve can be written 12, 014, 0XC, or 0b1100.
The integer literals 1048576, 1'048'576, 0X100000, 0x10'0000, and 0'004'000'000 all have the same value.
end example
]
The type of an integer literal is the first of the corresponding list in Table 7 in which its value can be represented.
Table 7 — Types of integer literals
Suffix
Decimal literal
Binary, octal, or hexadecimal literal
none
int
int
long int
unsigned int
long long int
long int
unsigned long int
long long int
unsigned long long int
u or U
unsigned int
unsigned int
unsigned long int
unsigned long int
unsigned long long int
unsigned long long int
l or L
long int
long int
long long int
unsigned long int
long long int
unsigned long long int
Both u or U
unsigned long int
unsigned long int
and l or L
unsigned long long int
unsigned long long int
ll or LL
long long int
long long int
unsigned long long int
Both u or U
unsigned long long int
unsigned long long int
and ll or LL
If an integer literal cannot be represented by any type in its list and an extended integer type ([basic.fundamental]) can represent its value, it may have that extended integer type.
If all of the types in the list for the integer literal are signed, the extended integer type shall be signed.
If all of the types in the list for the integer literal are unsigned, the extended integer type shall be unsigned.
If the list contains both signed and unsigned types, the extended integer type may be signed or unsigned.
A program is ill-formed if one of its translation units contains an integer literal that cannot be represented by any of the allowed types.
The digits 8 and 9 are not octal digits.

5.13.3 Character literals [lex.ccon]

A character literal is one or more characters enclosed in single quotes, as in 'x', optionally preceded by u8, u, U, or L, as in u8'w', u'x', U'y', or L'z', respectively.
A character literal that does not begin with u8, u, U, or L is an ordinary character literal.
An ordinary character literal that contains a single c-char representable in the execution character set has type char, with value equal to the numerical value of the encoding of the c-char in the execution character set.
An ordinary character literal that contains more than one c-char is a multicharacter literal.
A multicharacter literal, or an ordinary character literal containing a single c-char not representable in the execution character set, is conditionally-supported, has type int, and has an implementation-defined value.
A character literal that begins with u8, such as u8'w', is a character literal of type char, known as a UTF-8 character literal.
The value of a UTF-8 character literal is equal to its ISO 10646 code point value, provided that the code point value is representable with a single UTF-8 code unit (that is, provided it is in the C0 Controls and Basic Latin Unicode block).
If the value is not representable with a single UTF-8 code unit, the program is ill-formed.
A UTF-8 character literal containing multiple c-chars is ill-formed.
A character literal that begins with the letter u, such as u'x', is a character literal of type char16_­t.
The value of a char16_­t character literal containing a single c-char is equal to its ISO 10646 code point value, provided that the code point is representable with a single 16-bit code unit.
(That is, provided it is a basic multi-lingual plane code point.)
If the value is not representable within 16 bits, the program is ill-formed.
A char16_­t character literal containing multiple c-chars is ill-formed.
A character literal that begins with the letter U, such as U'y', is a character literal of type char32_­t.
The value of a char32_­t character literal containing a single c-char is equal to its ISO 10646 code point value.
A char32_­t character literal containing multiple c-chars is ill-formed.
A character literal that begins with the letter L, such as L'z', is a wide-character literal.
A wide-character literal has type wchar_­t.24
The value of a wide-character literal containing a single c-char has value equal to the numerical value of the encoding of the c-char in the execution wide-character set, unless the c-char has no representation in the execution wide-character set, in which case the value is implementation-defined.
[Note
:
The type wchar_­t is able to represent all members of the execution wide-character set (see [basic.fundamental]).
end note
]
The value of a wide-character literal containing multiple c-chars is implementation-defined.
Certain non-graphic characters, the single quote ', the double quote ", the question mark ?,25 and the backslash \, can be represented according to Table 8.
The double quote " and the question mark ?, can be represented as themselves or by the escape sequences \" and \? respectively, but the single quote ' and the backslash \ shall be represented by the escape sequences \' and \\ respectively.
Escape sequences in which the character following the backslash is not listed in Table 8 are conditionally-supported, with implementation-defined semantics.
An escape sequence specifies a single character.
Table 8 — Escape sequences
new-line
NL(LF)
\n
horizontal tab
HT
\t
vertical tab
VT
\v
backspace
BS
\b
carriage return
CR
\r
form feed
FF
\f
alert
BEL
\a
backslash
\
\\
question mark
?
\?
single quote
'
\'
double quote
"
\"
octal number
ooo
\ooo
hex number
hhh
\xhhh
The escape \ooo consists of the backslash followed by one, two, or three octal digits that are taken to specify the value of the desired character.
The escape \xhhh consists of the backslash followed by x followed by one or more hexadecimal digits that are taken to specify the value of the desired character.
There is no limit to the number of digits in a hexadecimal sequence.
A sequence of octal or hexadecimal digits is terminated by the first character that is not an octal digit or a hexadecimal digit, respectively.
The value of a character literal is implementation-defined if it falls outside of the implementation-defined range defined for char (for character literals with no prefix) or wchar_­t (for character literals prefixed by L).
[Note
:
If the value of a character literal prefixed by u, u8, or U is outside the range defined for its type, the program is ill-formed.
end note
]
A universal-character-name is translated to the encoding, in the appropriate execution character set, of the character named.
If there is no such encoding, the universal-character-name is translated to an implementation-defined encoding.
[Note
:
In translation phase 1, a universal-character-name is introduced whenever an actual extended character is encountered in the source text.
Therefore, all extended characters are described in terms of universal-character-names.
However, the actual compiler implementation may use its own native character set, so long as the same results are obtained.
end note
]
They are intended for character sets where a character does not fit into a single byte.
Using an escape sequence for a question mark is supported for compatibility with ISO C++ 2014 and ISO C.

5.13.4 Floating literals [lex.fcon]

A floating literal consists of an optional prefix specifying a base, an integer part, a radix point, a fraction part, an e, E, p or P, an optionally signed integer exponent, and an optional type suffix.
The integer and fraction parts both consist of a sequence of decimal (base ten) digits if there is no prefix, or hexadecimal (base sixteen) digits if the prefix is 0x or 0X.
The floating literal is a decimal floating literal in the former case and a hexadecimal floating literal in the latter case.
Optional separating single quotes in a digit-sequence or hexadecimal-digit-sequence are ignored when determining its value.
[Example
:
The floating literals 1.602'176'565e-19 and 1.602176565e-19 have the same value.
end example
]
Either the integer part or the fraction part (not both) can be omitted.
Either the radix point or the letter e or E and the exponent (not both) can be omitted from a decimal floating literal.
The radix point (but not the exponent) can be omitted from a hexadecimal floating literal.
The integer part, the optional radix point, and the optional fraction part, form the significand of the floating literal.
In a decimal floating literal, the exponent, if present, indicates the power of 10 by which the significand is to be scaled.
In a hexadecimal floating literal, the exponent indicates the power of 2 by which the significand is to be scaled.
[Example
:
The floating literals 49.625 and 0xC.68p+2 have the same value.
end example
]
If the scaled value is in the range of representable values for its type, the result is the scaled value if representable, else the larger or smaller representable value nearest the scaled value, chosen in an implementation-defined manner.
The type of a floating literal is double unless explicitly specified by a suffix.
The suffixes f and F specify float, the suffixes l and L specify long double.
If the scaled value is not in the range of representable values for its type, the program is ill-formed.

5.13.5 String literals [lex.string]

string-literal:
	encoding-prefix " s-char-sequence "
	encoding-prefix R raw-string
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-sequence ( r-char-sequence ) d-char-sequence "
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.
A string-literal is a sequence of characters (as defined in [lex.ccon]) surrounded by double quotes, optionally prefixed by R, u8, u8R, u, uR, U, UR, L, or LR, as in "...", R"(...)", u8"...", u8R"**(...)**", u"...", uR"*~(...)*~", U"...", UR"zzz(...)zzz", L"...", or LR"(...)", respectively.
A string-literal that has an R in the prefix is a raw string literal.
The d-char-sequence serves as a delimiter.
The terminating d-char-sequence of a raw-string is the same sequence of characters as the initial d-char-sequence.
A d-char-sequence shall consist of at most 16 characters.
[Note
:
The characters '(' and ')' are permitted in a raw-string.
Thus, R"delimiter((a|b))delimiter" is equivalent to "(a|b)".
end note
]
[Note
:
A source-file new-line in a raw string literal results in a new-line in the resulting execution string literal.
Assuming no whitespace at the beginning of lines in the following example, the assert will succeed:
const char* p = R"(a\
b
c)";
assert(std::strcmp(p, "a\\\nb\nc") == 0);
end note
]
[Example
:
The raw string
R"a(
)\
a"
)a"
is equivalent to "\n)\\\na\"\n".
The raw string
R"(??)"
is equivalent to "\?\?".
The raw string
R"#(
)??="
)#"
is equivalent to "\n)\?\?=\"\n".
end example
]
After translation phase 6, a string-literal that does not begin with an encoding-prefix is an ordinary string literal, and is initialized with the given characters.
A string-literal that begins with u8, such as u8"asdf", is a UTF-8 string literal.
Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals.
A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration ([basic.stc]).
For a UTF-8 string literal, each successive element of the object representation ([basic.types]) has the value of the corresponding code unit of the UTF-8 encoding of the string.
A string-literal that begins with u, such as u"asdf", is a char16_­t string literal.
A char16_­t string literal has type “array of n const char16_­t”, where n is the size of the string as defined below; it is initialized with the given characters.
A single c-char may produce more than one char16_­t character in the form of surrogate pairs.
A string-literal that begins with U, such as U"asdf", is a char32_­t string literal.
A char32_­t string literal has type “array of n const char32_­t”, where n is the size of the string as defined below; it is initialized with the given characters.
A string-literal that begins with L, such as L"asdf", is a wide string literal.
A wide string literal has type “array of n const wchar_­t”, where n is the size of the string as defined below; it is initialized with the given characters.
In translation phase 6 ([lex.phases]), adjacent string-literals are concatenated.
If both string-literals have the same encoding-prefix, the resulting concatenated string literal has that encoding-prefix.
If one string-literal has no encoding-prefix, it is treated as a string-literal of the same encoding-prefix as the other operand.
If a UTF-8 string literal token is adjacent to a wide string literal token, the program is ill-formed.
Any other concatenations are conditionally-supported with implementation-defined behavior.
[Note
:
This concatenation is an interpretation, not a conversion.
Because the interpretation happens in translation phase 6 (after each character from a string literal has been translated into a value from the appropriate character set), a string-literal's initial rawness has no effect on the interpretation or well-formedness of the concatenation.
end note
]
Table 9 has some examples of valid concatenations.
Table 9 — String literal concatenations
Source
Means
Source
Means
Source
Means
u"a"
u"b"
u"ab"
U"a"
U"b"
U"ab"
L"a"
L"b"
L"ab"
u"a"
"b"
u"ab"
U"a"
"b"
U"ab"
L"a"
"b"
L"ab"
"a"
u"b"
u"ab"
"a"
U"b"
U"ab"
"a"
L"b"
L"ab"
Characters in concatenated strings are kept distinct.
[Example
:
"\xA" "B"
contains the two characters '\xA' and 'B' after concatenation (and not the single hexadecimal character '\xAB').
end example
]
After any necessary concatenation, in translation phase 7 ([lex.phases]), '\0' is appended to every string literal so that programs that scan a string can find its end.
Escape sequences and universal-character-names in non-raw string literals have the same meaning as in character literals ([lex.ccon]), except that the single quote ' is representable either by itself or by the escape sequence \', and the double quote " shall be preceded by a \, and except that a universal-character-name in a char16_­t string literal may yield a surrogate pair.
In a narrow string literal, a universal-character-name may map to more than one char element due to multibyte encoding.
The size of a char32_­t or wide string literal is the total number of escape sequences, universal-character-names, and other characters, plus one for the terminating U'\0' or L'\0'.
The size of a char16_­t string literal is the total number of escape sequences, universal-character-names, and other characters, plus one for each character requiring a surrogate pair, plus one for the terminating u'\0'.
[Note
:
The size of a char16_­t string literal is the number of code units, not the number of characters.
end note
]
Within char32_­t and char16_­t string literals, any universal-character-names shall be within the range 0x0 to 0x10FFFF.
The size of a narrow string literal is the total number of escape sequences and other characters, plus at least one for the multibyte encoding of each universal-character-name, plus one for the terminating '\0'.
Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above.
Whether all string literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified.
[Note
:
The effect of attempting to modify a string literal is undefined.
end note
]

5.13.6 Boolean literals [lex.bool]

boolean-literal:
	false
	true
The Boolean literals are the keywords false and true.
Such literals are prvalues and have type bool.

5.13.7 Pointer literals [lex.nullptr]

The pointer literal is the keyword nullptr.
It is a prvalue of type std​::​nullptr_­t.
[Note
:
std​::​nullptr_­t is a distinct type that is neither a pointer type nor a pointer to member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value.
end note
]

5.13.8 User-defined literals [lex.ext]

If a token matches both user-defined-literal and another literal kind, it is treated as the latter.
[Example
:
123_­km is a user-defined-literal, but 12LL is an integer-literal.
end example
]
The syntactic non-terminal preceding the ud-suffix in a user-defined-literal is taken to be the longest sequence of characters that could match that non-terminal.
A user-defined-literal is treated as a call to a literal operator or literal operator template ([over.literal]).
To determine the form of this call for a given user-defined-literal L with ud-suffix X, the literal-operator-id whose literal suffix identifier is X is looked up in the context of L using the rules for unqualified name lookup ([basic.lookup.unqual]).
Let S be the set of declarations found by this lookup.
S shall not be empty.
If L is a user-defined-integer-literal, let n be the literal without its ud-suffix.
If S contains a literal operator with parameter type unsigned long long, the literal L is treated as a call of the form
operator "" X(nULL)
Otherwise, S shall contain a raw literal operator or a literal operator template ([over.literal]) but not both.
If S contains a raw literal operator, the literal L is treated as a call of the form
operator "" X("n")
Otherwise (S contains a literal operator template), L is treated as a call of the form
operator "" X<'', '', ... ''>()
where n is the source character sequence .
[Note
:
The sequence can only contain characters from the basic source character set.
end note
]
If L is a user-defined-floating-literal, let f be the literal without its ud-suffix.
If S contains a literal operator with parameter type long double, the literal L is treated as a call of the form
operator "" X(fL)
Otherwise, S shall contain a raw literal operator or a literal operator template ([over.literal]) but not both.
If S contains a raw literal operator, the literal L is treated as a call of the form
operator "" X("f")
Otherwise (S contains a literal operator template), L is treated as a call of the form
operator "" X<'', '', ... ''>()
where f is the source character sequence .
[Note
:
The sequence can only contain characters from the basic source character set.
end note
]
If L is a user-defined-string-literal, let str be the literal without its ud-suffix and let len be the number of code units in str (i.e., its length excluding the terminating null character). The literal L is treated as a call of the form
operator "" X(str, len)
If L is a user-defined-character-literal, let ch be the literal without its ud-suffix.
S shall contain a literal operator ([over.literal]) whose only parameter has the type of ch and the literal L is treated as a call of the form
operator "" X(ch)
[Example
:
long double operator "" _w(long double);
std::string operator "" _w(const char16_t*, std::size_t);
unsigned operator "" _w(const char*);
int main() {
  1.2_w;      // calls operator "" _­w(1.2L)
  u"one"_w;   // calls operator "" _­w(u"one", 3)
  12_w;       // calls operator "" _­w("12")
  "two"_w;    // error: no applicable literal operator
}
end example
]
In translation phase 6 ([lex.phases]), adjacent string literals are concatenated and user-defined-string-literals are considered string literals for that purpose.
During concatenation, ud-suffixes are removed and ignored and the concatenation process occurs as described in [lex.string].
At the end of phase 6, if a string literal is the result of a concatenation involving at least one user-defined-string-literal, all the participating user-defined-string-literals shall have the same ud-suffix and that suffix is applied to the result of the concatenation.
[Example
:
int main() {
  L"A" "B" "C"_x; // OK: same as L"ABC"_­x
  "P"_x "Q" "R"_y;// error: two different ud-suffixes
}
end example
]

6 Basic concepts [basic]

[Note
:
This Clause presents the basic concepts of the C++ language.
It explains the difference between an object and a name and how they relate to the value categories for expressions.
It introduces the concepts of a declaration and a definition and presents C++'s notion of type, scope, linkage, and storage duration.
The mechanisms for starting and terminating a program are discussed.
Finally, this Clause presents the fundamental types of the language and lists the ways of constructing compound types from these.
end note
]
[Note
:
This Clause does not cover concepts that affect only a single part of the language.
Such concepts are discussed in the relevant Clauses.
end note
]
An entity is a value, object, reference, function, enumerator, type, class member, bit-field, template, template specialization, namespace, or parameter pack.
Every name that denotes an entity is introduced by a declaration.
Every name that denotes a label is introduced either by a goto statement ([stmt.goto]) or a labeled-statement.
A variable is introduced by the declaration of a reference other than a non-static data member or of an object.
The variable's name, if any, denotes the reference or object.
Some names denote types or templates.
In general, whenever a name is encountered it is necessary to determine whether that name denotes one of these entities before continuing to parse the program that contains it.
The process that determines this is called name lookup ([basic.lookup]).
Two names are the same if
A name used in more than one translation unit can potentially refer to the same entity in these translation units depending on the linkage ([basic.link]) of the name specified in each translation unit.

6.1 Declarations and definitions [basic.def]

A declaration (Clause [dcl.dcl]) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.
If so, the declaration specifies the interpretation and attributes of these names.
A declaration may also have effects including:
A declaration is a definition unless
[Example
:
All but one of the following are definitions:
int a;                          // defines a
extern const int c = 1;         // defines c
int f(int x) { return x+a; }    // defines f and defines x
struct S { int a; int b; };     // defines S, S​::​a, and S​::​b
struct X {                      // defines X
  int x;                        // defines non-static data member x
  static int y;                 // declares static data member y
  X(): x(0) { }                 // defines a constructor of X
};
int X::y = 1;                   // defines X​::​y
enum { up, down };              // defines up and down
namespace N { int d; }          // defines N and N​::​d
namespace N1 = N;               // defines N1
X anX;                          // defines anX
whereas these are just declarations:
extern int a;                   // declares a
extern const int c;             // declares c
int f(int);                     // declares f
struct S;                       // declares S
typedef int Int;                // declares Int
extern X anotherX;              // declares anotherX
using N::d;                     // declares d
end example
]
[Note
:
In some circumstances, C++ implementations implicitly define the default constructor ([class.ctor]), copy constructor ([class.copy]), move constructor ([class.copy]), copy assignment operator ([class.copy]), move assignment operator ([class.copy]), or destructor ([class.dtor]) member functions.
end note
]
[Example
:
Given
#include <string>

struct C {
  std::string s;              // std​::​string is the standard library class (Clause [strings])
};

int main() {
  C a;
  C b = a;
  b = a;
}
the implementation will implicitly define functions to make the definition of C equivalent to
struct C {
  std::string s;
  C() : s() { }
  C(const C& x): s(x.s) { }
  C(C&& x): s(static_cast<std::string&&>(x.s)) { }
    // : s(std​::​move(x.s)) { }
  C& operator=(const C& x) { s = x.s; return *this; }
  C& operator=(C&& x) { s = static_cast<std::string&&>(x.s); return *this; }
    // { s = std​::​move(x.s); return *this; }
  ~C() { }
};
end example
]
[Note
:
A class name can also be implicitly declared by an elaborated-type-specifier ([dcl.type.elab]).
end note
]
A program is ill-formed if the definition of any object gives the object an incomplete type ([basic.types]).
Appearing inside the braced-enclosed declaration-seq in a linkage-specification does not affect whether a declaration is a definition.

6.2 One-definition rule [basic.def.odr]

No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template.
An expression is potentially evaluated unless it is an unevaluated operand (Clause [expr]) or a subexpression thereof.
The set of potential results of an expression e is defined as follows:
  • If e is an id-expression, the set contains only e.
  • If e is a subscripting operation ([expr.sub]) with an array operand, the set contains the potential results of that operand.
  • If e is a class member access expression ([expr.ref]), the set contains the potential results of the object expression.
  • If e is a pointer-to-member expression ([expr.mptr.oper]) whose second operand is a constant expression, the set contains the potential results of the object expression.
  • If e has the form (e1), the set contains the potential results of e1.
  • If e is a glvalue conditional expression ([expr.cond]), the set is the union of the sets of potential results of the second and third operands.
  • If e is a comma expression ([expr.comma]), the set contains the potential results of the right operand.
  • Otherwise, the set is empty.
[Note
:
This set is a (possibly-empty) set of id-expressions, each of which is either e or a subexpression of e.
[Example
:
In the following example, the set of potential results of the initializer of n contains the first S​::​x subexpression, but not the second S​::​x subexpression.
struct S { static const int x = 0; };
const int &f(const int &r);
int n = b ? (1, S::x)  // S​::​x is not odr-used here
          : f(S::x);   // S​::​x is odr-used here, so a definition is required
end example
]
end note
]
A variable x whose name appears as a potentially-evaluated expression ex is odr-used by ex unless applying the lvalue-to-rvalue conversion ([conv.lval]) to x yields a constant expression ([expr.const]) that does not invoke any non-trivial functions and, if x is an object, ex is an element of the set of potential results of an expression e, where either the lvalue-to-rvalue conversion ([conv.lval]) is applied to e, or e is a discarded-value expression (Clause [expr]).
this is odr-used if it appears as a potentially-evaluated expression (including as the result of the implicit transformation in the body of a non-static member function ([class.mfct.non-static])).
A virtual member function is odr-used if it is not pure.
A function whose name appears as a potentially-evaluated expression is odr-used if it is the unique lookup result or the selected member of a set of overloaded functions ([basic.lookup], [over.match], [over.over]), unless it is a pure virtual function and either its name is not explicitly qualified or the expression forms a pointer to member ([expr.unary.op]).
[Note
:
This covers calls to named functions ([expr.call]), operator overloading (Clause [over]), user-defined conversions ([class.conv.fct]), allocation functions for placement new-expressions ([expr.new]), as well as non-default initialization ([dcl.init]).
A constructor selected to copy or move an object of class type is odr-used even if the call is actually elided by the implementation ([class.copy]).
end note
]
An allocation or deallocation function for a class is odr-used by a new-expression appearing in a potentially-evaluated expression as specified in [expr.new] and [class.free].
A deallocation function for a class is odr-used by a delete expression appearing in a potentially-evaluated expression as specified in [expr.delete] and [class.free].
A non-placement allocation or deallocation function for a class is odr-used by the definition of a constructor of that class.
A non-placement deallocation function for a class is odr-used by the definition of the destructor of that class, or by being selected by the lookup at the point of definition of a virtual destructor ([class.dtor]).27
An assignment operator function in a class is odr-used by an implicitly-defined copy-assignment or move-assignment function for another class as specified in [class.copy].
A constructor for a class is odr-used as specified in [dcl.init].
A destructor for a class is odr-used if it is potentially invoked ([class.dtor]).
Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program outside of a discarded statement ([stmt.if]); no diagnostic required.
The definition can appear explicitly in the program, it can be found in the standard or a user-defined library, or (when appropriate) it is implicitly defined (see [class.ctor], [class.dtor] and [class.copy]).
An inline function or variable shall be defined in every translation unit in which it is odr-used outside of a discarded statement.
Exactly one definition of a class is required in a translation unit if the class is used in a way that requires the class type to be complete.
[Example
:
The following complete translation unit is well-formed, even though it never defines X:
struct X;                       // declare X as a struct type
struct X* x1;                   // use X in pointer formation
X* x2;                          // use X in pointer formation
end example
]
[Note
:
The rules for declarations and expressions describe in which contexts complete class types are required.
A class type T must be complete if:
end note
]
There can be more than one definition of a class type (Clause [class]), enumeration type ([dcl.enum]), inline function with external linkage ([dcl.inline]), inline variable with external linkage ([dcl.inline]), class template (Clause [temp]), non-static function template ([temp.fct]), static data member of a class template ([temp.static]), member function of a class template ([temp.mem.func]), or template specialization for which some template parameters are not specified ([temp.spec], [temp.class.spec]) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements.
Given such an entity named D defined in more than one translation unit, then
  • each definition of D shall consist of the same sequence of tokens; and
  • in each definition of D, corresponding names, looked up according to [basic.lookup], shall refer to an entity defined within the definition of D, or shall refer to the same entity, after overload resolution ([over.match]) and after matching of partial template specialization ([temp.over]), except that a name can refer to
    • a non-volatile const object with internal or no linkage if the object or
    • a reference with internal or no linkage initialized with a constant expression such that the reference refers to the same entity in all definitions of D;
    and
  • in each definition of D, corresponding entities shall have the same language linkage; and
  • in each definition of D, the overloaded operators referred to, the implicit calls to conversion functions, constructors, operator new functions and operator delete functions, shall refer to the same function, or to a function defined within the definition of D; and
  • in each definition of D, a default argument used by an (implicit or explicit) function call is treated as if its token sequence were present in the definition of D; that is, the default argument is subject to the requirements described in this paragraph (and, if the default argument has subexpressions with default arguments, this requirement applies recursively).28
  • if D is a class with an implicitly-declared constructor ([class.ctor]), it is as if the constructor was implicitly defined in every translation unit where it is odr-used, and the implicit definition in every translation unit shall call the same constructor for a subobject of D.
    [Example
    :
    // translation unit 1:
    struct X {
      X(int, int);
      X(int, int, int);
    };
    X::X(int, int = 0) { }
    class D {
      X x = 0;
    };
    D d1;                           // X(int, int) called by D()
    
    // translation unit 2:
    struct X {
      X(int, int);
      X(int, int, int);
    };
    X::X(int, int = 0, int = 0) { }
    class D {
      X x = 0;
    };
    D d2;                           // X(int, int, int) called by D();
                                    // D()'s implicit definition violates the ODR
    
    end example
    ]
If D is a template and is defined in more than one translation unit, then the preceding requirements shall apply both to names from the template's enclosing scope used in the template definition ([temp.nondep]), and also to dependent names at the point of instantiation ([temp.dep]).
If the definitions of D satisfy all these requirements, then the behavior is as if there were a single definition of D.
If the definitions of D do not satisfy these requirements, then the behavior is undefined.
An implementation is not required to call allocation and deallocation functions from constructors or destructors; however, this is a permissible implementation technique.
[dcl.fct.default] describes how default argument names are looked up.

6.3 Scope [basic.scope]

6.3.1 Declarative regions and scopes [basic.scope.declarative]

Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the same entity.
In general, each particular name is valid only within some possibly discontiguous portion of program text called its scope.
To determine the scope of a declaration, it is sometimes convenient to refer to the potential scope of a declaration.
The scope of a declaration is the same as its potential scope unless the potential scope contains another declaration of the same name.
In that case, the potential scope of the declaration in the inner (contained) declarative region is excluded from the scope of the declaration in the outer (containing) declarative region.
[Example
:
In
int j = 24;
int main() {
  int i = j, j;
  j = 42;
}
the identifier j is declared twice as a name (and used twice).
The declarative region of the first j includes the entire example.
The potential scope of the first j begins immediately after that j and extends to the end of the program, but its (actual) scope excludes the text between the , and the }.
The declarative region of the second declaration of j (the j immediately before the semicolon) includes all the text between { and }, but its potential scope excludes the declaration of i.
The scope of the second declaration of j is the same as its potential scope.
end example
]
The names declared by a declaration are introduced into the scope in which the declaration occurs, except that the presence of a friend specifier ([class.friend]), certain uses of the elaborated-type-specifier, and using-directives alter this general behavior.
Given a set of declarations in a single declarative region, each of which specifies the same unqualified name,
  • they shall all refer to the same entity, or all refer to functions and function templates; or
  • exactly one declaration shall declare a class name or enumeration name that is not a typedef name and the other declarations shall all refer to the same variable, non-static data member, or enumerator, or all refer to functions and function templates; in this case the class name or enumeration name is hidden ([basic.scope.hiding]).
    [Note
    :
    A namespace name or a class template name must be unique in its declarative region ([namespace.alias], Clause [temp]).
    end note
    ]
[Note
:
These restrictions apply to the declarative region into which a name is introduced, which is not necessarily the same as the region in which the declaration occurs.
In particular, elaborated-type-specifiers ([dcl.type.elab]) and friend declarations ([class.friend]) may introduce a (possibly not visible) name into an enclosing namespace; these restrictions apply to that region.
Local extern declarations ([basic.link]) may introduce a name into the declarative region where the declaration appears and also introduce a (possibly not visible) name into an enclosing namespace; these restrictions apply to both regions.
end note
]
[Note
:
The name lookup rules are summarized in [basic.lookup].
end note
]

6.3.2 Point of declaration [basic.scope.pdecl]

The point of declaration for a name is immediately after its complete declarator (Clause [dcl.decl]) and before its initializer (if any), except as noted below.
[Example
:
unsigned char x = 12;
{ unsigned char x = x; }
Here the second x is initialized with its own (indeterminate) value.
end example
]
[Note
:
a name from an outer scope remains visible up to the point of declaration of the name that hides it.
[Example
:
const int  i = 2;
{ int  i[i]; }
declares a block-scope array of two integers.
end example
]
end note
]
The point of declaration for a class or class template first declared by a class-specifier is immediately after the identifier or simple-template-id (if any) in its class-head.
The point of declaration for an enumeration is immediately after the identifier (if any) in either its enum-specifier or its first opaque-enum-declaration, whichever comes first.
The point of declaration of an alias or alias template immediately follows the type-id to which the alias refers.
The point of declaration of a using-declarator that does not name a constructor is immediately after the using-declarator.
The point of declaration for an enumerator is immediately after its enumerator-definition.
[Example
:
const int x = 12;
{ enum { x = x }; }
Here, the enumerator x is initialized with the value of the constant x, namely 12.
end example
]
After the point of declaration of a class member, the member name can be looked up in the scope of its class.
[Note
:
This is true even if the class is an incomplete class.
For example,
struct X {
  enum E { z = 16 };
  int b[X::z];      // OK
};
end note
]
The point of declaration of a class first declared in an elaborated-type-specifier is as follows:
The point of declaration for an injected-class-name (Clause [class]) is immediately following the opening brace of the class definition.
The point of declaration for a function-local predefined variable ([dcl.fct.def]) is immediately before the function-body of a function definition.
The point of declaration for a template parameter is immediately after its complete template-parameter.
[Example
:
typedef unsigned char T;
template<class T
  = T     // lookup finds the typedef name of unsigned char
  , T     // lookup finds the template parameter
    N = 0> struct A { };
end example
]
[Note
:
Friend declarations refer to functions or classes that are members of the nearest enclosing namespace, but they do not introduce new names into that namespace ([namespace.memdef]).
Function declarations at block scope and variable declarations with the extern specifier at block scope refer to declarations that are members of an enclosing namespace, but they do not introduce new names into that scope.
end note
]
[Note
:
For point of instantiation of a template, see [temp.point].
end note
]

6.3.3 Block scope [basic.scope.block]

A name declared in a block ([stmt.block]) is local to that block; it has block scope.
Its potential scope begins at its point of declaration ([basic.scope.pdecl]) and ends at the end of its block.
A variable declared at block scope is a local variable.
The potential scope of a function parameter name (including one appearing in a lambda-declarator) or of a function-local predefined variable in a function definition ([dcl.fct.def]) begins at its point of declaration.
If the function has a function-try-block the potential scope of a parameter or of a function-local predefined variable ends at the end of the last associated handler, otherwise it ends at the end of the outermost block of the function definition.
A parameter name shall not be redeclared in the outermost block of the function definition nor in the outermost block of any handler associated with a function-try-block.
The name declared in an exception-declaration is local to the handler and shall not be redeclared in the outermost block of the handler.
Names declared in the init-statement, the for-range-declaration, and in the condition of if, while, for, and switch statements are local to the if, while, for, or switch statement (including the controlled statement), and shall not be redeclared in a subsequent condition of that statement nor in the outermost block (or, for the if statement, any of the outermost blocks) of the controlled statement; see [stmt.select].

6.3.4 Function prototype scope [basic.scope.proto]

In a function declaration, or in any function declarator except the declarator of a function definition ([dcl.fct.def]), names of parameters (if supplied) have function prototype scope, which terminates at the end of the nearest enclosing function declarator.

6.3.5 Function scope [basic.funscope]

Labels ([stmt.label]) have function scope and may be used anywhere in the function in which they are declared.
Only labels have function scope.

6.3.6 Namespace scope [basic.scope.namespace]

The declarative region of a namespace-definition is its namespace-body.
Entities declared in a namespace-body are said to be members of the namespace, and names introduced by these declarations into the declarative region of the namespace are said to be member names of the namespace.
A namespace member name has namespace scope.
Its potential scope includes its namespace from the name's point of declaration ([basic.scope.pdecl]) onwards; and for each using-directive that nominates the member's namespace, the member's potential scope includes that portion of the potential scope of the using-directive that follows the member's point of declaration.
[Example
:
namespace N {
  int i;
  int g(int a) { return a; }
  int j();
  void q();
}
namespace { int l=1; }
// the potential scope of l is from its point of declaration to the end of the translation unit

namespace N {
  int g(char a) {   // overloads N​::​g(int)
    return l+a;     // l is from unnamed namespace
  }

  int i;            // error: duplicate definition
  int j();          // OK: duplicate function declaration

  int j() {         // OK: definition of N​::​j()
    return g(i);    // calls N​::​g(int)
  }
  int q();          // error: different return type
}
end example
]
A namespace member can also be referred to after the ​::​ scope resolution operator ([expr.prim]) applied to the name of its namespace or the name of a namespace which nominates the member's namespace in a using-directive; see [namespace.qual].
The outermost declarative region of a translation unit is also a namespace, called the global namespace.
A name declared in the global namespace has global namespace scope (also called global scope).
The potential scope of such a name begins at its point of declaration ([basic.scope.pdecl]) and ends at the end of the translation unit that is its declarative region.
A name with global namespace scope is said to be a global name.

6.3.7 Class scope [basic.scope.class]

The potential scope of a name declared in a class consists not only of the declarative region following the name's point of declaration, but also of all function bodies, default arguments, noexcept-specifiers, and brace-or-equal-initializers of non-static data members in that class (including such things in nested classes).
A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S.
No diagnostic is required for a violation of this rule.
A name declared within a member function hides a declaration of the same name whose scope extends to or past the end of the member function's class.
The potential scope of a declaration that extends to or past the end of a class definition also extends to the regions defined by its member definitions, even if the members are defined lexically outside the class (this includes static data member definitions, nested class definitions, and member function definitions, including the member function body and any portion of the declarator part of such definitions which follows the declarator-id, including a parameter-declaration-clause and any default arguments ([dcl.fct.default])).
[Example
:
typedef int  c;
enum { i = 1 };

class X {
  char  v[i];                       // error: i refers to ​::​i but when reevaluated is X​::​i
  int  f() { return sizeof(c); }    // OK: X​::​c
  char  c;
  enum { i = 2 };
};

typedef char*  T;
struct Y {
  T  a;                             // error: T refers to ​::​T but when reevaluated is Y​::​T
  typedef long  T;
  T  b;
};

typedef int I;
class D {
  typedef I I;                      // error, even though no reordering involved
};
end example
]
The name of a class member shall only be used as follows:
  • in the scope of its class (as described above) or a class derived (Clause [class.derived]) from its class,
  • after the . operator applied to an expression of the type of its class ([expr.ref]) or a class derived from its class,
  • after the -> operator applied to a pointer to an object of its class ([expr.ref]) or a class derived from its class,
  • after the ​::​ scope resolution operator ([expr.prim]) applied to the name of its class or a class derived from its class.

6.3.8 Enumeration scope [basic.scope.enum]

The name of a scoped enumerator ([dcl.enum]) has enumeration scope.
Its potential scope begins at its point of declaration and terminates at the end of the enum-specifier.

6.3.9 Template parameter scope [basic.scope.temp]

The declarative region of the name of a template parameter of a template template-parameter is the smallest template-parameter-list in which the name was introduced.
The declarative region of the name of a template parameter of a template is the smallest template-declaration in which the name was introduced.
Only template parameter names belong to this declarative region; any other kind of name introduced by the declaration of a template-declaration is instead introduced into the same declarative region where it would be introduced as a result of a non-template declaration of the same name.
[Example
:
namespace N {
  template<class T> struct A { };               // #1
  template<class U> void f(U) { }               // #2
  struct B {
    template<class V> friend int g(struct C*);  // #3
  };
}
The declarative regions of T, U and V are the template-declarations on lines #1, #2, and #3, respectively.
But the names A, f, g and C all belong to the same declarative region — namely, the namespace-body of N.
(g is still considered to belong to this declarative region in spite of its being hidden during qualified and unqualified name lookup.)
end example
]
The potential scope of a template parameter name begins at its point of declaration ([basic.scope.pdecl]) and ends at the end of its declarative region.
[Note
:
This implies that a template-parameter can be used in the declaration of subsequent template-parameters and their default arguments but cannot be used in preceding template-parameters or their default arguments.
For example,
template<class T, T* p, class U = T> class X { /* ... */ };
template<class T> void f(T* p = new T);
This also implies that a template-parameter can be used in the specification of base classes.
For example,
template<class T> class X : public Array<T> { /* ... */ };
template<class T> class Y : public T { /* ... */ };
The use of a template parameter as a base class implies that a class used as a template argument must be defined and not just declared when the class template is instantiated.
end note
]
The declarative region of the name of a template parameter is nested within the immediately-enclosing declarative region.
[Note
:
As a result, a template-parameter hides any entity with the same name in an enclosing scope ([basic.scope.hiding]).
[Example
:
typedef int N;
template<N X, typename N, template<N Y> class T> struct A;
Here, X is a non-type template parameter of type int and Y is a non-type template parameter of the same type as the second template parameter of A.
end example
]
end note
]
[Note
:
Because the name of a template parameter cannot be redeclared within its potential scope ([temp.local]), a template parameter's scope is often its potential scope.
However, it is still possible for a template parameter name to be hidden; see [temp.local].
end note
]

6.3.10 Name hiding [basic.scope.hiding]

A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class ([class.member.lookup]).
A class name ([class.name]) or enumeration name ([dcl.enum]) can be hidden by the name of a variable, data member, function, or enumerator declared in the same scope.
If a class or enumeration name and a variable, data member, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the variable, data member, function, or enumerator name is visible.
In a member function definition, the declaration of a name at block scope hides the declaration of a member of the class with the same name; see [basic.scope.class].
The declaration of a member in a derived class (Clause [class.derived]) hides the declaration of a member of a base class of the same name; see [class.member.lookup].
During the lookup of a name qualified by a namespace name, declarations that would otherwise be made visible by a using-directive can be hidden by declarations with the same name in the namespace containing the using-directive; see [namespace.qual].
If a name is in scope and is not hidden it is said to be visible.

6.4 Name lookup [basic.lookup]

The name lookup rules apply uniformly to all names (including typedef-names, namespace-names ([basic.namespace]), and class-names ([class.name])) wherever the grammar allows such names in the context discussed by a particular rule.
Name lookup associates the use of a name with a set of declarations ([basic.def]) of that name.
The declarations found by name lookup shall either all declare the same entity or shall all declare functions; in the latter case, the declarations are said to form a set of overloaded functions ([over.load]).
Overload resolution ([over.match]) takes place after name lookup has succeeded.
The access rules (Clause [class.access]) are considered only once name lookup and function overload resolution (if applicable) have succeeded.
Only after name lookup, function overload resolution (if applicable) and access checking have succeeded are the attributes introduced by the name's declaration used further in expression processing (Clause [expr]).
A name “looked up in the context of an expression” is looked up as an unqualified name in the scope where the expression is found.
The injected-class-name of a class (Clause [class]) is also considered to be a member of that class for the purposes of name hiding and lookup.
[Note
:
[basic.link] discusses linkage issues.
The notions of scope, point of declaration and name hiding are discussed in [basic.scope].
end note
]

6.4.1 Unqualified name lookup [basic.lookup.unqual]

In all the cases listed in [basic.lookup.unqual], the scopes are searched for a declaration in the order listed in each of the respective categories; name lookup ends as soon as a declaration is found for the name.
If no declaration is found, the program is ill-formed.
The declarations from the namespace nominated by a using-directive become visible in a namespace enclosing the using-directive; see [namespace.udir].
For the purpose of the unqualified name lookup rules described in [basic.lookup.unqual], the declarations from the namespace nominated by the using-directive are considered members of that enclosing namespace.
The lookup for an unqualified name used as the postfix-expression of a function call is described in [basic.lookup.argdep].
[Note
:
For purposes of determining (during parsing) whether an expression is a postfix-expression for a function call, the usual name lookup rules apply.
The rules in [basic.lookup.argdep] have no effect on the syntactic interpretation of an expression.
For example,
typedef int f;
namespace N {
  struct A {
    friend void f(A &);
    operator int();
    void g(A a) {
      int i = f(a);  // f is the typedef, not the friend function: equivalent to int(a)
    }
  };
}
Because the expression is not a function call, the argument-dependent name lookup ([basic.lookup.argdep]) does not apply and the friend function f is not found.
end note
]
A name used in global scope, outside of any function, class or user-declared namespace, shall be declared before its use in global scope.
A name used in a user-declared namespace outside of the definition of any function or class shall be declared before its use in that namespace or before its use in a namespace enclosing its namespace.
In the definition of a function that is a member of namespace N, a name used after the function's declarator-id29 shall be declared before its use in the block in which it is used or in one of its enclosing blocks ([stmt.block]) or shall be declared before its use in namespace N or, if N is a nested namespace, shall be declared before its use in one of N's enclosing namespaces.
[Example
:
namespace A {
  namespace N {
    void f();
  }
}
void A::N::f() {
  i = 5;
  // The following scopes are searched for a declaration of i:
  // 1) outermost block scope of A​::​N​::​f, before the use of i
  // 2) scope of namespace N
  // 3) scope of namespace A
  // 4) global scope, before the definition of A​::​N​::​f
}
end example
]
A name used in the definition of a class X outside of a member function body, default argument, noexcept-specifier, brace-or-equal-initializer of a non-static data member, or nested class definition30 shall be declared in one of the following ways:
  • before its use in class X or be a member of a base class of X ([class.member.lookup]), or
  • if X is a nested class of class Y ([class.nest]), before the definition of X in Y, or shall be a member of a base class of Y (this lookup applies in turn to Y's enclosing classes, starting with the innermost enclosing class),31 or
  • if X is a local class ([class.local]) or is a nested class of a local class, before the definition of class X in a block enclosing the definition of class X, or
  • if X is a member of namespace N, or is a nested class of a class that is a member of N, or is a local class or a nested class within a local class of a function that is a member of N, before the definition of class X in namespace N or in one of N's enclosing namespaces.
[Example
:
namespace M {
  class B { };
}
namespace N {
  class Y : public M::B {
    class X {
      int a[i];
    };
  };
}

// The following scopes are searched for a declaration of i:
// 1) scope of class N​::​Y​::​X, before the use of i
// 2) scope of class N​::​Y, before the definition of N​::​Y​::​X
// 3) scope of N​::​Y's base class M​::​B
// 4) scope of namespace N, before the definition of N​::​Y
// 5) global scope, before the definition of N
end example
]
[Note
:
When looking for a prior declaration of a class or function introduced by a friend declaration, scopes outside of the innermost enclosing namespace scope are not considered; see [namespace.memdef].
end note
]
[Note
:
[basic.scope.class] further describes the restrictions on the use of names in a class definition.
[class.nest] further describes the restrictions on the use of names in nested class definitions.
[class.local] further describes the restrictions on the use of names in local class definitions.
end note
]
For the members of a class X, a name used in a member function body, in a default argument, in a noexcept-specifier, in the brace-or-equal-initializer of a non-static data member ([class.mem]), or in the definition of a class member outside of the definition of X, following the member's declarator-id32, shall be declared in one of the following ways:
  • before its use in the block in which it is used or in an enclosing block ([stmt.block]), or
  • shall be a member of class X or be a member of a base class of X ([class.member.lookup]), or
  • if X is a nested class of class Y ([class.nest]), shall be a member of Y, or shall be a member of a base class of Y (this lookup applies in turn to Y's enclosing classes, starting with the innermost enclosing class),33 or
  • if X is a local class ([class.local]) or is a nested class of a local class, before the definition of class X in a block enclosing the definition of class X, or
  • if X is a member of namespace N, or is a nested class of a class that is a member of N, or is a local class or a nested class within a local class of a function that is a member of N, before the use of the name, in namespace N or in one of N's enclosing namespaces.
[Example
:
class B { };
namespace M {
  namespace N {
    class X : public B {
      void f();
    };
  }
}
void M::N::X::f() {
  i = 16;
}

// The following scopes are searched for a declaration of i:
// 1) outermost block scope of M​::​N​::​X​::​f, before the use of i
// 2) scope of class M​::​N​::​X
// 3) scope of M​::​N​::​X's base class B
// 4) scope of namespace M​::​N
// 5) scope of namespace M
// 6) global scope, before the definition of M​::​N​::​X​::​f
end example
]
[Note
:
[class.mfct] and [class.static] further describe the restrictions on the use of names in member function definitions.
[class.nest] further describes the restrictions on the use of names in the scope of nested classes.
[class.local] further describes the restrictions on the use of names in local class definitions.
end note
]
Name lookup for a name used in the definition of a friend function ([class.friend]) defined inline in the class granting friendship shall proceed as described for lookup in member function definitions.
If the friend function is not defined in the class granting friendship, name lookup in the friend function definition shall proceed as described for lookup in namespace member function definitions.
In a friend declaration naming a member function, a name used in the function declarator and not part of a template-argument in the declarator-id is first looked up in the scope of the member function's class ([class.member.lookup]).
If it is not found, or if the name is part of a template-argument in the declarator-id, the look up is as described for unqualified names in the definition of the class granting friendship.
[Example
:
struct A {
  typedef int AT;
  void f1(AT);
  void f2(float);
  template <class T> void f3();
};
struct B {
  typedef char AT;
  typedef float BT;
  friend void A::f1(AT);      // parameter type is A​::​AT
  friend void A::f2(BT);      // parameter type is B​::​BT
  friend void A::f3<AT>();    // template argument is B​::​AT
};
end example
]
During the lookup for a name used as a default argument ([dcl.fct.default]) in a function parameter-declaration-clause or used in the expression of a mem-initializer for a constructor ([class.base.init]), the function parameter names are visible and hide the names of entities declared in the block, class or namespace scopes containing the function declaration.
[Note
:
[dcl.fct.default] further describes the restrictions on the use of names in default arguments.
[class.base.init] further describes the restrictions on the use of names in a ctor-initializer.
end note
]
During the lookup of a name used in the constant-expression of an enumerator-definition, previously declared enumerators of the enumeration are visible and hide the names of entities declared in the block, class, or namespace scopes containing the enum-specifier.
A name used in the definition of a static data member of class X ([class.static.data]) (after the qualified-id of the static member) is looked up as if the name was used in a member function of X.
[Note
:
[class.static.data] further describes the restrictions on the use of names in the definition of a static data member.
end note
]
If a variable member of a namespace is defined outside of the scope of its namespace then any name that appears in the definition of the member (after the declarator-id) is looked up as if the definition of the member occurred in its namespace.
[Example
:
namespace N {
  int i = 4;
  extern int j;
}

int i = 2;

int N::j = i;       // N​::​j == 4
end example
]
A name used in the handler for a function-try-block is looked up as if the name was used in the outermost block of the function definition.
In particular, the function parameter names shall not be redeclared in the exception-declaration nor in the outermost block of a handler for the function-try-block.
Names declared in the outermost block of the function definition are not found when looked up in the scope of a handler for the function-try-block.
[Note
:
But function parameter names are found.
end note
]
[Note
:
The rules for name lookup in template definitions are described in [temp.res].
end note
]
This refers to unqualified names that occur, for instance, in a type or default argument in the parameter-declaration-clause or used in the function body.
This refers to unqualified names following the class name; such a name may be used in the base-clause or may be used in the class definition.
This lookup applies whether the definition of X is nested within Y's definition or whether X's definition appears in a namespace scope enclosing Y's definition ([class.nest]).
That is, an unqualified name that occurs, for instance, in a type in the parameter-declaration-clause or in the noexcept-specifier.
This lookup applies whether the member function is defined within the definition of class X or whether the member function is defined in a namespace scope enclosing X's definition.

6.4.2 Argument-dependent name lookup [basic.lookup.argdep]

When the postfix-expression in a function call ([expr.call]) is an unqualified-id, other namespaces not considered during the usual unqualified lookup ([basic.lookup.unqual]) may be searched, and in those namespaces, namespace-scope friend function or function template declarations ([class.friend]) not otherwise visible may be found.
These modifications to the search depend on the types of the arguments (and for template template arguments, the namespace of the template argument).
[Example
:
namespace N {
  struct S { };
  void f(S);
}

void g() {
  N::S s;
  f(s);             // OK: calls N​::​f
  (f)(s);           // error: N​::​f not considered; parentheses prevent argument-dependent lookup
}
end example
]
For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero or more associated classes to be considered.
The sets of namespaces and classes are determined entirely by the types of the function arguments (and the namespace of any template template argument).
Typedef names and using-declarations used to specify the types do not contribute to this set.
The sets of namespaces and classes are determined in the following way:
  • If T is a fundamental type, its associated sets of namespaces and classes are both empty.
  • If T is a class type (including unions), its associated classes are: the class itself; the class of which it is a member, if any; and its direct and indirect base classes.
    Its associated namespaces are the innermost enclosing namespaces of its associated classes.
    Furthermore, if T is a class template specialization, its associated namespaces and classes also include: the namespaces and classes associated with the types of the template arguments provided for template type parameters (excluding template template parameters); the namespaces of which any template template arguments are members; and the classes of which any member templates used as template template arguments are members.
    [Note
    :
    Non-type template arguments do not contribute to the set of associated namespaces.
    end note
    ]
  • If T is an enumeration type, its associated namespace is the innermost enclosing namespace of its declaration.
    If it is a class member, its associated class is the member's class; else it has no associated class.
  • If T is a pointer to U or an array of U, its associated namespaces and classes are those associated with U.
  • If T is a function type, its associated namespaces and classes are those associated with the function parameter types and those associated with the return type.
  • If T is a pointer to a member function of a class X, its associated namespaces and classes are those associated with the function parameter types and return type, together with those associated with X.
  • If T is a pointer to a data member of class X, its associated namespaces and classes are those associated with the member type together with those associated with X.
If an associated namespace is an inline namespace ([namespace.def]), its enclosing namespace is also included in the set.
If an associated namespace directly contains inline namespaces, those inline namespaces are also included in the set.
In addition, if the argument is the name or address of a set of overloaded functions and/or function templates, its associated classes and namespaces are the union of those associated with each of the members of the set, i.e., the classes and namespaces associated with its parameter types and return type. Additionally, if the aforementioned set of overloaded functions is named with a template-id, its associated classes and namespaces also include those of its type template-arguments and its template template-arguments.
Let X be the lookup set produced by unqualified lookup ([basic.lookup.unqual]) and let Y be the lookup set produced by argument dependent lookup (defined as follows).
If X contains
  • a declaration of a class member, or
  • a block-scope function declaration that is not a using-declaration, or
  • a declaration that is neither a function nor a function template
then Y is empty.
Otherwise Y is the set of declarations found in the namespaces associated with the argument types as described below.
The set of declarations found by the lookup of the name is the union of X and Y.
[Note
:
The namespaces and classes associated with the argument types can include namespaces and classes already considered by the ordinary unqualified lookup.
end note
]
[Example
:
namespace NS {
  class T { };
  void f(T);
  void g(T, int);
}
NS::T parm;
void g(NS::T, float);
int main() {
  f(parm);                      // OK: calls NS​::​f
  extern void g(NS::T, float);
  g(parm, 1);                   // OK: calls g(NS​::​T, float)
}
end example
]
When considering an associated namespace, the lookup is the same as the lookup performed when the associated namespace is used as a qualifier ([namespace.qual]) except that:
  • Any using-directives in the associated namespace are ignored.
  • Any namespace-scope friend functions or friend function templates declared in associated classes are visible within their respective namespaces even if they are not visible during an ordinary lookup ([class.friend]).
  • All names except those of (possibly overloaded) functions and function templates are ignored.

6.4.3 Qualified name lookup [basic.lookup.qual]

The name of a class or namespace member or enumerator can be referred to after the ​::​ scope resolution operator ([expr.prim]) applied to a nested-name-specifier that denotes its class, namespace, or enumeration.
If a ​::​ scope resolution operator in a nested-name-specifier is not preceded by a decltype-specifier, lookup of the name preceding that ​::​ considers only namespaces, types, and templates whose specializations are types.
If the name found does not designate a namespace or a class, enumeration, or dependent type, the program is ill-formed.
[Example
:
class A {
public:
  static int n;
};
int main() {
  int A;
  A::n = 42;        // OK
  A b;              // ill-formed: A does not name a type
}
end example
]
[Note
:
Multiply qualified names, such as N1​::​N2​::​N3​::​n, can be used to refer to members of nested classes ([class.nest]) or members of nested namespaces.
end note
]
In a declaration in which the declarator-id is a qualified-id, names used before the qualified-id being declared are looked up in the defining namespace scope; names following the qualified-id are looked up in the scope of the member's class or namespace.
[Example
:
class X { };
class C {
  class X { };
  static const int number = 50;
  static X arr[number];
};
X C::arr[number];   // ill-formed:
                    // equivalent to ​::​X C​::​arr[C​::​number];
                    // and not to C​::​X C​::​arr[C​::​number];
end example
]
A name prefixed by the unary scope operator ​::​ ([expr.prim]) is looked up in global scope, in the translation unit where it is used.
The name shall be declared in global namespace scope or shall be a name whose declaration is visible in global scope because of a using-directive ([namespace.qual]).
The use of ​::​ allows a global name to be referred to even if its identifier has been hidden ([basic.scope.hiding]).
A name prefixed by a nested-name-specifier that nominates an enumeration type shall represent an enumerator of that enumeration.
If a pseudo-destructor-name ([expr.pseudo]) contains a nested-name-specifier, the type-names are looked up as types in the scope designated by the nested-name-specifier.
Similarly, in a qualified-id of the form:
nested-name-specifier class-name :: ~ class-name
the second class-name is looked up in the same scope as the first.
[Example
:
struct C {
  typedef int I;
};
typedef int I1, I2;
extern int* p;
extern int* q;
p->C::I::~I();      // I is looked up in the scope of C
q->I1::~I2();       // I2 is looked up in the scope of the postfix-expression

struct A {
  ~A();
};
typedef A AB;
int main() {
  AB* p;
  p->AB::~AB();     // explicitly calls the destructor for A
}
end example
]
[Note
:
[basic.lookup.classref] describes how name lookup proceeds after the . and -> operators.
end note
]

6.4.3.1 Class members [class.qual]

If the nested-name-specifier of a qualified-id nominates a class, the name specified after the nested-name-specifier is looked up in the scope of the class ([class.member.lookup]), except for the cases listed below.
The name shall represent one or more members of that class or of one of its base classes (Clause [class.derived]).
[Note
:
A class member can be referred to using a qualified-id at any point in its potential scope ([basic.scope.class]).
end note
]
The exceptions to the name lookup rule above are the following:
In a lookup in which function names are not ignored34 and the nested-name-specifier nominates a class C: the name is instead considered to name the constructor of class C.
[Note
:
For example, the constructor is not an acceptable lookup result in an elaborated-type-specifier so the constructor would not be used in place of the injected-class-name.
end note
]
Such a constructor name shall be used only in the declarator-id of a declaration that names a constructor or in a using-declaration.
[Example
:
struct A { A(); };
struct B: public A { B(); };

A::A() { }
B::B() { }

B::A ba;            // object of type A
A::A a;             // error, A​::​A is not a type name
struct A::A a2;     // object of type A
end example
]
A class member name hidden by a name in a nested declarative region or by the name of a derived class member can still be found if qualified by the name of its class followed by the ​::​ operator.
Lookups in which function names are ignored include names appearing in a nested-name-specifier, an elaborated-type-specifier, or a base-specifier.

6.4.3.2 Namespace members [namespace.qual]

If the nested-name-specifier of a qualified-id nominates a namespace (including the case where the nested-name-specifier is ​::​, i.e., nominating the global namespace), the name specified after the nested-name-specifier is looked up in the scope of the namespace.
The names in a template-argument of a template-id are looked up in the context in which the entire postfix-expression occurs.
For a namespace X and name m, the namespace-qualified lookup set is defined as follows: Let be the set of all declarations of m in X and the inline namespace set of X ([namespace.def]).
If is not empty, is ; otherwise, is the union of for all namespaces nominated by using-directives in X and its inline namespace set.
Given X​::​m (where X is a user-declared namespace), or given ​::​m (where X is the global namespace), if is the empty set, the program is ill-formed.
Otherwise, if has exactly one member, or if the context of the reference is a using-declaration, is the required set of declarations of m.
Otherwise if the use of m is not one that allows a unique declaration to be chosen from , the program is ill-formed.
[Example
:
int x;
namespace Y {
  void f(float);
  void h(int);
}

namespace Z {
  void h(double);
}

namespace A {
  using namespace Y;
  void f(int);
  void g(int);
  int i;
}

namespace B {
  using namespace Z;
  void f(char);
  int i;
}

namespace AB {
  using namespace A;
  using namespace B;
  void g();
}

void h()
{
  AB::g();          // g is declared directly in AB, therefore S is { AB​::​g() } and AB​::​g() is chosen

  AB::f(1);         // f is not declared directly in AB so the rules are applied recursively to A and B;
                    // namespace Y is not searched and Y​::​f(float) is not considered;
                    // S is  and overload resolution chooses A​::​f(int)

  AB::f('c');       // as above but resolution chooses B​::​f(char)

  AB::x++;          // x is not declared directly in AB, and is not declared in A or B, so the rules
                    // are applied recursively to Y and Z, S is { } so the program is ill-formed

  AB::i++;          // i is not declared directly in AB so the rules are applied recursively to A and B,
                    // S is  so the use is ambiguous and the program is ill-formed

  AB::h(16.8);      // h is not declared directly in AB and not declared directly in A or B so the rules
                    // are applied recursively to Y and Z, S is  and
                    // overload resolution chooses Z​::​h(double)
}
end example
]
[Note
:
The same declaration found more than once is not an ambiguity (because it is still a unique declaration).
[Example
:
namespace A {
  int a;
}

namespace B {
  using namespace A;
}

namespace C {
  using namespace A;
}

namespace BC {
  using namespace B;
  using namespace C;
}

void f()
{
  BC::a++;          // OK: S is 
}

namespace D {
  using A::a;
}

namespace BD {
  using namespace B;
  using namespace D;
}

void g()
{
  BD::a++;          // OK: S is 
}
end example
]
end note
]
[Example
:
Because each referenced namespace is searched at most once, the following is well-defined:
namespace B {
  int b;
}

namespace A {
  using namespace B;
  int a;
}

namespace B {
  using namespace A;
}

void f()
{
  A::a++;           // OK: a declared directly in A, S is { A​::​a }
  B::a++;           // OK: both A and B searched (once), S is { A​::​a }
  A::b++;           // OK: both A and B searched (once), S is { B​::​b }
  B::b++;           // OK: b declared directly in B, S is { B​::​b }
}
end example
]
During the lookup of a qualified namespace member name, if the lookup finds more than one declaration of the member, and if one declaration introduces a class name or enumeration name and the other declarations either introduce the same variable, the same enumerator or a set of functions, the non-type name hides the class or enumeration name if and only if the declarations are from the same namespace; otherwise (the declarations are from different namespaces), the program is ill-formed.
[Example
:
namespace A {
  struct x { };
  int x;
  int y;
}

namespace B {
  struct y { };
}

namespace C {
  using namespace A;
  using namespace B;
  int i = C::x;     // OK, A​::​x (of type int)
  int j = C::y;     // ambiguous, A​::​y or B​::​y
}
end example
]
In a declaration for a namespace member in which the declarator-id is a qualified-id, given that the qualified-id for the namespace member has the form
nested-name-specifier unqualified-id
the unqualified-id shall name a member of the namespace designated by the nested-name-specifier or of an element of the inline namespace set ([namespace.def]) of that namespace.
[Example
:
namespace A {
  namespace B {
    void f1(int);
  }
  using namespace B;
}
void A::f1(int){ }  // ill-formed, f1 is not a member of A
end example
]
However, in such namespace member declarations, the nested-name-specifier may rely on using-directives to implicitly provide the initial part of the nested-name-specifier.
[Example
:
namespace A {
  namespace B {
    void f1(int);
  }
}

namespace C {
  namespace D {
    void f1(int);
  }
}

using namespace A;
using namespace C::D;
void B::f1(int){ }  // OK, defines A​::​B​::​f1(int)
end example
]

6.4.4 Elaborated type specifiers [basic.lookup.elab]

An elaborated-type-specifier may be used to refer to a previously declared class-name or enum-name even though the name has been hidden by a non-type declaration ([basic.scope.hiding]).
If the elaborated-type-specifier has no nested-name-specifier, and unless the elaborated-type-specifier appears in a declaration with the following form:
class-key attribute-specifier-seq identifier ;
the identifier is looked up according to [basic.lookup.unqual] but ignoring any non-type names that have been declared.
If the elaborated-type-specifier is introduced by the enum keyword and this lookup does not find a previously declared type-name, the elaborated-type-specifier is ill-formed.
If the elaborated-type-specifier is introduced by the class-key and this lookup does not find a previously declared type-name, or if the elaborated-type-specifier appears in a declaration with the form:
If the elaborated-type-specifier has a nested-name-specifier, qualified name lookup is performed, as described in [basic.lookup.qual], but ignoring any non-type names that have been declared.
If the name lookup does not find a previously declared type-name, the elaborated-type-specifier is ill-formed.
[Example
:
struct Node {
  struct Node* Next;            // OK: Refers to Node at global scope
  struct Data* Data;            // OK: Declares type Data
                                // at global scope and member Data
};

struct Data {
  struct Node* Node;            // OK: Refers to Node at global scope
  friend struct ::Glob;         // error: Glob is not declared, cannot introduce a qualified type ([dcl.type.elab])
  friend struct Glob;           // OK: Refers to (as yet) undeclared Glob at global scope.
  /* ... */
};

struct Base {
  struct Data;                  // OK: Declares nested Data
  struct ::Data*     thatData;  // OK: Refers to ​::​Data
  struct Base::Data* thisData;  // OK: Refers to nested Data
  friend class ::Data;          // OK: global Data is a friend
  friend class Data;            // OK: nested Data is a friend
  struct Data { /* ... */ };    // Defines nested Data
};

struct Data;                    // OK: Redeclares Data at global scope
struct ::Data;                  // error: cannot introduce a qualified type ([dcl.type.elab])
struct Base::Data;              // error: cannot introduce a qualified type ([dcl.type.elab])
struct Base::Datum;             // error: Datum undefined
struct Base::Data* pBase;       // OK: refers to nested Data
end example
]

6.4.5 Class member access [basic.lookup.classref]

In a class member access expression ([expr.ref]), if the . or -> token is immediately followed by an identifier followed by a <, the identifier must be looked up to determine whether the < is the beginning of a template argument list ([temp.names]) or a less-than operator.
The identifier is first looked up in the class of the object expression.
If the identifier is not found, it is then looked up in the context of the entire postfix-expression and shall name a class template.
If the id-expression in a class member access ([expr.ref]) is an unqualified-id, and the type of the object expression is of a class type C, the unqualified-id is looked up in the scope of class C.
For a pseudo-destructor call ([expr.pseudo]), the unqualified-id is looked up in the context of the complete postfix-expression.
If the unqualified-id is ~type-name, the type-name is looked up in the context of the entire postfix-expression.
If the type T of the object expression is of a class type C, the type-name is also looked up in the scope of class C.
At least one of the lookups shall find a name that refers to cv T.
[Example
:
struct A { };

struct B {
  struct A { };
  void f(::A* a);
};

void B::f(::A* a) {
  a->~A();                      // OK: lookup in *a finds the injected-class-name
}
end example
]
If the id-expression in a class member access is a qualified-id of the form
class-name-or-namespace-name::...
the class-name-or-namespace-name following the . or -> operator is first looked up in the class of the object expression and the name, if found, is used.
Otherwise it is looked up in the context of the entire postfix-expression.
[Note
:
See [basic.lookup.qual], which describes the lookup of a name before ​::​, which will only find a type or namespace name.
end note
]
If the qualified-id has the form
::class-name-or-namespace-name::...
the class-name-or-namespace-name is looked up in global scope as a class-name or namespace-name.
If the nested-name-specifier contains a simple-template-id, the names in its template-arguments are looked up in the context in which the entire postfix-expression occurs.
If the id-expression is a conversion-function-id, its conversion-type-id is first looked up in the class of the object expression and the name, if found, is used.
Otherwise it is looked up in the context of the entire postfix-expression.
In each of these lookups, only names that denote types or templates whose specializations are types are considered.
[Example
:
struct A { };
namespace N {
  struct A {
    void g() { }
    template <class T> operator T();
  };
}

int main() {
  N::A a;
  a.operator A();               // calls N​::​A​::​operator N​::​A
}
end example
]

6.4.6 Using-directives and namespace aliases [basic.lookup.udir]

In a using-directive or namespace-alias-definition, during the lookup for a namespace-name or for a name in a nested-name-specifier only namespace names are considered.

6.6 Start and termination [basic.start]

6.6.1 main function [basic.start.main]

A program shall contain a global function called main.
Executing a program starts a main thread of execution ([intro.multithread], [thread.threads]) in which the main function is invoked, and in which variables of static storage duration might be initialized ([basic.start.static]) and destroyed ([basic.start.term]).
It is implementation-defined whether a program in a freestanding environment is required to define a main function.
[Note
:
In a freestanding environment, start-up and termination is implementation-defined; start-up contains the execution of constructors for objects of namespace scope with static storage duration; termination contains the execution of destructors for objects with static storage duration.
end note
]
An implementation shall not predefine the main function.
This function shall not be overloaded.
Its type shall have C++ language linkage and it shall have a declared return type of type int, but otherwise its type is implementation-defined.
An implementation shall allow both
  • a function of () returning int and
  • a function of (int, pointer to pointer to char) returning int
as the type of main ([dcl.fct]).
In the latter form, for purposes of exposition, the first function parameter is called argc and the second function parameter is called argv, where argc shall be the number of arguments passed to the program from the environment in which the program is run.
If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings (ntmbs s) ([multibyte.strings]) and argv[0] shall be the pointer to the initial character of a ntmbs that represents the name used to invoke the program or "".
The value of argc shall be non-negative.
The value of argv[argc] shall be 0.
[Note
:
It is recommended that any further (optional) parameters be added after argv.
end note
]
The function main shall not be used within a program.
The linkage ([basic.link]) of main is implementation-defined.
A program that defines main as deleted or that declares main to be inline, static, or constexpr is ill-formed.
The main function shall not be declared with a linkage-specification.
A program that declares a variable main at global scope or that declares the name main with C language linkage (in any namespace) is ill-formed.
The name main is not otherwise reserved.
[Example
:
Member functions, classes, and enumerations can be called main, as can entities in other namespaces.
end example
]
Terminating the program without leaving the current block (e.g., by calling the function std​::​exit(int) ([support.start.term])) does not destroy any objects with automatic storage duration ([class.dtor]).
If std​::​exit is called to end a program during the destruction of an object with static or thread storage duration, the program has undefined behavior.
A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std​::​exit with the return value as the argument.
If control flows off the end of the compound-statement of main, the effect is equivalent to a return with operand 0 (see also [except.handle]).

6.6.2 Static initialization [basic.start.static]

Variables with static storage duration are initialized as a consequence of program initiation.
Variables with thread storage duration are initialized as a consequence of thread execution.
Within each of these phases of initiation, initialization occurs as follows.
A constant initializer for a variable or temporary object o is an initializer whose full-expression is a constant expression, except that if o is an object, such an initializer may also invoke constexpr constructors for o and its subobjects even if those objects are of non-literal class types.
[Note
:
Such a class may have a non-trivial destructor.
end note
]
Constant initialization is performed if a variable or temporary object with static or thread storage duration is initialized by a constant initializer for the entity.
If constant initialization is not performed, a variable with static storage duration ([basic.stc.static]) or thread storage duration ([basic.stc.thread]) is zero-initialized ([dcl.init]).
Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization.
All static initialization strongly happens before ([intro.races]) any dynamic initialization.
[Note
:
The dynamic initialization of non-local variables is described in [basic.start.dynamic]; that of local static variables is described in [stmt.dcl].
end note
]
An implementation is permitted to perform the initialization of a variable with static or thread storage duration as a static initialization even if such initialization is not required to be done statically, provided that
  • the dynamic version of the initialization does not change the value of any other object of static or thread storage duration prior to its initialization, and
  • the static version of the initialization produces the same value in the initialized variable as would be produced by the dynamic initialization if all variables not required to be initialized statically were initialized dynamically.
[Note
:
As a consequence, if the initialization of an object obj1 refers to an object obj2 of namespace scope potentially requiring dynamic initialization and defined later in the same translation unit, it is unspecified whether the value of obj2 used will be the value of the fully initialized obj2 (because obj2 was statically initialized) or will be the value of obj2 merely zero-initialized.
For example,
inline double fd() { return 1.0; }
extern double d1;
double d2 = d1;     // unspecified:
                    // may be statically initialized to 0.0 or
                    // dynamically initialized to 0.0 if d1 is
                    // dynamically initialized, or 1.0 otherwise
double d1 = fd();   // may be initialized statically or dynamically to 1.0
end note
]

6.6.3 Dynamic initialization of non-local variables [basic.start.dynamic]

Dynamic initialization of a non-local variable with static storage duration is unordered if the variable is an implicitly or explicitly instantiated specialization, is partially-ordered if the variable is an inline variable that is not an implicitly or explicitly instantiated specialization, and otherwise is ordered.
[Note
:
An explicitly specialized non-inline static data member or variable template specialization has ordered initialization.
end note
]
Dynamic initialization of non-local variables V and W with static storage duration are ordered as follows:
  • If V and W have ordered initialization and V is defined before W within a single translation unit, the initialization of V is sequenced before the initialization of W.
  • If V has partially-ordered initialization, W does not have unordered initialization, and V is defined before W in every translation unit in which W is defined, then
    • if the program starts a thread ([intro.multithread]) other than the main thread ([basic.start.main]), the initialization of V strongly happens before the initialization of W;
    • otherwise, the initialization of V is sequenced before the initialization of W.
  • Otherwise, if the program starts a thread other than the main thread before either V or W is initialized, it is unspecified in which threads the initializations of V and W occur; the initializations are unsequenced if they occur in the same thread.
  • Otherwise, the initializations of V and W are indeterminately sequenced.
[Note
:
This definition permits initialization of a sequence of ordered variables concurrently with another sequence.
end note
]
A non-initialization odr-use is an odr-use ([basic.def.odr]) not caused directly or indirectly by the initialization of a non-local static or thread storage duration variable.
It is implementation-defined whether the dynamic initialization of a non-local non-inline variable with static storage duration is sequenced before the first statement of main or is deferred.
If it is deferred, it strongly happens before any non-initialization odr-use of any non-inline function or non-inline variable defined in the same translation unit as the variable to be initialized.36
It is implementation-defined in which threads and at which points in the program such deferred dynamic initialization occurs.
[Note
:
Such points should be chosen in a way that allows the programmer to avoid deadlocks.
end note
]
[Example
:
// - File 1 -
#include "a.h"
#include "b.h"
B b;
A::A(){
  b.Use();
}

// - File 2 -
#include "a.h"
A a;

// - File 3 -
#include "a.h"
#include "b.h"
extern A a;
extern B b;

int main() {
  a.Use();
  b.Use();
}
It is implementation-defined whether either a or b is initialized before main is entered or whether the initializations are delayed until a is first odr-used in main.
In particular, if a is initialized before main is entered, it is not guaranteed that b will be initialized before it is odr-used by the initialization of a, that is, before A​::​A is called.
If, however, a is initialized at some point after the first statement of main, b will be initialized prior to its use in A​::​A.
end example
]
It is implementation-defined whether the dynamic initialization of a non-local inline variable with static storage duration is sequenced before the first statement of main or is deferred.
If it is deferred, it strongly happens before any non-initialization odr-use of that variable.
It is implementation-defined in which threads and at which points in the program such deferred dynamic initialization occurs.
It is implementation-defined whether the dynamic initialization of a non-local non-inline variable with thread storage duration is sequenced before the first statement of the initial function of a thread or is deferred.
If it is deferred, the initialization associated with the entity for thread t is sequenced before the first non-initialization odr-use by t of any non-inline variable with thread storage duration defined in the same translation unit as the variable to be initialized.
It is implementation-defined in which threads and at which points in the program such deferred dynamic initialization occurs.
If the initialization of a non-local variable with static or thread storage duration exits via an exception, std​::​terminate is called ([except.terminate]).
A non-local variable with static storage duration having initialization with side effects is initialized in this case, even if it is not itself odr-used ([basic.def.odr], [basic.stc.static]).

6.6.4 Termination [basic.start.term]

Destructors ([class.dtor]) for initialized objects (that is, objects whose lifetime ([basic.life]) has begun) with static storage duration, and functions registered with std​::​atexit, are called as part of a call to std​::​exit ([support.start.term]).
The call to std​::​exit is sequenced before the invocations of the destructors and the registered functions.
[Note
:
Returning from main invokes std​::​exit ([basic.start.main]).
end note
]
Destructors for initialized objects with thread storage duration within a given thread are called as a result of returning from the initial function of that thread and as a result of that thread calling std​::​exit.
The completions of the destructors for all initialized objects with thread storage duration within that thread strongly happen before the initiation of the destructors of any object with static storage duration.
If the completion of the constructor or dynamic initialization of an object with static storage duration strongly happens before that of another, the completion of the destructor of the second is sequenced before the initiation of the destructor of the first.
If the completion of the constructor or dynamic initialization of an object with thread storage duration is sequenced before that of another, the completion of the destructor of the second is sequenced before the initiation of the destructor of the first.
If an object is initialized statically, the object is destroyed in the same order as if the object was dynamically initialized.
For an object of array or class type, all subobjects of that object are destroyed before any block-scope object with static storage duration initialized during the construction of the subobjects is destroyed.
If the destruction of an object with static or thread storage duration exits via an exception, std​::​terminate is called ([except.terminate]).
If a function contains a block-scope object of static or thread storage duration that has been destroyed and the function is called during the destruction of an object with static or thread storage duration, the program has undefined behavior if the flow of control passes through the definition of the previously destroyed block-scope object.
Likewise, the behavior is undefined if the block-scope object is used indirectly (i.e., through a pointer) after its destruction.
If the completion of the initialization of an object with static storage duration strongly happens before a call to std​::​atexit (see <cstdlib>, [support.start.term]), the call to the function passed to std​::​atexit is sequenced before the call to the destructor for the object.
If a call to std​::​atexit strongly happens before the completion of the initialization of an object with static storage duration, the call to the destructor for the object is sequenced before the call to the function passed to std​::​atexit.
If a call to std​::​atexit strongly happens before another call to std​::​atexit, the call to the function passed to the second std​::​atexit call is sequenced before the call to the function passed to the first std​::​atexit call.
If there is a use of a standard library object or function not permitted within signal handlers ([support.runtime]) that does not happen before ([intro.multithread]) completion of destruction of objects with static storage duration and execution of std​::​atexit registered functions ([support.start.term]), the program has undefined behavior.
[Note
:
If there is a use of an object with static storage duration that does not happen before the object's destruction, the program has undefined behavior.
Terminating every thread before a call to std​::​exit or the exit from main is sufficient, but not necessary, to satisfy these requirements.
These requirements permit thread managers as static-storage-duration objects.
end note
]
Calling the function std​::​abort() declared in <cstdlib> terminates the program without executing any destructors and without calling the functions passed to std​::​atexit() or std​::​at_­quick_­exit().

6.7 Storage duration [basic.stc]

The storage duration is the property of an object that defines the minimum potential lifetime of the storage containing the object.
The storage duration is determined by the construct used to create the object and is one of the following:
  • static storage duration
  • thread storage duration
  • automatic storage duration
  • dynamic storage duration
Static, thread, and automatic storage durations are associated with objects introduced by declarations ([basic.def]) and implicitly created by the implementation ([class.temporary]).
The dynamic storage duration is associated with objects created by a new-expression.
The storage duration categories apply to references as well.
When the end of the duration of a region of storage is reached, the values of all pointers representing the address of any part of that region of storage become invalid pointer values ([basic.compound]).
Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior.
Any other use of an invalid pointer value has implementation-defined behavior.37
Some implementations might define that copying an invalid pointer value causes a system-generated runtime fault.

6.7.1 Static storage duration [basic.stc.static]

All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration.
The storage for these entities shall last for the duration of the program ([basic.start.static], [basic.start.term]).
If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in [class.copy].
The keyword static can be used to declare a local variable with static storage duration.
[Note
:
[stmt.dcl] describes the initialization of local static variables; [basic.start.term] describes the destruction of local static variables.
end note
]
The keyword static applied to a class data member in a class definition gives the data member static storage duration.

6.7.2 Thread storage duration [basic.stc.thread]

All variables declared with the thread_­local keyword have thread storage duration.
The storage for these entities shall last for the duration of the thread in which they are created.
There is a distinct object or reference per thread, and use of the declared name refers to the entity associated with the current thread.
A variable with thread storage duration shall be initialized before its first odr-use ([basic.def.odr]) and, if constructed, shall be destroyed on thread exit.

6.7.3 Automatic storage duration [basic.stc.auto]

Block-scope variables not explicitly declared static, thread_­local, or extern have automatic storage duration.
The storage for these entities lasts until the block in which they are created exits.
[Note
:
These variables are initialized and destroyed as described in [stmt.dcl].
end note
]
If a variable with automatic storage duration has initialization or a destructor with side effects, an implementation shall not destroy it before the end of its block nor eliminate it as an optimization, even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in [class.copy].

6.7.4 Dynamic storage duration [basic.stc.dynamic]

Objects can be created dynamically during program execution ([intro.execution]), using new-expressions, and destroyed using delete-expressions.
A C++ implementation provides access to, and management of, dynamic storage via the global allocation functions operator new and operator new[] and the global deallocation functions operator delete and operator delete[].
[Note
:
The non-allocating forms described in [new.delete.placement] do not perform allocation or deallocation.
end note
]
The library provides default definitions for the global allocation and deallocation functions.
Some global allocation and deallocation functions are replaceable ([new.delete]).
A C++ program shall provide at most one definition of a replaceable allocation or deallocation function.
Any such function definition replaces the default version provided in the library ([replacement.functions]).
The following allocation and deallocation functions ([support.dynamic]) are implicitly declared in global scope in each translation unit of a program.
void* operator new(std::size_t);
void* operator new(std::size_t, std::align_val_t);

void operator delete(void*) noexcept;
void operator delete(void*, std::size_t) noexcept;
void operator delete(void*, std::align_val_t) noexcept;
void operator delete(void*, std::size_t, std::align_val_t) noexcept;

void* operator new[](std::size_t);
void* operator new[](std::size_t, std::align_val_t);

void operator delete[](void*) noexcept;
void operator delete[](void*, std::size_t) noexcept;
void operator delete[](void*, std::align_val_t) noexcept;
void operator delete[](void*, std::size_t, std::align_val_t) noexcept;
These implicit declarations introduce only the function names operator new, operator new[], operator delete, and operator delete[].
[Note
:
The implicit declarations do not introduce the names std, std​::​size_­t, std​::​align_­val_­t, or any other names that the library uses to declare these names.
Thus, a new-expression, delete-expression or function call that refers to one of these functions without including the header <new> is well-formed.
However, referring to std or std​::​size_­t or std​::​align_­val_­t is ill-formed unless the name has been declared by including the appropriate header.
end note
]
Allocation and/or deallocation functions may also be declared and defined for any class ([class.free]).
Any allocation and/or deallocation functions defined in a C++ program, including the default versions in the library, shall conform to the semantics specified in [basic.stc.dynamic.allocation] and [basic.stc.dynamic.deallocation].

6.7.4.1 Allocation functions [basic.stc.dynamic.allocation]

An allocation function shall be a class member function or a global function; a program is ill-formed if an allocation function is declared in a namespace scope other than global scope or declared static in global scope.
The return type shall be void*.
The first parameter shall have type std​::​size_­t ([support.types]).
The first parameter shall not have an associated default argument ([dcl.fct.default]).
The value of the first parameter shall be interpreted as the requested size of the allocation.
An allocation function can be a function template.
Such a template shall declare its return type and first parameter as specified above (that is, template parameter types shall not be used in the return type and first parameter type).
Template allocation functions shall have two or more parameters.
The allocation function attempts to allocate the requested amount of storage.
If it is successful, it shall return the address of the start of a block of storage whose length in bytes shall be at least as large as the requested size.
There are no constraints on the contents of the allocated storage on return from the allocation function.
The order, contiguity, and initial value of storage allocated by successive calls to an allocation function are unspecified.
The pointer returned shall be suitably aligned so that it can be converted to a pointer to any suitable complete object type ([new.delete.single]) and then used to access the object or array in the storage allocated (until the storage is explicitly deallocated by a call to a corresponding deallocation function).
Even if the size of the space requested is zero, the request can fail.
If the request succeeds, the value returned shall be a non-null pointer value ([conv.ptr]) p0 different from any previously returned value p1, unless that value p1 was subsequently passed to an operator delete.
Furthermore, for the library allocation functions in [new.delete.single] and [new.delete.array], p0 shall represent the address of a block of storage disjoint from the storage for any other object accessible to the caller.
The effect of indirecting through a pointer returned as a request for zero size is undefined.38
An allocation function that fails to allocate storage can invoke the currently installed new-handler function ([new.handler]), if any.
[Note
:
A program-supplied allocation function can obtain the address of the currently installed new_­handler using the std​::​get_­new_­handler function ([set.new.handler]).
end note
]
If an allocation function that has a non-throwing exception specification ([except.spec]) fails to allocate storage, it shall return a null pointer.
Any other allocation function that fails to allocate storage shall indicate failure only by throwing an exception ([except.throw]) of a type that would match a handler ([except.handle]) of type std​::​bad_­alloc ([bad.alloc]).
A global allocation function is only called as the result of a new expression ([expr.new]), or called directly using the function call syntax ([expr.call]), or called indirectly through calls to the functions in the C++ standard library.
[Note
:
In particular, a global allocation function is not called to allocate storage for objects with static storage duration ([basic.stc.static]), for objects or references with thread storage duration ([basic.stc.thread]), for objects of type std​::​type_­info ([expr.typeid]), or for an exception object ([except.throw]).
end note
]
The intent is to have operator new() implementable by calling std​::​malloc() or std​::​calloc(), so the rules are substantially the same.
C++ differs from C in requiring a zero request to return a non-null pointer.

6.7.4.2 Deallocation functions [basic.stc.dynamic.deallocation]

Deallocation functions shall be class member functions or global functions; a program is ill-formed if deallocation functions are declared in a namespace scope other than global scope or declared static in global scope.
Each deallocation function shall return void and its first parameter shall be void*.
A deallocation function may have more than one parameter.
A usual deallocation function is a deallocation function that has:
  • exactly one parameter; or
  • exactly two parameters, the type of the second being either std​::​align_­val_­t or std​::​size_­t39; or
  • exactly three parameters, the type of the second being std​::​size_­t and the type of the third being std​::​align_­val_­t.
A deallocation function may be an instance of a function template.
Neither the first parameter nor the return type shall depend on a template parameter.
[Note
:
That is, a deallocation function template shall have a first parameter of type void* and a return type of void (as specified above).
end note
]
A deallocation function template shall have two or more function parameters.
A template instance is never a usual deallocation function, regardless of its signature.
If a deallocation function terminates by throwing an exception, the behavior is undefined.
The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect.
If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value ([conv.ptr]), the deallocation function shall deallocate the storage referenced by the pointer, ending the duration of the region of storage.
The global operator delete(void*, std​::​size_­t) precludes use of an allocation function void operator new(std​::​size_­t, std​::​size_­t) as a placement allocation function ([diff.cpp11.basic]).

6.7.4.3 Safely-derived pointers [basic.stc.dynamic.safety]

A traceable pointer object is
  • an object of an object pointer type ([basic.compound]), or
  • an object of an integral type that is at least as large as std​::​intptr_­t, or
  • a sequence of elements in an array of narrow character type ([basic.fundamental]), where the size and alignment of the sequence match those of some object pointer type.
A pointer value is a safely-derived pointer to a dynamic object only if it has an object pointer type and it is one of the following:
  • the value returned by a call to the C++ standard library implementation of ​::​operator new(std​::​​size_­t) or ​::​operator new(std​::​size_­t, std​::​align_­val_­t);40
  • the result of taking the address of an object (or one of its subobjects) designated by an lvalue resulting from indirection through a safely-derived pointer value;
  • the result of well-defined pointer arithmetic ([expr.add]) using a safely-derived pointer value;
  • the result of a well-defined pointer conversion ([conv.ptr], [expr.cast]) of a safely-derived pointer value;
  • the result of a reinterpret_­cast of a safely-derived pointer value;
  • the result of a reinterpret_­cast of an integer representation of a safely-derived pointer value;
  • the value of an object whose value was copied from a traceable pointer object, where at the time of the copy the source object contained a copy of a safely-derived pointer value.
An integer value is an integer representation of a safely-derived pointer only if its type is at least as large as std​::​intptr_­t and it is one of the following:
  • the result of a reinterpret_­cast of a safely-derived pointer value;
  • the result of a valid conversion of an integer representation of a safely-derived pointer value;
  • the value of an object whose value was copied from a traceable pointer object, where at the time of the copy the source object contained an integer representation of a safely-derived pointer value;
  • the result of an additive or bitwise operation, one of whose operands is an integer representation of a safely-derived pointer value P, if that result converted by reinterpret_­cast<void*> would compare equal to a safely-derived pointer computable from reinterpret_­cast<void*>(P).
An implementation may have relaxed pointer safety, in which case the validity of a pointer value does not depend on whether it is a safely-derived pointer value.
Alternatively, an implementation may have strict pointer safety, in which case a pointer value referring to an object with dynamic storage duration that is not a safely-derived pointer value is an invalid pointer value unless the referenced complete object has previously been declared reachable ([util.dynamic.safety]).
[Note
:
The effect of using an invalid pointer value (including passing it to a deallocation function) is undefined, see [basic.stc.dynamic.deallocation].
This is true even if the unsafely-derived pointer value might compare equal to some safely-derived pointer value.
end note
]
It is implementation-defined whether an implementation has relaxed or strict pointer safety.
This section does not impose restrictions on indirection through pointers to memory not allocated by ​::​operator new.
This maintains the ability of many C++ implementations to use binary libraries and components written in other languages.
In particular, this applies to C binaries, because indirection through pointers to memory allocated by std​::​malloc is not restricted.

6.7.5 Duration of subobjects [basic.stc.inherit]

The storage duration of subobjects and reference members is that of their complete object ([intro.object]).

6.8 Object lifetime [basic.life]

The lifetime of an object or reference is a runtime property of the object or reference.
An object is said to have non-vacuous initialization if it is of a class or aggregate type and it or one of its subobjects is initialized by a constructor other than a trivial default constructor.
[Note
:
Initialization by a trivial copy/move constructor is non-vacuous initialization.
end note
]
The lifetime of an object of type T begins when:
  • storage with the proper alignment and size for type T is obtained, and
  • if the object has non-vacuous initialization, its initialization is complete,
except that if the object is a union member or subobject thereof, its lifetime only begins if that union member is the initialized member in the union ([dcl.init.aggr], [class.base.init]), or as described in [class.union].
The lifetime of an object o of type T ends when:
  • if T is a class type with a non-trivial destructor ([class.dtor]), the destructor call starts, or
  • the storage which the object occupies is released, or is reused by an object that is not nested within o ([intro.object]).
The lifetime of a reference begins when its initialization is complete.
The lifetime of a reference ends as if it were a scalar object.
[Note
:
[class.base.init] describes the lifetime of base and member subobjects.
end note
]
The properties ascribed to objects and references throughout this International Standard apply for a given object or reference only during its lifetime.
[Note
:
In particular, before the lifetime of an object starts and after its lifetime ends there are significant restrictions on the use of the object, as described below, in [class.base.init] and in [class.cdtor].
Also, the behavior of an object under construction and destruction might not be the same as the behavior of an object whose lifetime has started and not ended.
[class.base.init] and [class.cdtor] describe the behavior of objects during the construction and destruction phases.
end note
]
A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor.
For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.
Before the lifetime of an object has started but after the storage which the object will occupy has been allocated41 or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that represents the address of the storage location where the object will be or was located may be used but only in limited ways.
For an object under construction or destruction, see [class.cdtor].
Otherwise, such a pointer refers to allocated storage ([basic.stc.dynamic.deallocation]), and using the pointer as if the pointer were of type void*, is well-defined.
Indirection through such a pointer is permitted but the resulting lvalue may only be used in limited ways, as described below.
The program has undefined behavior if:
  • the object will be or was of a class type with a non-trivial destructor and the pointer is used as the operand of a delete-expression,
  • the pointer is used to access a non-static data member or call a non-static member function of the object, or
  • the pointer is implicitly converted ([conv.ptr]) to a pointer to a virtual base class, or
  • the pointer is used as the operand of a static_­cast ([expr.static.cast]), except when the conversion is to pointer to cv void, or to pointer to cv void and subsequently to pointer to cv char, cv unsigned char, or cv std​::​byte ([cstddef.syn]), or
  • the pointer is used as the operand of a dynamic_­cast ([expr.dynamic.cast]).
[Example
:
#include <cstdlib>

struct B {
  virtual void f();
  void mutate();
  virtual ~B();
};

struct D1 : B { void f(); };
struct D2 : B { void f(); };

void B::mutate() {
  new (this) D2;    // reuses storage — ends the lifetime of *this
  f();              // undefined behavior
  ... = this;       // OK, this points to valid memory
}

void g() {
  void* p = std::malloc(sizeof(D1) + sizeof(D2));
  B* pb = new (p) D1;
  pb->mutate();
  *pb;              // OK: pb points to valid memory
  void* q = pb;     // OK: pb points to valid memory
  pb->f();          // undefined behavior, lifetime of *pb has ended
}
end example
]
Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways.
For an object under construction or destruction, see [class.cdtor].
Otherwise, such a glvalue refers to allocated storage ([basic.stc.dynamic.deallocation]), and using the properties of the glvalue that do not depend on its value is well-defined.
The program has undefined behavior if:
  • the glvalue is used to access the object, or
  • the glvalue is used to call a non-static member function of the object, or
  • the glvalue is bound to a reference to a virtual base class ([dcl.init.ref]), or
  • the glvalue is used as the operand of a dynamic_­cast ([expr.dynamic.cast]) or as the operand of typeid.
If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if:
  • the storage for the new object exactly overlays the storage location which the original object occupied, and
  • the new object is of the same type as the original object (ignoring the top-level cv-qualifiers), and
  • the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and
  • the original object was a most derived object ([intro.object]) of type T and the new object is a most derived object of type T (that is, they are not base class subobjects).
[Example
:
struct C {
  int i;
  void f();
  const C& operator=( const C& );
};

const C& C::operator=( const C& other) {
  if ( this != &other ) {
    this->~C();                 // lifetime of *this ends
    new (this) C(other);        // new object of type C created
    f();                        // well-defined
  }
  return *this;
}

C c1;
C c2;
c1 = c2;                        // well-defined
c1.f();                         // well-defined; c1 refers to a new object of type C
end example
]
[Note
:
If these conditions are not met, a pointer to the new object can be obtained from a pointer that represents the address of its storage by calling std​::​launder ([support.dynamic]).
end note
]
If a program ends the lifetime of an object of type T with static ([basic.stc.static]), thread ([basic.stc.thread]), or automatic ([basic.stc.auto]) storage duration and if T has a non-trivial destructor,42 the program must ensure that an object of the original type occupies that same storage location when the implicit destructor call takes place; otherwise the behavior of the program is undefined.
This is true even if the block is exited with an exception.
[Example
:
class T { };
struct B {
   ~B();
};

void h() {
   B b;
   new (&b) T;
}                               // undefined behavior at block exit
end example
]
Creating a new object within the storage that a const complete object with static, thread, or automatic storage duration occupies, or within the storage that such a const object used to occupy before its lifetime ended, results in undefined behavior.
[Example
:
struct B {
  B();
  ~B();
};

const B b;

void h() {
  b.~B();
  new (const_cast<B*>(&b)) const B;     // undefined behavior
}
end example
]
In this section, “before” and “after” refer to the “happens before” relation ([intro.multithread]).
[Note
:
Therefore, undefined behavior results if an object that is being constructed in one thread is referenced from another thread without adequate synchronization.
end note
]
For example, before the construction of a global object of non-POD class type ([class.cdtor]).
That is, an object for which a destructor will be called implicitly—upon exit from the block for an object with automatic storage duration, upon exit from the thread for an object with thread storage duration, or upon exit from the program for an object with static storage duration.

6.9 Types [basic.types]

[Note
:
[basic.types] and the subclauses thereof impose requirements on implementations regarding the representation of types.
There are two kinds of types: fundamental types and compound types.
Types describe objects ([intro.object]), references ([dcl.ref]), or functions ([dcl.fct]).
end note
]
For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes ([intro.memory]) making up the object can be copied into an array of char, unsigned char, or std​::​byte ([cstddef.syn]).43
If the content of that array is copied back into the object, the object shall subsequently hold its original value.
[Example
:
#define N sizeof(T)
char buf[N];
T obj;                          // obj initialized to its original value
std::memcpy(buf, &obj, N);      // between these two calls to std​::​memcpy, obj might be modified
std::memcpy(&obj, buf, N);      // at this point, each subobject of obj of scalar type holds its original value
end example
]
For any trivially copyable type T, if two pointers to T point to distinct T objects obj1 and obj2, where neither obj1 nor obj2 is a base-class subobject, if the underlying bytes ([intro.memory]) making up obj1 are copied into obj2,44 obj2 shall subsequently hold the same value as obj1.
[Example
:
T* t1p;
T* t2p;
    // provided that t2p points to an initialized object ...
std::memcpy(t1p, t2p, sizeof(T));
    // at this point, every subobject of trivially copyable type in *t1p contains
    // the same value as the corresponding subobject in *t2p
end example
]
The object representation of an object of type T is the sequence of N unsigned char objects taken up by the object of type T, where N equals sizeof(T).
The value representation of an object is the set of bits that hold the value of type T.
For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values.45
A class that has been declared but not defined, an enumeration type in certain contexts ([dcl.enum]), or an array of unknown bound or of incomplete element type, is an incompletely-defined object type.46
Incompletely-defined object types and cv void are incomplete types ([basic.fundamental]).
Objects shall not be defined to have an incomplete type.
A class type (such as “class X”) might be incomplete at one point in a translation unit and complete later on; the type “class X” is the same type at both points.
The declared type of an array object might be an array of incomplete class type and therefore incomplete; if the class type is completed later on in the translation unit, the array type becomes complete; the array type at those two points is the same type.
The declared type of an array object might be an array of unknown bound and therefore be incomplete at one point in a translation unit and complete later on; the array types at those two points (“array of unknown bound of T” and “array of N T”) are different types.
The type of a pointer to array of unknown bound, or of a type defined by a typedef declaration to be an array of unknown bound, cannot be completed.
[Example
:
class X;                        // X is an incomplete type
extern X* xp;                   // xp is a pointer to an incomplete type
extern int arr[];               // the type of arr is incomplete
typedef int UNKA[];             // UNKA is an incomplete type
UNKA* arrp;                     // arrp is a pointer to an incomplete type
UNKA** arrpp;

void foo() {
  xp++;                         // ill-formed: X is incomplete
  arrp++;                       // ill-formed: incomplete type
  arrpp++;                      // OK: sizeof UNKA* is known
}

struct X { int i; };            // now X is a complete type
int  arr[10];                   // now the type of arr is complete

X x;
void bar() {
  xp = &x;                      // OK; type is “pointer to X  arrp = &arr;                  // ill-formed: different types
  xp++;                         // OK:  X is complete
  arrp++;                       // ill-formed: UNKA can't be completed
}
end example
]
[Note
:
The rules for declarations and expressions describe in which contexts incomplete types are prohibited.
end note
]
An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not cv void.
Arithmetic types ([basic.fundamental]), enumeration types, pointer types, pointer to member types ([basic.compound]), std​::​nullptr_­t, and cv-qualified ([basic.type.qualifier]) versions of these types are collectively called scalar types.
Scalar types, POD classes (Clause [class]), arrays of such types and cv-qualified versions of these types are collectively called POD types.
Cv-unqualified scalar types, trivially copyable class types (Clause [class]), arrays of such types, and cv-qualified versions of these types are collectively called trivially copyable types.
Scalar types, trivial class types (Clause [class]), arrays of such types and cv-qualified versions of these types are collectively called trivial types.
Scalar types, standard-layout class types (Clause [class]), arrays of such types and cv-qualified versions of these types are collectively called standard-layout types.
A type is a literal type if it is:
  • possibly cv-qualified void; or
  • a scalar type; or
  • a reference type; or
  • an array of literal type; or
  • a possibly cv-qualified class type (Clause [class]) that has all of the following properties:
    • it has a trivial destructor,
    • it is either a closure type ([expr.prim.lambda.closure]), an aggregate type ([dcl.init.aggr]), or has at least one constexpr constructor or constructor template (possibly inherited ([namespace.udecl]) from a base class) that is not a copy or move constructor,
    • if it is a union, at least one of its non-static data members is of non-volatile literal type, and
    • if it is not a union, all of its non-static data members and base classes are of non-volatile literal types.
[Note
:
A literal type is one for which it might be possible to create an object within a constant expression.
It is not a guarantee that it is possible to create such an object, nor is it a guarantee that any object of that type will usable in a constant expression.
end note
]
Two types cv1 T1 and cv2 T2 are layout-compatible types if T1 and T2 are the same type, layout-compatible enumerations ([dcl.enum]), or layout-compatible standard-layout class types ([class.mem]).
By using, for example, the library functions ([headers]) std​::​memcpy or std​::​memmove.
By using, for example, the library functions ([headers]) std​::​memcpy or std​::​memmove.
The intent is that the memory model of C++ is compatible with that of ISO/IEC 9899 Programming Language C.
The size and layout of an instance of an incompletely-defined object type is unknown.

6.9.1 Fundamental types [basic.fundamental]

Objects declared as characters (char) shall be large enough to store any member of the implementation's basic character set.
If a character from this set is stored in a character object, the integral value of that character object is equal to the value of the single character literal form of that character.
It is implementation-defined whether a char object can hold negative values.
Characters can be explicitly declared unsigned or signed.
Plain char, signed char, and unsigned char are three distinct types, collectively called narrow character types.
A char, a signed char, and an unsigned char occupy the same amount of storage and have the same alignment requirements ([basic.align]); that is, they have the same object representation.
For narrow character types, all bits of the object representation participate in the value representation.
[Note
:
A bit-field of narrow character type whose length is larger than the number of bits in the object representation of that type has padding bits; see [class.bit].
end note
]
For unsigned narrow character types, each possible bit pattern of the value representation represents a distinct number.
These requirements do not hold for other types.
In any particular implementation, a plain char object can take on either the same values as a signed char or an unsigned char; which one is implementation-defined.
For each value i of type unsigned char in the range 0 to 255 inclusive, there exists a value j of type char such that the result of an integral conversion ([conv.integral]) from i to char is j, and the result of an integral conversion from j to unsigned char is i.
There are five standard signed integer types : signed char”, “short int”, “int”, “long int”, and “long long int.
In this list, each type provides at least as much storage as those preceding it in the list.
There may also be implementation-defined extended signed integer types.
The standard and extended signed integer types are collectively called signed integer types.
Plain ints have the natural size suggested by the architecture of the execution environment47; the other signed integer types are provided to meet special needs.
For each of the standard signed integer types, there exists a corresponding (but different) standard unsigned integer type: unsigned char”, “unsigned short int”, “unsigned int”, “unsigned long int”, and “unsigned long long int”, each of which occupies the same amount of storage and has the same alignment requirements ([basic.align]) as the corresponding signed integer type48; that is, each signed integer type has the same object representation as its corresponding unsigned integer type.
Likewise, for each of the extended signed integer types there exists a corresponding extended unsigned integer type with the same amount of storage and alignment requirements.
The standard and extended unsigned integer types are collectively called unsigned integer types.
The range of non-negative values of a signed integer type is a subrange of the corresponding unsigned integer type, the representation of the same value in each of the two types is the same, and the value representation of each corresponding signed/unsigned type shall be the same.
The standard signed integer types and standard unsigned integer types are collectively called the standard integer types, and the extended signed integer types and extended unsigned integer types are collectively called the extended integer types.
The signed and unsigned integer types shall satisfy the constraints given in the C standard, section 5.
2.
4.
2.
1.
Unsigned integers shall obey the laws of arithmetic modulo where n is the number of bits in the value representation of that particular size of integer.49
Type wchar_­t is a distinct type whose values can represent distinct codes for all members of the largest extended character set specified among the supported locales ([locale]).
Type wchar_­t shall have the same size, signedness, and alignment requirements ([basic.align]) as one of the other integral types, called its underlying type.
Types char16_­t and char32_­t denote distinct types with the same size, signedness, and alignment as uint_­least16_­t and uint_­least32_­t, respectively, in <cstdint>, called the underlying types.
Values of type bool are either true or false.50
[Note
:
There are no signed, unsigned, short, or long bool types or values.
end note
]
Values of type bool participate in integral promotions ([conv.prom]).
Types bool, char, char16_­t, char32_­t, wchar_­t, and the signed and unsigned integer types are collectively called integral types.51
A synonym for integral type is integer type.
The representations of integral types shall define values by use of a pure binary numeration system.52
[Example
:
This International Standard permits two's complement, ones' complement and signed magnitude representations for integral types.
end example
]
There are three floating-point types: float, double, and long double.
The type double provides at least as much precision as float, and the type long double provides at least as much precision as double.
The set of values of the type float is a subset of the set of values of the type double; the set of values of the type double is a subset of the set of values of the type long double.
The value representation of floating-point types is implementation-defined.
[Note
:
This International Standard imposes no requirements on the accuracy of floating-point operations; see also [support.limits].
end note
]
Integral and floating types are collectively called arithmetic types.
Specializations of the standard library template std​::​numeric_­limits ([support.limits]) shall specify the maximum and minimum values of each arithmetic type for an implementation.
A type cv void is an incomplete type that cannot be completed; such a type has an empty set of values.
It is used as the return type for functions that do not return a value.
Any expression can be explicitly converted to type cv void ([expr.cast]).
An expression of type cv void shall be used only as an expression statement ([stmt.expr]), as an operand of a comma expression ([expr.comma]), as a second or third operand of ?: ([expr.cond]), as the operand of typeid, noexcept, or decltype, as the expression in a return statement ([stmt.return]) for a function with the return type cv void, or as the operand of an explicit conversion to type cv void.
A value of type std​::​nullptr_­t is a null pointer constant ([conv.ptr]).
Such values participate in the pointer and the pointer to member conversions ([conv.ptr], [conv.mem]).
sizeof(std​::​nullptr_­t) shall be equal to sizeof(void*).
[Note
:
Even if the implementation defines two or more basic types to have the same value representation, they are nevertheless different types.
end note
]
int must also be large enough to contain any value in the range [INT_­MIN, INT_­MAX], as defined in the header <climits>.
See [dcl.type.simple] regarding the correspondence between types and the sequences of type-specifiers that designate them.
This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.
Using a bool value in ways described by this International Standard as “undefined”, such as by examining the value of an uninitialized automatic object, might cause it to behave as if it is neither true nor false.
Therefore, enumerations ([dcl.enum]) are not integral; however, enumerations can be promoted to integral types as specified in [conv.prom].
A positional representation for integers that uses the binary digits 0 and 1, in which the values represented by successive bits are additive, begin with 1, and are multiplied by successive integral power of 2, except perhaps for the bit with the highest position.
(Adapted from the American National Dictionary for Information Processing Systems.)

6.9.2 Compound types [basic.compound]

Compound types can be constructed in the following ways:
These methods of constructing types can be applied recursively; restrictions are mentioned in [dcl.ptr], [dcl.array], [dcl.fct], and [dcl.ref].
Constructing a type such that the number of bytes in its object representation exceeds the maximum value representable in the type std​::​size_­t ([support.types]) is ill-formed.
The type of a pointer to cv void or a pointer to an object type is called an object pointer type.
[Note
:
A pointer to void does not have a pointer-to-object type, however, because void is not an object type.
end note
]
The type of a pointer that can designate a function is called a function pointer type.
A pointer to objects of type T is referred to as a “pointer to T.
[Example
:
A pointer to an object of type int is referred to as “pointer to int” and a pointer to an object of class X is called a “pointer to X.
end example
]
Except for pointers to static members, text referring to “pointers” does not apply to pointers to members.
Pointers to incomplete types are allowed although there are restrictions on what can be done with them ([basic.align]).
Every value of pointer type is one of the following:
A value of a pointer type that is a pointer to or past the end of an object represents the address of the first byte in memory ([intro.memory]) occupied by the object54 or the first byte in memory after the end of the storage occupied by the object, respectively.
[Note
:
A pointer past the end of an object ([expr.add]) is not considered to point to an unrelated object of the object's type that might be located at that address.
A pointer value becomes invalid when the storage it denotes reaches the end of its storage duration; see [basic.stc].
end note
]
For purposes of pointer arithmetic ([expr.add]) and comparison ([expr.rel], [expr.eq]), a pointer past the end of the last element of an array x of n elements is considered to be equivalent to a pointer to a hypothetical element x[n].
The value representation of pointer types is implementation-defined.
Pointers to layout-compatible types shall have the same value representation and alignment requirements ([basic.align]).
[Note
:
Pointers to over-aligned types ([basic.align]) have no special representation, but their range of valid values is restricted by the extended alignment requirement.
end note
]
Two objects a and b are pointer-interconvertible if:
  • they are the same object, or
  • one is a standard-layout union object and the other is a non-static data member of that object ([class.union]), or
  • one is a standard-layout class object and the other is the first non-static data member of that object, or, if the object has no non-static data members, the first base class subobject of that object ([class.mem]), or
  • there exists an object c such that a and c are pointer-interconvertible, and c and b are pointer-interconvertible.
If two objects are pointer-interconvertible, then they have the same address, and it is possible to obtain a pointer to one from a pointer to the other via a reinterpret_­cast ([expr.reinterpret.cast]).
[Note
:
An array object and its first element are not pointer-interconvertible, even though they have the same address.
end note
]
A pointer to cv-qualified ([basic.type.qualifier]) or cv-unqualified void can be used to point to objects of unknown type.
Such a pointer shall be able to hold any object pointer.
An object of type cv void* shall have the same representation and alignment requirements as cv char*.
Static class members are objects or functions, and pointers to them are ordinary pointers to objects or functions.
For an object that is not within its lifetime, this is the first byte in memory that it will occupy or used to occupy.

6.9.3 CV-qualifiers [basic.type.qualifier]

Each type which is a cv-unqualified complete or incomplete object type or is void ([basic.types]) has three corresponding cv-qualified versions of its type: a const-qualified version, a volatile-qualified version, and a const-volatile-qualified version.
The type of an object ([intro.object]) includes the cv-qualifiers specified in the decl-specifier-seq, declarator, type-id, or new-type-id when the object is created.
  • A const object is an object of type const T or a non-mutable subobject of such an object.
  • A volatile object is an object of type volatile T, a subobject of such an object, or a mutable subobject of a const volatile object.
  • A const volatile object is an object of type const volatile T, a non-mutable subobject of such an object, a const subobject of a volatile object, or a non-mutable volatile subobject of a const object.
The cv-qualified or cv-unqualified versions of a type are distinct types; however, they shall have the same representation and alignment requirements ([basic.align]).55
A compound type ([basic.compound]) is not cv-qualified by the cv-qualifiers (if any) of the types from which it is compounded.
Any cv-qualifiers applied to an array type affect the array element type ([dcl.array]).
See [dcl.fct] and [class.this] regarding function types that have cv-qualifiers.
There is a partial ordering on cv-qualifiers, so that a type can be said to be more cv-qualified than another.
Table 10 shows the relations that constitute this ordering.
Table 10 — Relations on const and volatile
no cv-qualifier
<
const
no cv-qualifier
<
volatile
no cv-qualifier
<
const volatile
const
<
const volatile
volatile
<
const volatile
In this International Standard, the notation cv (or cv1, cv2, etc.)
, used in the description of types, represents an arbitrary set of cv-qualifiers, i.e., one of {const}, {volatile}, {const, volatile}, or the empty set.
For a type cv T, the top-level cv-qualifiers of that type are those denoted by cv.
[Example
:
The type corresponding to the type-id const int& has no top-level cv-qualifiers.
The type corresponding to the type-id volatile int * const has the top-level cv-qualifier const.
For a class type C, the type corresponding to the type-id void (C​::​* volatile)(int) const has the top-level cv-qualifier volatile.
end example
]
Cv-qualifiers applied to an array type attach to the underlying element type, so the notation “cv T”, where T is an array type, refers to an array whose elements are so-qualified.
An array type whose elements are cv-qualified is also considered to have the same cv-qualifications as its elements.
[Example
:
typedef char CA[5];
typedef const char CC;
CC arr1[5] = { 0 };
const CA arr2 = { 0 };
The type of both arr1 and arr2 is “array of 5 const char”, and the array type is considered to be const-qualified.
end example
]
The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and non-static data members of unions.

6.10 Lvalues and rvalues [basic.lval]

Expressions are categorized according to the taxonomy in Figure [fig:categories].
categories expression expression glvalue glvalue expression->glvalue rvalue rvalue expression->rvalue lvalue lvalue glvalue->lvalue xvalue xvalue glvalue->xvalue rvalue->xvalue prvalue prvalue rvalue->prvalue
Figure 1 — Expression category taxonomy
  • A glvalue is an expression whose evaluation determines the identity of an object, bit-field, or function.
  • A prvalue is an expression whose evaluation initializes an object or a bit-field, or computes the value of the operand of an operator, as specified by the context in which it appears.
  • An xvalue is a glvalue that denotes an object or bit-field whose resources can be reused (usually because it is near the end of its lifetime).
    [Example
    :
    Certain kinds of expressions involving rvalue references ([dcl.ref]) yield xvalues, such as a call to a function whose return type is an rvalue reference or a cast to an rvalue reference type.
    end example
    ]
  • An lvalue is a glvalue that is not an xvalue.
  • An rvalue is a prvalue or an xvalue.
[Note
:
Historically, lvalues and rvalues were so-called because they could appear on the left- and right-hand side of an assignment (although this is no longer generally true); glvalues are “generalized” lvalues, prvalues are “pure” rvalues, and xvalues are “eXpiring” lvalues.
Despite their names, these terms classify expressions, not values.
end note
]
Every expression belongs to exactly one of the fundamental classifications in this taxonomy: lvalue, xvalue, or prvalue.
This property of an expression is called its value category.
[Note
:
The discussion of each built-in operator in Clause [expr] indicates the category of the value it yields and the value categories of the operands it expects.
For example, the built-in assignment operators expect that the left operand is an lvalue and that the right operand is a prvalue and yield an lvalue as the result.
User-defined operators are functions, and the categories of values they expect and yield are determined by their parameter and return types.
end note
]
The result of a prvalue is the value that the expression stores into its context.
A prvalue whose result is the value V is sometimes said to have or name the value V.
The result object of a prvalue is the object initialized by the prvalue; a prvalue that is used to compute the value of an operand of an operator or that has type cv void has no result object.
[Note
:
Except when the prvalue is the operand of a decltype-specifier, a prvalue of class or array type always has a result object.
For a discarded prvalue, a temporary object is materialized; see Clause [expr].
end note
]
The result of a glvalue is the entity denoted by the expression.
[Note
:
Whenever a glvalue appears in a context where a prvalue is expected, the glvalue is converted to a prvalue; see [conv.lval], [conv.array], and [conv.func].
An attempt to bind an rvalue reference to an lvalue is not such a context; see [dcl.init.ref].
end note
]
[Note
:
There are no prvalue bit-fields; if a bit-field is converted to a prvalue ([conv.lval]), a prvalue of the type of the bit-field is created, which might then be promoted ([conv.prom]).
end note
]
[Note
:
Whenever a prvalue appears in a context where a glvalue is expected, the prvalue is converted to an xvalue; see [conv.rval].
end note
]
The discussion of reference initialization in [dcl.init.ref] and of temporaries in [class.temporary] indicates the behavior of lvalues and rvalues in other significant contexts.
Unless otherwise indicated ([expr.call]), a prvalue shall always have complete type or the void type.
A glvalue shall not have type cv void.
[Note
:
A glvalue may have complete or incomplete non-void type.
Class and array prvalues can have cv-qualified types; other prvalues always have cv-unqualified types.
See Clause [expr].
end note
]
An lvalue is modifiable unless its type is const-qualified or is a function type.
[Note
:
A program that attempts to modify an object through a nonmodifiable lvalue expression or through an rvalue expression is ill-formed ([expr.ass], [expr.post.incr], [expr.pre.incr]).
end note
]
If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:56
  • the dynamic type of the object,
  • a cv-qualified version of the dynamic type of the object,
  • a type similar (as defined in [conv.qual]) to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
  • an aggregate or union type that includes one of the aforementioned types among its elements or non-static data members (including, recursively, an element or non-static data member of a subaggregate or contained union),
  • a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
  • a char, unsigned char, or std​::​byte type.
The intent of this list is to specify those circumstances in which an object may or may not be aliased.

6.11 Alignment [basic.align]

Object types have alignment requirements ([basic.fundamental], [basic.compound]) which place restrictions on the addresses at which an object of that type may be allocated.
An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated.
An object type imposes an alignment requirement on every object of that type; stricter alignment can be requested using the alignment specifier ([dcl.align]).
A fundamental alignment is represented by an alignment less than or equal to the greatest alignment supported by the implementation in all contexts, which is equal to alignof(std​::​max_­align_­t) ([support.types]).
The alignment required for a type might be different when it is used as the type of a complete object and when it is used as the type of a subobject.
[Example
:
struct B { long double d; };
struct D : virtual B { char c; };
When D is the type of a complete object, it will have a subobject of type B, so it must be aligned appropriately for a long double.
If D appears as a subobject of another object that also has B as a virtual base class, the B subobject might be part of a different subobject, reducing the alignment requirements on the D subobject.
end example
]
The result of the alignof operator reflects the alignment requirement of the type in the complete-object case.
An extended alignment is represented by an alignment greater than alignof(std​::​max_­align_­t).
It is implementation-defined whether any extended alignments are supported and the contexts in which they are supported ([dcl.align]).
A type having an extended alignment requirement is an over-aligned type.
[Note
:
Every over-aligned type is or contains a class type to which extended alignment applies (possibly through a non-static data member).
end note
]
A new-extended alignment is represented by an alignment greater than __STDCPP_­DEFAULT_­NEW_­ALIGNMENT__ ([cpp.predefined]).
Alignments are represented as values of the type std​::​size_­t.
Valid alignments include only those values returned by an alignof expression for the fundamental types plus an additional implementation-defined set of values, which may be empty.
Every alignment value shall be a non-negative integral power of two.
Alignments have an order from weaker to stronger or stricter alignments.
Stricter alignments have larger alignment values.
An address that satisfies an alignment requirement also satisfies any weaker valid alignment requirement.
The alignment requirement of a complete type can be queried using an alignof expression ([expr.alignof]).
Furthermore, the narrow character types ([basic.fundamental]) shall have the weakest alignment requirement.
[Note
:
This enables the narrow character types to be used as the underlying type for an aligned memory area ([dcl.align]).
end note
]
Comparing alignments is meaningful and provides the obvious results:
  • Two alignments are equal when their numeric values are equal.
  • Two alignments are different when their numeric values are not equal.
  • When an alignment is larger than another it represents a stricter alignment.
[Note
:
The runtime pointer alignment function ([ptr.align]) can be used to obtain an aligned pointer within a buffer; the aligned-storage templates in the library ([meta.trans.other]) can be used to obtain aligned storage.
end note
]
If a request for a specific extended alignment in a specific context is not supported by an implementation, the program is ill-formed.

7 Standard conversions [conv]

Standard conversions are implicit conversions with built-in meaning.
Clause [conv] enumerates the full set of such conversions.
A standard conversion sequence is a sequence of standard conversions in the following order:
  • Zero or one conversion from the following set: lvalue-to-rvalue conversion, array-to-pointer conversion, and function-to-pointer conversion.
  • Zero or one conversion from the following set: integral promotions, floating-point promotion, integral conversions, floating-point conversions, floating-integral conversions, pointer conversions, pointer to member conversions, and boolean conversions.
  • Zero or one function pointer conversion.
  • Zero or one qualification conversion.
[Note
:
A standard conversion sequence can be empty, i.e., it can consist of no conversions.
end note
]
A standard conversion sequence will be applied to an expression if necessary to convert it to a required destination type.
[Note
:
Expressions with a given type will be implicitly converted to other types in several contexts:
  • When used as operands of operators.
    The operator's requirements for its operands dictate the destination type (Clause [expr]).
  • When used in the condition of an if statement or iteration statement ([stmt.select], [stmt.iter]).
    The destination type is bool.
  • When used in the expression of a switch statement.
    The destination type is integral ([stmt.select]).
  • When used as the source expression for an initialization (which includes use as an argument in a function call and use as the expression in a return statement).
    The type of the entity being initialized is (generally) the destination type.
end note
]
An expression e can be implicitly converted to a type T if and only if the declaration T t=e; is well-formed, for some invented temporary variable t ([dcl.init]).
Certain language constructs require that an expression be converted to a Boolean value.
An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t ([dcl.init]).
Certain language constructs require conversion to a value having one of a specified set of types appropriate to the construct.
An expression e of class type E appearing in such a context is said to be contextually implicitly converted to a specified type T and is well-formed if and only if e can be implicitly converted to a type T that is determined as follows: E is searched for non-explicit conversion functions whose return type is cv T or reference to cv T such that T is allowed by the context.
There shall be exactly one such T.
The effect of any implicit conversion is the same as performing the corresponding declaration and initialization and then using the temporary variable as the result of the conversion.
The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type ([dcl.ref]), an xvalue if T is an rvalue reference to object type, and a prvalue otherwise.
The expression e is used as a glvalue if and only if the initialization uses it as a glvalue.
[Note
:
For class types, user-defined conversions are considered as well; see [class.conv].
In general, an implicit conversion sequence ([over.best.ics]) consists of a standard conversion sequence followed by a user-defined conversion followed by another standard conversion sequence.
end note
]
[Note
:
There are some contexts where certain conversions are suppressed.
For example, the lvalue-to-rvalue conversion is not done on the operand of the unary & operator.
Specific exceptions are given in the descriptions of those operators and contexts.
end note
]

7.1 Lvalue-to-rvalue conversion [conv.lval]

A glvalue ([basic.lval]) of a non-function, non-array type T can be converted to a prvalue.57
If T is an incomplete type, a program that necessitates this conversion is ill-formed.
If T is a non-class type, the type of the prvalue is the cv-unqualified version of T.
Otherwise, the type of the prvalue is T.58
When an lvalue-to-rvalue conversion is applied to an expression e, and either
  • e is not potentially evaluated, or
  • the evaluation of e results in the evaluation of a member ex of the set of potential results of e, and ex names a variable x that is not odr-used by ex ([basic.def.odr]),
the value contained in the referenced object is not accessed.
[Example
:
struct S { int n; };
auto f() {
  S x { 1 };
  constexpr S y { 2 };
  return [&](bool b) { return (b ? y : x).n; };
}
auto g = f();
int m = g(false);   // undefined behavior due to access of x.n outside its lifetime
int n = g(true);    // OK, does not access y.n
end example
]
The result of the conversion is determined according to the following rules:
  • If T is cv std​::​nullptr_­t, the result is a null pointer constant ([conv.ptr]).
    [Note
    :
    Since no value is fetched from memory, there is no side effect for a volatile access ([intro.execution]), and an inactive member of a union ([class.union]) may be accessed.
    end note
    ]
  • Otherwise, if T has a class type, the conversion copy-initializes the result object from the glvalue.
  • Otherwise, if the object to which the glvalue refers contains an invalid pointer value ([basic.stc.dynamic.deallocation], [basic.stc.dynamic.safety]), the behavior is implementation-defined.
  • Otherwise, the value contained in the object indicated by the glvalue is the prvalue result.
[Note
:
See also [basic.lval].
end note
]
For historical reasons, this conversion is called the “lvalue-to-rvalue” conversion, even though that name does not accurately reflect the taxonomy of expressions described in [basic.lval].
In C++ class and array prvalues can have cv-qualified types.
This differs from ISO C, in which non-lvalues never have cv-qualified types.

7.2 Array-to-pointer conversion [conv.array]

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T.
The temporary materialization conversion ([conv.rval]) is applied.
The result is a pointer to the first element of the array.

7.3 Function-to-pointer conversion [conv.func]

An lvalue of function type T can be converted to a prvalue of type “pointer to T.
The result is a pointer to the function.59
[Note
:
See [over.over] for additional rules for the case where the function is overloaded.
end note
]
This conversion never applies to non-static member functions because an lvalue that refers to a non-static member function cannot be obtained.

7.4 Temporary materialization conversion [conv.rval]

A prvalue of type T can be converted to an xvalue of type T.
This conversion initializes a temporary object ([class.temporary]) of type T from the prvalue by evaluating the prvalue with the temporary object as its result object, and produces an xvalue denoting the temporary object.
T shall be a complete type.
[Note
:
If T is a class type (or array thereof), it must have an accessible and non-deleted destructor; see [class.dtor].
end note
]
[Example
:
struct X { int n; };
int k = X().n;      // OK, X() prvalue is converted to xvalue
end example
]

7.5 Qualification conversions [conv.qual]

A cv-decomposition of a type T is a sequence of and such that T is U” for , where each is a set of cv-qualifiers ([basic.type.qualifier]), and each is “pointer to” ([dcl.ptr]), “pointer to member of class of type” ([dcl.mptr]), “array of ”, or “array of unknown bound of” ([dcl.array]).
If designates an array, the cv-qualifiers on the element type are also taken as the cv-qualifiers of the array.
[Example
:
The type denoted by the type-id const int ** has two cv-decompositions, taking U as “int” and as “pointer to const int.
end example
]
The n-tuple of cv-qualifiers after the first one in the longest cv-decomposition of T, that is, , is called the cv-qualification signature of T.
Two types and are similar if they have cv-decompositions with the same n such that corresponding components are the same and the types denoted by U are the same.
A prvalue expression of type can be converted to type if the following conditions are satisfied, where denotes the cv-qualifiers in the cv-qualification signature of :60
  • and are similar.
  • For every , if const is in then const is in , and similarly for volatile.
  • If the and are different, then const is in every for .
[Note
:
If a program could assign a pointer of type T** to a pointer of type const T** (that is, if line #1 below were allowed), a program could inadvertently modify a const object (as it is done on line #2).
For example,
int main() {
  const char c = 'c';
  char* pc;
  const char** pcc = &pc;       // #1: not allowed
  *pcc = &c;
  *pc = 'C';                    // #2: modifies a const object
}
end note
]
[Note
:
A prvalue of type “pointer to cv1 T” can be converted to a prvalue of type “pointer to cv2 T” if “cv2 T” is more cv-qualified than “cv1 T.
A prvalue of type “pointer to member of X of type cv1 T” can be converted to a prvalue of type “pointer to member of X of type cv2 T” if “cv2 T” is more cv-qualified than “cv1 T.
end note
]
[Note
:
Function types (including those used in pointer to member function types) are never cv-qualified ([dcl.fct]).
end note
]
These rules ensure that const-safety is preserved by the conversion.

7.6 Integral promotions [conv.prom]

A prvalue of an integer type other than bool, char16_­t, char32_­t, or wchar_­t whose integer conversion rank ([conv.rank]) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.
A prvalue of type char16_­t, char32_­t, or wchar_­t ([basic.fundamental]) can be converted to a prvalue of the first of the following types that can represent all the values of its underlying type: int, unsigned int, long int, unsigned long int, long long int, or unsigned long long int.
If none of the types in that list can represent all the values of its underlying type, a prvalue of type char16_­t, char32_­t, or wchar_­t can be converted to a prvalue of its underlying type.
A prvalue of an unscoped enumeration type whose underlying type is not fixed ([dcl.enum]) can be converted to a prvalue of the first of the following types that can represent all the values of the enumeration (i.e., the values in the range to as described in [dcl.enum]): int, unsigned int, long int, unsigned long int, long long int, or unsigned long long int.
If none of the types in that list can represent all the values of the enumeration, a prvalue of an unscoped enumeration type can be converted to a prvalue of the extended integer type with lowest integer conversion rank ([conv.rank]) greater than the rank of long long in which all the values of the enumeration can be represented.
If there are two such extended types, the signed one is chosen.
A prvalue of an unscoped enumeration type whose underlying type is fixed ([dcl.enum]) can be converted to a prvalue of its underlying type.
Moreover, if integral promotion can be applied to its underlying type, a prvalue of an unscoped enumeration type whose underlying type is fixed can also be converted to a prvalue of the promoted underlying type.
A prvalue for an integral bit-field ([class.bit]) can be converted to a prvalue of type int if int can represent all the values of the bit-field; otherwise, it can be converted to unsigned int if unsigned int can represent all the values of the bit-field.
If the bit-field is larger yet, no integral promotion applies to it.
If the bit-field has an enumerated type, it is treated as any other value of that type for promotion purposes.
A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.
These conversions are called integral promotions.

7.7 Floating-point promotion [conv.fpprom]

A prvalue of type float can be converted to a prvalue of type double.
The value is unchanged.
This conversion is called floating-point promotion.

7.8 Integral conversions [conv.integral]

A prvalue of an integer type can be converted to a prvalue of another integer type.
A prvalue of an unscoped enumeration type can be converted to a prvalue of an integer type.
If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo where n is the number of bits used to represent the unsigned type).
[Note
:
In a two's complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation).
end note
]
If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined.
If the destination type is bool, see [conv.bool].
If the source type is bool, the value false is converted to zero and the value true is converted to one.
The conversions allowed as integral promotions are excluded from the set of integral conversions.

7.9 Floating-point conversions [conv.double]

A prvalue of floating-point type can be converted to a prvalue of another floating-point type.
If the source value can be exactly represented in the destination type, the result of the conversion is that exact representation.
If the source value is between two adjacent destination values, the result of the conversion is an implementation-defined choice of either of those values.
Otherwise, the behavior is undefined.
The conversions allowed as floating-point promotions are excluded from the set of floating-point conversions.

7.10 Floating-integral conversions [conv.fpint]

A prvalue of a floating-point type can be converted to a prvalue of an integer type.
The conversion truncates; that is, the fractional part is discarded.
The behavior is undefined if the truncated value cannot be represented in the destination type.
[Note
:
If the destination type is bool, see [conv.bool].
end note
]
A prvalue of an integer type or of an unscoped enumeration type can be converted to a prvalue of a floating-point type.
The result is exact if possible.
If the value being converted is in the range of values that can be represented but the value cannot be represented exactly, it is an implementation-defined choice of either the next lower or higher representable value.
[Note
:
Loss of precision occurs if the integral value cannot be represented exactly as a value of the floating type.
end note
]
If the value being converted is outside the range of values that can be represented, the behavior is undefined.
If the source type is bool, the value false is converted to zero and the value true is converted to one.

7.11 Pointer conversions [conv.ptr]

A null pointer constant is an integer literal ([lex.icon]) with value zero or a prvalue of type std​::​nullptr_­t.
A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type.
Such a conversion is called a null pointer conversion.
Two null pointer values of the same type shall compare equal.
The conversion of a null pointer constant to a pointer to cv-qualified type is a single conversion, and not the sequence of a pointer conversion followed by a qualification conversion ([conv.qual]).
A null pointer constant of integral type can be converted to a prvalue of type std​::​nullptr_­t.
[Note
:
The resulting prvalue is not a null pointer value.
end note
]
A prvalue of type “pointer to cv T”, where T is an object type, can be converted to a prvalue of type “pointer to cv void.
The pointer value ([basic.compound]) is unchanged by this conversion.
A prvalue of type “pointer to cv D”, where D is a class type, can be converted to a prvalue of type “pointer to cv B”, where B is a base class (Clause [class.derived]) of D.
If B is an inaccessible (Clause [class.access]) or ambiguous ([class.member.lookup]) base class of D, a program that necessitates this conversion is ill-formed.
The result of the conversion is a pointer to the base class subobject of the derived class object.
The null pointer value is converted to the null pointer value of the destination type.

7.12 Pointer to member conversions [conv.mem]

A null pointer constant ([conv.ptr]) can be converted to a pointer to member type; the result is the null member pointer value of that type and is distinguishable from any pointer to member not created from a null pointer constant.
Such a conversion is called a null member pointer conversion.
Two null member pointer values of the same type shall compare equal.
The conversion of a null pointer constant to a pointer to member of cv-qualified type is a single conversion, and not the sequence of a pointer to member conversion followed by a qualification conversion ([conv.qual]).
A prvalue of type “pointer to member of B of type cv T”, where B is a class type, can be converted to a prvalue of type “pointer to member of D of type cv T”, where D is a derived class (Clause [class.derived]) of B.
If B is an inaccessible (Clause [class.access]), ambiguous ([class.member.lookup]), or virtual ([class.mi]) base class of D, or a base class of a virtual base class of D, a program that necessitates this conversion is ill-formed.
The result of the conversion refers to the same member as the pointer to member before the conversion took place, but it refers to the base class member as if it were a member of the derived class.
The result refers to the member in D's instance of B.
Since the result has type “pointer to member of D of type cv T”, indirection through it with a D object is valid.
The result is the same as if indirecting through the pointer to member of B with the B subobject of D.
The null member pointer value is converted to the null member pointer value of the destination type.61
The rule for conversion of pointers to members (from pointer to member of base to pointer to member of derived) appears inverted compared to the rule for pointers to objects (from pointer to derived to pointer to base) ([conv.ptr], Clause [class.derived]).
This inversion is necessary to ensure type safety.
Note that a pointer to member is not an object pointer or a function pointer and the rules for conversions of such pointers do not apply to pointers to members.
In particular, a pointer to member cannot be converted to a void*.

7.13 Function pointer conversions [conv.fctptr]

A prvalue of type “pointer to noexcept function” can be converted to a prvalue of type “pointer to function”.
The result is a pointer to the function.
A prvalue of type “pointer to member of type noexcept function” can be converted to a prvalue of type “pointer to member of type function”.
The result points to the member function.
[Example
:
  void (*p)();
  void (**pp)() noexcept = &p;  // error: cannot convert to pointer to noexcept function

  struct S { typedef void (*p)(); operator p(); };
  void (*q)() noexcept = S();   // error: cannot convert to pointer to noexcept function
end example
]

7.14 Boolean conversions [conv.bool]

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool.
A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.
For direct-initialization ([dcl.init]), a prvalue of type std​::​nullptr_­t can be converted to a prvalue of type bool; the resulting value is false.

7.15 Integer conversion rank [conv.rank]

Every integer type has an integer conversion rank defined as follows:
  • No two signed integer types other than char and signed char (if char is signed) shall have the same rank, even if they have the same representation.
  • The rank of a signed integer type shall be greater than the rank of any signed integer type with a smaller size.
  • The rank of long long int shall be greater than the rank of long int, which shall be greater than the rank of int, which shall be greater than the rank of short int, which shall be greater than the rank of signed char.
  • The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type.
  • The rank of any standard integer type shall be greater than the rank of any extended integer type with the same size.
  • The rank of char shall equal the rank of signed char and unsigned char.
  • The rank of bool shall be less than the rank of all other standard integer types.
  • The ranks of char16_­t, char32_­t, and wchar_­t shall equal the ranks of their underlying types ([basic.fundamental]).
  • The rank of any extended signed integer type relative to another extended signed integer type with the same size is implementation-defined, but still subject to the other rules for determining the integer conversion rank.
  • For all integer types T1, T2, and T3, if T1 has greater rank than T2 and T2 has greater rank than T3, then T1 shall have greater rank than T3.
[Note
:
The integer conversion rank is used in the definition of the integral promotions ([conv.prom]) and the usual arithmetic conversions (Clause [expr]).
end note
]

8 Expressions [expr]

[Note
:
Clause [expr] defines the syntax, order of evaluation, and meaning of expressions.62
An expression is a sequence of operators and operands that specifies a computation.
An expression can result in a value and can cause side effects.
end note
]
[Note
:
Operators can be overloaded, that is, given meaning when applied to expressions of class type (Clause [class]) or enumeration type ([dcl.enum]).
Uses of overloaded operators are transformed into function calls as described in [over.oper].
Overloaded operators obey the rules for syntax and evaluation order specified in Clause [expr], but the requirements of operand type and value category are replaced by the rules for function call.
Relations between operators, such as ++a meaning a+=1, are not guaranteed for overloaded operators ([over.oper]).
end note
]
Clause [expr] defines the effects of operators when applied to types for which they have not been overloaded.
Operator overloading shall not modify the rules for the built-in operators, that is, for operators applied to types for which they are defined by this Standard.
However, these built-in operators participate in overload resolution, and as part of that process user-defined conversions will be considered where necessary to convert the operands to types appropriate for the built-in operator.
If a built-in operator is selected, such conversions will be applied to the operands before the operation is considered further according to the rules in Clause [expr]; see [over.match.oper], [over.built].
If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.
[Note
:
Treatment of division by zero, forming a remainder using a zero divisor, and all floating-point exceptions vary among machines, and is sometimes adjustable by a library function.
end note
]
If an expression initially has the type “reference to T” ([dcl.ref], [dcl.init.ref]), the type is adjusted to T prior to any further analysis.
The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.
[Note
:
Before the lifetime of the reference has started or after it has ended, the behavior is undefined (see [basic.life]).
end note
]
If a prvalue initially has the type “cv T”, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis.
[Note
:
An expression is an xvalue if it is:
  • the result of calling a function, whether implicitly or explicitly, whose return type is an rvalue reference to object type,
  • a cast to an rvalue reference to object type,
  • a class member access expression designating a non-static data member of non-reference type in which the object expression is an xvalue, or
  • a .* pointer-to-member expression in which the first operand is an xvalue and the second operand is a pointer to data member.
In general, the effect of this rule is that named rvalue references are treated as lvalues and unnamed rvalue references to objects are treated as xvalues; rvalue references to functions are treated as lvalues whether named or not.
end note
]
[Example
:
struct A {
  int m;
};
A&& operator+(A, A);
A&& f();

A a;
A&& ar = static_cast<A&&>(a);
The expressions f(), f().m, static_­cast<A&&>(a), and a + a are xvalues.
The expression ar is an lvalue.
end example
]
An unevaluated operand is not evaluated.
[Note
:
In an unevaluated operand, a non-static class member may be named ([expr.prim]) and naming of objects or functions does not, by itself, require that a definition be provided ([basic.def.odr]).
An unevaluated operand is considered a full-expression ([intro.execution]).
end note
]
Whenever a glvalue expression appears as an operand of an operator that expects a prvalue for that operand, the lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), or function-to-pointer ([conv.func]) standard conversions are applied to convert the expression to a prvalue.
[Note
:
Because cv-qualifiers are removed from the type of an expression of non-class type when the expression is converted to a prvalue, an lvalue expression of type const int can, for example, be used where a prvalue expression of type int is required.
end note
]
Whenever a prvalue expression appears as an operand of an operator that expects a glvalue for that operand, the temporary materialization conversion ([conv.rval]) is applied to convert the expression to an xvalue.
Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way.
The purpose is to yield a common type, which is also the type of the result.
This pattern is called the usual arithmetic conversions, which are defined as follows:
  • If either operand is of scoped enumeration type ([dcl.enum]), no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.
  • If either operand is of type long double, the other shall be converted to long double.
  • Otherwise, if either operand is double, the other shall be converted to double.
  • Otherwise, if either operand is float, the other shall be converted to float.
  • Otherwise, the integral promotions ([conv.prom]) shall be performed on both operands.63
    Then the following rules shall be applied to the promoted operands:
    • If both operands have the same type, no further conversion is needed.
    • Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank shall be converted to the type of the operand with greater rank.
    • Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.
    • Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type shall be converted to the type of the operand with signed integer type.
    • Otherwise, both operands shall be converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
In some contexts, an expression only appears for its side effects.
Such an expression is called a discarded-value expression.
The array-to-pointer ([conv.array]) and function-to-pointer ([conv.func]) standard conversions are not applied.
The lvalue-to-rvalue conversion ([conv.lval]) is applied if and only if the expression is a glvalue of volatile-qualified type and it is one of the following:
[Note
:
Using an overloaded operator causes a function call; the above covers only operators with built-in meaning.
end note
]
If the expression is a prvalue after this optional conversion, the temporary materialization conversion ([conv.rval]) is applied.
[Note
:
If the expression is an lvalue of class type, it must have a volatile copy constructor to initialize the temporary that is the result object of the lvalue-to-rvalue conversion.
end note
]
The glvalue expression is evaluated and its value is discarded.
The values of the floating operands and the results of floating expressions may be represented in greater precision and range than that required by the type; the types are not changed thereby.64
The cv-combined type of two types T1 and T2 is a type T3 similar to T1 whose cv-qualification signature ([conv.qual]) is:
  • for every , is the union of and ;
  • if the resulting is different from or , then const is added to every for .
[Note
:
Given similar types T1 and T2, this construction ensures that both can be converted to T3.
end note
]
The composite pointer type of two operands p1 and p2 having types T1 and T2, respectively, where at least one is a pointer or pointer to member type or std​::​nullptr_­t, is:
  • if both p1 and p2 are null pointer constants, std​::​nullptr_­t;
  • if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
  • if T1 or T2 is “pointer to cv1 void” and the other type is “pointer to cv2 T”, where T is an object type or void, “pointer to cv12 void”, where cv12 is the union of cv1 and cv2;
  • if T1 or T2 is “pointer to noexcept function” and the other type is “pointer to function”, where the function types are otherwise the same, “pointer to function”;
  • if T1 is “pointer to cv1 C1” and T2 is “pointer to cv2 C2”, where C1 is reference-related to C2 or C2 is reference-related to C1 ([dcl.init.ref]), the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, respectively;
  • if T1 is “pointer to member of C1 of type cv1 U1” and T2 is “pointer to member of C2 of type cv2 U2” where C1 is reference-related to C2 or C2 is reference-related to C1 ([dcl.init.ref]), the cv-combined type of T2 and T1 or the cv-combined type of T1 and T2, respectively;
  • if T1 and T2 are similar types ([conv.qual]), the cv-combined type of T1 and T2;
  • otherwise, a program that necessitates the determination of a composite pointer type is ill-formed.
[Example
:
typedef void *p;
typedef const int *q;
typedef int **pi;
typedef const int **pci;
The composite pointer type of p and q is “pointer to const void”; the composite pointer type of pi and pci is “pointer to const pointer to const int.
end example
]
The precedence of operators is not directly specified, but it can be derived from the syntax.
As a consequence, operands of type bool, char16_­t, char32_­t, wchar_­t, or an enumerated type are converted to some integral type.
The cast and assignment operators must still perform their specific conversions as described in [expr.cast], [expr.static.cast] and [expr.ass].

8.1 Primary expressions [expr.prim]

8.1.1 Literals [expr.prim.literal]

A literal is a primary expression.
Its type depends on its form ([lex.literal]).
A string literal is an lvalue; all other literals are prvalues.

8.1.2 This [expr.prim.this]

The keyword this names a pointer to the object for which a non-static member function ([class.this]) is invoked or a non-static data member's initializer ([class.mem]) is evaluated.
If a declaration declares a member function or member function template of a class X, the expression this is a prvalue of type “pointer to cv-qualifier-seq X” between the optional cv-qualifier-seq and the end of the function-definition, member-declarator, or declarator.
It shall not appear before the optional cv-qualifier-seq and it shall not appear within the declaration of a static member function (although its type and value category are defined within a static member function as they are within a non-static member function).
[Note
:
This is because declaration matching does not occur until the complete declarator is known.
end note
]
Unlike the object expression in other contexts, *this is not required to be of complete type for purposes of class member access ([expr.ref]) outside the member function body.
[Note
:
Only class members declared prior to the declaration are visible.
end note
]
[Example
:
struct A {
  char g();
  template<class T> auto f(T t) -> decltype(t + g())
    { return t + g(); }
};
template auto A::f(int t) -> decltype(t + g());
end example
]
Otherwise, if a member-declarator declares a non-static data member ([class.mem]) of a class X, the expression this is a prvalue of type “pointer to X” within the optional default member initializer ([class.mem]).
It shall not appear elsewhere in the member-declarator.
The expression this shall not appear in any other context.
[Example
:
class Outer {
  int a[sizeof(*this)];               // error: not inside a member function
  unsigned int sz = sizeof(*this);    // OK: in default member initializer

  void f() {
    int b[sizeof(*this)];             // OK

    struct Inner {
      int c[sizeof(*this)];           // error: not inside a member function of Inner
    };
  }
};
end example
]

8.1.3 Parentheses [expr.prim.paren]

A parenthesized expression (E) is a primary expression whose type, value, and value category are identical to those of E.
The parenthesized expression can be used in exactly the same contexts as those where E can be used, and with the same meaning, except as otherwise indicated.

8.1.4 Names [expr.prim.id]

An id-expression is a restricted form of a primary-expression.
[Note
:
An id-expression can appear after . and -> operators ([expr.ref]).
end note
]
An id-expression that denotes a non-static data member or non-static member function of a class can only be used:
  • as part of a class member access ([expr.ref]) in which the object expression refers to the member's class65 or a class derived from that class, or
  • to form a pointer to member ([expr.unary.op]), or
  • if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
    [Example
    :
    struct S {
      int m;
    };
    int i = sizeof(S::m);           // OK
    int j = sizeof(S::m + 42);      // OK
    
    end example
    ]
This also applies when the object expression is an implicit (*this) ([class.mfct.non-static]).

8.1.4.1 Unqualified names [expr.prim.id.unqual]

An identifier is an id-expression provided it has been suitably declared (Clause [dcl.dcl]).
[Note
:
For operator-function-ids, see [over.oper]; for conversion-function-ids, see [class.conv.fct]; for literal-operator-ids, see [over.literal]; for template-ids, see [temp.names].
A class-name or decltype-specifier prefixed by ~ denotes a destructor; see [class.dtor].
Within the definition of a non-static member function, an identifier that names a non-static member is transformed to a class member access expression ([class.mfct.non-static]).
end note
]
The type of the expression is the type of the identifier.
The result is the entity denoted by the identifier.
The expression is an lvalue if the entity is a function, variable, or data member and a prvalue otherwise; it is a bit-field if the identifier designates a bit-field ([dcl.struct.bind]).

8.1.4.2 Qualified names [expr.prim.id.qual]

The type denoted by a decltype-specifier in a nested-name-specifier shall be a class or enumeration type.
A nested-name-specifier that denotes a class, optionally followed by the keyword template ([temp.names]), and then followed by the name of a member of either that class ([class.mem]) or one of its base classes (Clause [class.derived]), is a qualified-id; [class.qual] describes name lookup for class members that appear in qualified-ids.
The result is the member.
The type of the result is the type of the member.
The result is an lvalue if the member is a static member function or a data member and a prvalue otherwise.
[Note
:
A class member can be referred to using a qualified-id at any point in its potential scope ([basic.scope.class]).
end note
]
Where class-name ​::​~ class-name is used, the two class-names shall refer to the same class; this notation names the destructor ([class.dtor]).
The form ~ decltype-specifier also denotes the destructor, but it shall not be used as the unqualified-id in a qualified-id.
[Note
:
A typedef-name that names a class is a class-name ([class.name]).
end note
]
The nested-name-specifier ​::​ names the global namespace.
A nested-name-specifier that names a namespace ([basic.namespace]), optionally followed by the keyword template ([temp.names]), and then followed by the name of a member of that namespace (or the name of a member of a namespace made visible by a using-directive), is a qualified-id; [namespace.qual] describes name lookup for namespace members that appear in qualified-ids.
The result is the member.
The type of the result is the type of the member.
The result is an lvalue if the member is a function or a variable and a prvalue otherwise.
A nested-name-specifier that denotes an enumeration ([dcl.enum]), followed by the name of an enumerator of that enumeration, is a qualified-id that refers to the enumerator.
The result is the enumerator.
The type of the result is the type of the enumeration.
The result is a prvalue.
In a qualified-id, if the unqualified-id is a conversion-function-id, its conversion-type-id shall denote the same type in both the context in which the entire qualified-id occurs and in the context of the class denoted by the nested-name-specifier.

8.1.5 Lambda expressions [expr.prim.lambda]

Lambda expressions provide a concise way to create simple function objects.
[Example
:
#include <algorithm>
#include <cmath>
void abssort(float* x, unsigned N) {
  std::sort(x, x + N, [](float a, float b) { return std::abs(a) < std::abs(b); });
}
end example
]
A lambda-expression is a prvalue whose result object is called the closure object.
A lambda-expression shall not appear in an unevaluated operand (Clause [expr]), in a template-argument, in an alias-declaration, in a typedef declaration, or in the declaration of a function or function template outside its function body and default arguments.
[Note
:
The intention is to prevent lambdas from appearing in a signature.
end note
]
[Note
:
A closure object behaves like a function object ([function.objects]).
end note
]
In the decl-specifier-seq of the lambda-declarator, each decl-specifier shall either be mutable or constexpr.
If a lambda-expression does not include a lambda-declarator, it is as if the lambda-declarator were ().
The lambda return type is auto, which is replaced by the type specified by the trailing-return-type if provided and/or deduced from return statements as described in [dcl.spec.auto].
[Example
:
auto x1 = [](int i){ return i; };     // OK: return type is int
auto x2 = []{ return { 1, 2 }; };     // error: deducing return type from braced-init-list
int j;
auto x3 = []()->auto&& { return j; }; // OK: return type is int&
end example
]

8.1.5.1 Closure types [expr.prim.lambda.closure]

The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type, called the closure type, whose properties are described below.
The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the corresponding lambda-expression.
[Note
:
This determines the set of namespaces and classes associated with the closure type ([basic.lookup.argdep]).
The parameter types of a lambda-declarator do not affect these associated namespaces and classes.
end note
]
The closure type is not an aggregate type ([dcl.init.aggr]).
An implementation may define the closure type differently from what is described below provided this does not alter the observable behavior of the program other than by changing:
  • the size and/or alignment of the closure type,
  • whether the closure type is trivially copyable (Clause [class]),
  • whether the closure type is a standard-layout class (Clause [class]), or
  • whether the closure type is a POD class (Clause [class]).
An implementation shall not add members of rvalue reference type to the closure type.
The closure type for a non-generic lambda-expression has a public inline function call operator ([over.call]) whose parameters and return type are described by the lambda-expression's parameter-declaration-clause and trailing-return-type respectively.
For a generic lambda, the closure type has a public inline function call operator member template ([temp.mem]) whose template-parameter-list consists of one invented type template-parameter for each occurrence of auto in the lambda's parameter-declaration-clause, in order of appearance.
The invented type template-parameter is a parameter pack if the corresponding parameter-declaration declares a function parameter pack ([dcl.fct]).
The return type and function parameters of the function call operator template are derived from the lambda-expression's trailing-return-type and parameter-declaration-clause by replacing each occurrence of auto in the decl-specifiers of the parameter-declaration-clause with the name of the corresponding invented template-parameter.
[Example
:
auto glambda = [](auto a, auto&& b) { return a < b; };
bool b = glambda(3, 3.14);                             // OK

auto vglambda = [](auto printer) {
  return [=](auto&& ... ts) {                          // OK: ts is a function parameter pack
    printer(std::forward<decltype(ts)>(ts)...);

    return [=]() {
      printer(ts ...);
    };
  };
};
auto p = vglambda( [](auto v1, auto v2, auto v3)
                   { std::cout << v1 << v2 << v3; } );
auto q = p(1, 'a', 3.14);                              // OK: outputs 1a3.14
q();                                                   // OK: outputs 1a3.14
end example
]
The function call operator or operator template is declared const ([class.mfct.non-static]) if and only if the lambda-expression's parameter-declaration-clause is not followed by mutable.
It is neither virtual nor declared volatile.
Any noexcept-specifier specified on a lambda-expression applies to the corresponding function call operator or operator template.
An attribute-specifier-seq in a lambda-declarator appertains to the type of the corresponding function call operator or operator template.
The function call operator or any given operator template specialization is a constexpr function if either the corresponding lambda-expression's parameter-declaration-clause is followed by constexpr, or it satisfies the requirements for a constexpr function ([dcl.constexpr]).
[Note
:
Names referenced in the lambda-declarator are looked up in the context in which the lambda-expression appears.
end note
]
[Example
:
auto ID = [](auto a) { return a; };
static_assert(ID(3) == 3); // OK

struct NonLiteral {
  NonLiteral(int n) : n(n) { }
  int n;
};
static_assert(ID(NonLiteral{3}).n == 3); // ill-formed
end example
]
[Example
:
auto monoid = [](auto v) { return [=] { return v; }; };
auto add = [](auto m1) constexpr {
  auto ret = m1();
  return [=](auto m2) mutable {
    auto m1val = m1();
    auto plus = [=](auto m2val) mutable constexpr
                   { return m1val += m2val; };
    ret = plus(m2());
    return monoid(ret);
  };
};
constexpr auto zero = monoid(0);
constexpr auto one = monoid(1);
static_assert(add(one)(zero)() == one()); // OK

// Since two below is not declared constexpr, an evaluation of its constexpr member function call operator
// cannot perform an lvalue-to-rvalue conversion on one of its subobjects (that represents its capture)
// in a constant expression.
auto two = monoid(2);
assert(two() == 2); // OK, not a constant expression.
static_assert(add(one)(one)() == two()); // ill-formed: two() is not a constant expression
static_assert(add(one)(one)() == monoid(2)()); // OK
end example
]
The closure type for a non-generic lambda-expression with no lambda-capture has a conversion function to pointer to function with C++ language linkage ([dcl.link]) having the same parameter and return types as the closure type's function call operator.
The conversion is to “pointer to noexcept function” if the function call operator has a non-throwing exception specification.
The value returned by this conversion function is the address of a function F that, when invoked, has the same effect as invoking the closure type's function call operator.
F is a constexpr function if the function call operator is a constexpr function.
For a generic lambda with no lambda-capture, the closure type has a conversion function template to pointer to function.
The conversion function template has the same invented template-parameter-list, and the pointer to function has the same parameter types, as the function call operator template.
The return type of the pointer to function shall behave as if it were a decltype-specifier denoting the return type of the corresponding function call operator template specialization.
[Note
:
If the generic lambda has no trailing-return-type or the trailing-return-type contains a placeholder type, return type deduction of the corresponding function call operator template specialization has to be done.
The corresponding specialization is that instantiation of the function call operator template with the same template arguments as those deduced for the conversion function template.
Consider the following:
auto glambda = [](auto a) { return a; };
int (*fp)(int) = glambda;
The behavior of the conversion function of glambda above is like that of the following conversion function:
struct Closure {
  template<class T> auto operator()(T t) const { ... }
  template<class T> static auto lambda_call_operator_invoker(T a) {
    // forwards execution to operator()(a) and therefore has
    // the same return type deduced
    ...
  }
  template<class T> using fptr_t =
     decltype(lambda_call_operator_invoker(declval<T>())) (*)(T);

  template<class T> operator fptr_t<T>() const
    { return &lambda_call_operator_invoker; }
};
end note
]
[Example
:
void f1(int (*)(int))   { }
void f2(char (*)(int))  { }

void g(int (*)(int))    { }  // #1
void g(char (*)(char))  { }  // #2

void h(int (*)(int))    { }  // #3
void h(char (*)(int))   { }  // #4

auto glambda = [](auto a) { return a; };
f1(glambda);  // OK
f2(glambda);  // error: ID is not convertible
g(glambda);   // error: ambiguous
h(glambda);   // OK: calls #3 since it is convertible from ID
int& (*fpi)(int*) = [](auto* a) -> auto& { return *a; }; // OK
end example
]
The value returned by any given specialization of this conversion function template is the address of a function F that, when invoked, has the same effect as invoking the generic lambda's corresponding function call operator template specialization.
F is a constexpr function if the corresponding specialization is a constexpr function.
[Note
:
This will result in the implicit instantiation of the generic lambda's body.
The instantiated generic lambda's return type and parameter types shall match the return type and parameter types of the pointer to function.
end note
]
[Example
:
auto GL = [](auto a) { std::cout << a; return a; };
int (*GL_int)(int) = GL;  // OK: through conversion function template
GL_int(3);                // OK: same as GL(3)
end example
]
The conversion function or conversion function template is public, constexpr, non-virtual, non-explicit, const, and has a non-throwing exception specification ([except.spec]).
[Example
:
auto Fwd = [](int (*fp)(int), auto a) { return fp(a); };
auto C = [](auto a) { return a; };

static_assert(Fwd(C,3) == 3); // OK

// No specialization of the function call operator template can be constexpr (due to the local static).
auto NC = [](auto a) { static int s; return a; };
static_assert(Fwd(NC,3) == 3); // ill-formed
end example
]
The lambda-expression's compound-statement yields the function-body ([dcl.fct.def]) of the function call operator, but for purposes of name lookup ([basic.lookup]), determining the type and value of this ([class.this]) and transforming id-expressions referring to non-static class members into class member access expressions using (*this) ([class.mfct.non-static]), the compound-statement is considered in the context of the lambda-expression.
[Example
:
struct S1 {
  int x, y;
  int operator()(int);
  void f() {
    [=]()->int {
      return operator()(this->x + y); // equivalent to S1​::​operator()(this->x + (*this).y)
                                      // this has type S1*
    };
  }
};
end example
]
Further, a variable _­_­func_­_­ is implicitly defined at the beginning of the compound-statement of the lambda-expression, with semantics as described in [dcl.fct.def.general].
The closure type associated with a lambda-expression has no default constructor and a deleted copy assignment operator.
It has a defaulted copy constructor and a defaulted move constructor ([class.copy]).
[Note
:
These special member functions are implicitly defined as usual, and might therefore be defined as deleted.
end note
]
The closure type associated with a lambda-expression has an implicitly-declared destructor ([class.dtor]).
A member of a closure type shall not be explicitly instantiated ([temp.explicit]), explicitly specialized ([temp.expl.spec]), or named in a friend declaration ([class.friend]).

8.1.5.2 Captures [expr.prim.lambda.capture]

The body of a lambda-expression may refer to variables with automatic storage duration and the *this object (if any) of enclosing block scopes by capturing those entities, as described below.
If a lambda-capture includes a capture-default that is &, no identifier in a simple-capture of that lambda-capture shall be preceded by &.
If a lambda-capture includes a capture-default that is =, each simple-capture of that lambda-capture shall be of the form “& identifier” or “* this.
[Note
:
The form [&,this] is redundant but accepted for compatibility with ISO C++ 2014.
end note
]
Ignoring appearances in initializers of init-captures, an identifier or this shall not appear more than once in a lambda-capture.
[Example
:
struct S2 { void f(int i); };
void S2::f(int i) {
  [&, i]{ };        // OK
  [&, &i]{ };       // error: i preceded by & when & is the default
  [=, *this]{ };    // OK
  [=, this]{ };     // error: this when = is the default
  [i, i]{ };        // error: i repeated
  [this, *this]{ }; // error: this appears twice
}
end example
]
A lambda-expression whose smallest enclosing scope is a block scope ([basic.scope.block]) is a local lambda expression; any other lambda-expression shall not have a capture-default or simple-capture in its lambda-introducer.
The reaching scope of a local lambda expression is the set of enclosing scopes up to and including the innermost enclosing function and its parameters.
[Note
:
This reaching scope includes any intervening lambda-expressions.
end note
]
The identifier in a simple-capture is looked up using the usual rules for unqualified name lookup ([basic.lookup.unqual]); each such lookup shall find an entity.
An entity that is designated by a simple-capture is said to be explicitly captured, and shall be *this (when the simple-capture is “this” or “* this”) or a variable with automatic storage duration declared in the reaching scope of the local lambda expression.
If an identifier in a simple-capture appears as the declarator-id of a parameter of the lambda-declarator's parameter-declaration-clause, the program is ill-formed.
[Example
:
void f() {
  int x = 0;
  auto g = [x](int x) { return 0; }    // error: parameter and simple-capture have the same name
}
end example
]
An init-capture behaves as if it declares and explicitly captures a variable of the form “auto init-capture ;” whose declarative region is the lambda-expression's compound-statement, except that:
  • if the capture is by copy (see below), the non-static data member declared for the capture and the variable are treated as two different ways of referring to the same object, which has the lifetime of the non-static data member, and no additional copy and destruction is performed, and
  • if the capture is by reference, the variable's lifetime ends when the closure object's lifetime ends.
[Note
:
This enables an init-capture like “x = std​::​move(x)”; the second “x” must bind to a declaration in the surrounding context.
end note
]
[Example
:
int x = 4;
auto y = [&r = x, x = x+1]()->int {
            r += 2;
            return x+2;
         }();  // Updates ​::​x to 6, and initializes y to 7.

auto z = [a = 42](int a) { return 1; } // error: parameter and local variable have the same name
end example
]
A lambda-expression with an associated capture-default that does not explicitly capture *this or a variable with automatic storage duration (this excludes any id-expression that has been found to refer to an init-capture's associated non-static data member), is said to implicitly capture the entity (i.e., *this or a variable) if the compound-statement:
[Example
:
void f(int, const int (&)[2] = {})    { }   // #1
void f(const int&, const int (&)[1])  { }   // #2
void test() {
  const int x = 17;
  auto g = [](auto a) {
    f(x);                       // OK: calls #1, does not capture x
  };

  auto g2 = [=](auto a) {
    int selector[sizeof(a) == 1 ? 1 : 2]{};
    f(x, selector);             // OK: is a dependent expression, so captures x
  };
}
end example
]
All such implicitly captured entities shall be declared within the reaching scope of the lambda expression.
[Note
:
The implicit capture of an entity by a nested lambda-expression can cause its implicit capture by the containing lambda-expression (see below).
Implicit odr-uses of this can result in implicit capture.
end note
]
An entity is captured if it is captured explicitly or implicitly.
An entity captured by a lambda-expression is odr-used ([basic.def.odr]) in the scope containing the lambda-expression.
If *this is captured by a local lambda expression, its nearest enclosing function shall be a non-static member function.
If a lambda-expression or an instantiation of the function call operator template of a generic lambda odr-uses ([basic.def.odr]) this or a variable with automatic storage duration from its reaching scope, that entity shall be captured by the lambda-expression.
If a lambda-expression captures an entity and that entity is not defined or captured in the immediately enclosing lambda expression or function, the program is ill-formed.
[Example
:
void f1(int i) {
  int const N = 20;
  auto m1 = [=]{
    int const M = 30;
    auto m2 = [i]{
      int x[N][M];              // OK: N and M are not odr-used
      x[0][0] = i;              // OK: i is explicitly captured by m2 and implicitly captured by m1
    };
  };
  struct s1 {
    int f;
    void work(int n) {
      int m = n*n;
      int j = 40;
      auto m3 = [this,m] {
        auto m4 = [&,j] {       // error: j not captured by m3
          int x = n;            // error: n implicitly captured by m4 but not captured by m3
          x += m;               // OK: m implicitly captured by m4 and explicitly captured by m3
          x += i;               // error: i is outside of the reaching scope
          x += f;               // OK: this captured implicitly by m4 and explicitly by m3
        };
      };
    }
  };
}

struct s2 {
  double ohseven = .007;
  auto f() {
    return [this] {
      return [*this] {
          return ohseven;       // OK
      }
    }();
  }
  auto g() {
    return [] {
      return [*this] { };       // error: *this not captured by outer lambda-expression
    }();
  }
};
end example
]
A lambda-expression appearing in a default argument shall not implicitly or explicitly capture any entity.
[Example
:
void f2() {
  int i = 1;
  void g1(int = ([i]{ return i; })());          // ill-formed
  void g2(int = ([i]{ return 0; })());          // ill-formed
  void g3(int = ([=]{ return i; })());          // ill-formed
  void g4(int = ([=]{ return 0; })());          // OK
  void g5(int = ([]{ return sizeof i; })());    // OK
}
end example
]
An entity is captured by copy if
For each entity captured by copy, an unnamed non-static data member is declared in the closure type.
The declaration order of these members is unspecified.
The type of such a data member is the referenced type if the entity is a reference to an object, an lvalue reference to the referenced function type if the entity is a reference to a function, or the type of the corresponding captured entity otherwise.
A member of an anonymous union shall not be captured by copy.
Every id-expression within the compound-statement of a lambda-expression that is an odr-use ([basic.def.odr]) of an entity captured by copy is transformed into an access to the corresponding unnamed data member of the closure type.
[Note
:
An id-expression that is not an odr-use refers to the original entity, never to a member of the closure type.
Furthermore, such an id-expression does not cause the implicit capture of the entity.
end note
]
If *this is captured by copy, each odr-use of this is transformed into a pointer to the corresponding unnamed data member of the closure type, cast ([expr.cast]) to the type of this.
[Note
:
The cast ensures that the transformed expression is a prvalue.
end note
]
An id-expression within the compound-statement of a lambda-expression that is an odr-use of a reference captured by reference refers to the entity to which the captured reference is bound and not to the captured reference.
[Note
:
The validity of such captures is determined by the lifetime of the object to which the reference refers, not by the lifetime of the reference itself.
end note
]
[Example
:
void f(const int*);
void g() {
  const int N = 10;
  [=] {
    int arr[N];     // OK: not an odr-use, refers to automatic variable
    f(&N);          // OK: causes N to be captured; &N points to
                    // the corresponding member of the closure type
  };
}
auto h(int &r) {
  return [&] {
    ++r;            // Valid after h returns if the lifetime of the
                    // object to which r is bound has not ended
  };
}
end example
]
An entity is captured by reference if it is implicitly or explicitly captured but not captured by copy.
It is unspecified whether additional unnamed non-static data members are declared in the closure type for entities captured by reference.
If declared, such non-static data members shall be of literal type.
[Example
:
// The inner closure type must be a literal type regardless of how reference captures are represented.
static_assert([](int n) { return [&n] { return ++n; }(); }(3) == 4);
end example
]
A bit-field or a member of an anonymous union shall not be captured by reference.
If a lambda-expression m2 captures an entity and that entity is captured by an immediately enclosing lambda-expression m1, then m2's capture is transformed as follows:
  • if m1 captures the entity by copy, m2 captures the corresponding non-static data member of m1's closure type;
  • if m1 captures the entity by reference, m2 captures the same entity captured by m1.
[Example
:
The nested lambda expressions and invocations below will output 123234.
int a = 1, b = 1, c = 1;
auto m1 = [a, &b, &c]() mutable {
  auto m2 = [a, b, &c]() mutable {
    std::cout << a << b << c;
    a = 4; b = 4; c = 4;
  };
  a = 3; b = 3; c = 3;
  m2();
};
a = 2; b = 2; c = 2;
m1();
std::cout << a << b << c;
end example
]
Every occurrence of decltype((x)) where x is a possibly parenthesized id-expression that names an entity of automatic storage duration is treated as if x were transformed into an access to a corresponding data member of the closure type that would have been declared if x were an odr-use of the denoted entity.
[Example
:
void f3() {
  float x, &r = x;
  [=] {                     // x and r are not captured (appearance in a decltype operand is not an odr-use)
    decltype(x) y1;         // y1 has type float
    decltype((x)) y2 = y1;  // y2 has type float const& because this lambda is not mutable and x is an lvalue
    decltype(r) r1 = y1;    // r1 has type float& (transformation not considered)
    decltype((r)) r2 = y2;  // r2 has type float const&
  };
}
end example
]
When the lambda-expression is evaluated, the entities that are captured by copy are used to direct-initialize each corresponding non-static data member of the resulting closure object, and the non-static data members corresponding to the init-captures are initialized as indicated by the corresponding initializer (which may be copy- or direct-initialization).
(For array members, the array elements are direct-initialized in increasing subscript order.)
These initializations are performed in the (unspecified) order in which the non-static data members are declared.
[Note
:
This ensures that the destructions will occur in the reverse order of the constructions.
end note
]
[Note
:
If a non-reference entity is implicitly or explicitly captured by reference, invoking the function call operator of the corresponding lambda-expression after the lifetime of the entity has ended is likely to result in undefined behavior.
end note
]
A simple-capture followed by an ellipsis is a pack expansion ([temp.variadic]).
An init-capture followed by an ellipsis is ill-formed.
[Example
:
template<class... Args>
void f(Args... args) {
  auto lm = [&, args...] { return g(args...); };
  lm();
}
end example
]

8.1.6 Fold expressions [expr.prim.fold]

A fold expression performs a fold of a template parameter pack ([temp.variadic]) over a binary operator.
fold-expression:
	( cast-expression fold-operator ... )
	( ... fold-operator cast-expression )
	( cast-expression fold-operator ... fold-operator cast-expression )
fold-operator: one of
	+   -   *   /   %   ^   &   |   <<   >> 
	+=  -=  *=  /=  %=  ^=  &=  |=  <<=  >>=  =
	==  !=  <   >   <=  >=  &&  ||  ,    .*   ->*
An expression of the form (... op e) where op is a fold-operator is called a unary left fold.
An expression of the form (e op ...) where op is a fold-operator is called a unary right fold.
Unary left folds and unary right folds are collectively called unary folds.
In a unary fold, the cast-expression shall contain an unexpanded parameter pack ([temp.variadic]).
An expression of the form (e1 op1 ... op2 e2) where op1 and op2 are fold-operators is called a binary fold.
In a binary fold, op1 and op2 shall be the same fold-operator, and either e1 shall contain an unexpanded parameter pack or e2 shall contain an unexpanded parameter pack, but not both.
If e2 contains an unexpanded parameter pack, the expression is called a binary left fold.
If e1 contains an unexpanded parameter pack, the expression is called a binary right fold.
[Example
:
template<typename ...Args>
bool f(Args ...args) {
  return (true && ... && args); // OK
}

template<typename ...Args>
bool f(Args ...args) {
  return (args + ... + args);   // error: both operands contain unexpanded parameter packs
}
end example
]

8.2 Postfix expressions [expr.post]

[Note
:
The > token following the type-id in a dynamic_­cast, static_­cast, reinterpret_­cast, or const_­cast may be the product of replacing a >> token by two consecutive > tokens ([temp.names]).
end note
]

8.2.1 Subscripting [expr.sub]

A postfix expression followed by an expression in square brackets is a postfix expression.
One of the expressions shall be a glvalue of type “array of T” or a prvalue of type “pointer to T” and the other shall be a prvalue of unscoped enumeration or integral type.
The result is of type “T.
The type “T” shall be a completely-defined object type.66
The expression E1[E2] is identical (by definition) to *((E1)+(E2))
[Note
:
see [expr.unary] and [expr.add] for details of * and + and [dcl.array] for details of arrays.
end note
]
, except that in the case of an array operand, the result is an lvalue if that operand is an lvalue and an xvalue otherwise.
The expression E1 is sequenced before the expression E2.
A braced-init-list shall not be used with the built-in subscript operator.
This is true even if the subscript operator is used in the following common idiom: &x[0].

8.2.2 Function call [expr.call]

A function call is a postfix expression followed by parentheses containing a possibly empty, comma-separated list of initializer-clauses which constitute the arguments to the function.
The postfix expression shall have function type or function pointer type.
For a call to a non-member function or to a static member function, the postfix expression shall be either an lvalue that refers to a function (in which case the function-to-pointer standard conversion ([conv.func]) is suppressed on the postfix expression), or it shall have function pointer type.
Calling a function through an expression whose function type is different from the function type of the called function's definition results in undefined behavior ([dcl.link]).
For a call to a non-static member function, the postfix expression shall be an implicit ([class.mfct.non-static], [class.static]) or explicit class member access ([expr.ref]) whose id-expression is a function member name, or a pointer-to-member expression ([expr.mptr.oper]) selecting a function member; the call is as a member of the class object referred to by the object expression.
In the case of an implicit class member access, the implied object is the one pointed to by this.
[Note
:
A member function call of the form f() is interpreted as (*this).f() (see [class.mfct.non-static]).
end note
]
If a function or member function name is used, the name can be overloaded (Clause [over]), in which case the appropriate function shall be selected according to the rules in [over.match].
If the selected function is non-virtual, or if the id-expression in the class member access expression is a qualified-id, that function is called.
Otherwise, its final overrider ([class.virtual]) in the dynamic type of the object expression is called; such a call is referred to as a virtual function call.
[Note
:
The dynamic type is the type of the object referred to by the current value of the object expression.
[class.cdtor] describes the behavior of virtual function calls when the object expression refers to an object under construction or destruction.
end note
]
[Note
:
If a function or member function name is used, and name lookup ([basic.lookup]) does not find a declaration of that name, the program is ill-formed.
No function is implicitly declared by such a call.
end note
]
If the postfix-expression designates a destructor ([class.dtor]), the type of the function call expression is void; otherwise, the type of the function call expression is the return type of the statically chosen function (i.e., ignoring the virtual keyword), even if the type of the function actually called is different.
This return type shall be an object type, a reference type or cv void.
When a function is called, each parameter ([dcl.fct]) shall be initialized ([dcl.init], [class.copy], [class.ctor]) with its corresponding argument.
If the function is a non-static member function, the this parameter of the function ([class.this]) shall be initialized with a pointer to the object of the call, converted as if by an explicit type conversion ([expr.cast]).
[Note
:
There is no access or ambiguity checking on this conversion; the access checking and disambiguation are done as part of the (possibly implicit) class member access operator.
end note
]
When a function is called, the parameters that have object type shall have completely-defined object type.
[Note
:
this still allows a parameter to be a pointer or reference to an incomplete class type.
However, it prevents a passed-by-value parameter to have an incomplete class type.
end note
]
It is implementation-defined whether the lifetime of a parameter ends when the function in which it is defined returns or at the end of the enclosing full-expression.
The initialization and destruction of each parameter occurs within the context of the calling function.
[Example
:
The access of the constructor, conversion functions or destructor is checked at the point of call in the calling function.
If a constructor or destructor for a function parameter throws an exception, the search for a handler starts in the scope of the calling function; in particular, if the function called has a function-try-block (Clause [except]) with a handler that could handle the exception, this handler is not considered.
end example
]
The postfix-expression is sequenced before each expression in the expression-list and any default argument.
The initialization of a parameter, including every associated value computation and side effect, is indeterminately sequenced with respect to that of any other parameter.
[Note
:
All side effects of argument evaluations are sequenced before the function is entered (see [intro.execution]).
end note
]
[Example
:
void f() {
  std::string s = "but I have heard it works even if you don't believe in it";
  s.replace(0, 4, "").replace(s.find("even"), 4, "only").replace(s.find(" don't"), 6, "");
  assert(s == "I have heard it works only if you believe in it"); // OK
}
end example
]
[Note
:
If an operator function is invoked using operator notation, argument evaluation is sequenced as specified for the built-in operator; see [over.match.oper].
end note
]
[Example
:
struct S {
  S(int);
};
int operator<<(S, int);
int i, j;
int x = S(i=1) << (i=2);
int y = operator<<(S(j=1), j=2);
After performing the initializations, the value of i is 2 (see [expr.shift]), but it is unspecified whether the value of j is 1 or 2.
end example
]
The result of a function call is the result of the operand of the evaluated return statement ([stmt.return]) in the called function (if any), except in a virtual function call if the return type of the final overrider is different from the return type of the statically chosen function, the value returned from the final overrider is converted to the return type of the statically chosen function.
[Note
:
A function can change the values of its non-const parameters, but these changes cannot affect the values of the arguments except where a parameter is of a reference type ([dcl.ref]); if the reference is to a const-qualified type, const_­cast is required to be used to cast away the constness in order to modify the argument's value.
Where a parameter is of const reference type a temporary object is introduced if needed ([dcl.type], [lex.literal], [lex.string], [dcl.array], [class.temporary]).
In addition, it is possible to modify the values of non-constant objects through pointer parameters.
end note
]
A function can be declared to accept fewer arguments (by declaring default arguments ([dcl.fct.default])) or more arguments (by using the ellipsis, ..., or a function parameter pack ([dcl.fct])) than the number of parameters in the function definition ([dcl.fct.def]).
[Note
:
This implies that, except where the ellipsis (...) or a function parameter pack is used, a parameter is available for each argument.
end note
]
When there is no parameter for a given argument, the argument is passed in such a way that the receiving function can obtain the value of the argument by invoking va_­arg ([support.runtime]).
[Note
:
This paragraph does not apply to arguments passed to a function parameter pack.
Function parameter packs are expanded during template instantiation ([temp.variadic]), thus each such argument has a corresponding parameter when a function template specialization is actually called.
end note
]
The lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions are performed on the argument expression.
An argument that has type cv std​::​nullptr_­t is converted to type void* ([conv.ptr]).
After these conversions, if the argument does not have arithmetic, enumeration, pointer, pointer to member, or class type, the program is ill-formed.
Passing a potentially-evaluated argument of class type (Clause [class]) having a non-trivial copy constructor, a non-trivial move constructor, or a non-trivial destructor, with no corresponding parameter, is conditionally-supported with implementation-defined semantics.
If the argument has integral or enumeration type that is subject to the integral promotions ([conv.prom]), or a floating-point type that is subject to the floating-point promotion ([conv.fpprom]), the value of the argument is converted to the promoted type before the call.
These promotions are referred to as the default argument promotions.
Recursive calls are permitted, except to the main function ([basic.start.main]).
A function call is an lvalue if the result type is an lvalue reference type or an rvalue reference to function type, an xvalue if the result type is an rvalue reference to object type, and a prvalue otherwise.

8.2.3 Explicit type conversion (functional notation) [expr.type.conv]

A simple-type-specifier or typename-specifier followed by a parenthesized optional expression-list or by a braced-init-list (the initializer) constructs a value of the specified type given the initializer.
If the type is a placeholder for a deduced class type, it is replaced by the return type of the function selected by overload resolution for class template deduction ([over.match.class.deduct]) for the remainder of this section.
If the initializer is a parenthesized single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression ([expr.cast]).
If the type is cv void and the initializer is (), the expression is a prvalue of the specified type that performs no initialization.
Otherwise, the expression is a prvalue of the specified type whose result object is direct-initialized ([dcl.init]) with the initializer.
For an expression of the form T(), T shall not be an array type.

8.2.4 Pseudo destructor call [expr.pseudo]

The use of a pseudo-destructor-name after a dot . or arrow -> operator represents the destructor for the non-class type denoted by type-name or decltype-specifier.
The result shall only be used as the operand for the function call operator (), and the result of such a call has type void.
The only effect is the evaluation of the postfix-expression before the dot or arrow.
The left-hand side of the dot operator shall be of scalar type.
The left-hand side of the arrow operator shall be of pointer to scalar type.
This scalar type is the object type.
The cv-unqualified versions of the object type and of the type designated by the pseudo-destructor-name shall be the same type.
Furthermore, the two type-names in a pseudo-destructor-name of the form
nested-name-specifier type-name ::~ type-name
shall designate the same scalar type (ignoring cv-qualification).

8.2.5 Class member access [expr.ref]

A postfix expression followed by a dot . or an arrow ->, optionally followed by the keyword template ([temp.names]), and then followed by an id-expression, is a postfix expression.
The postfix expression before the dot or arrow is evaluated;67 the result of that evaluation, together with the id-expression, determines the result of the entire postfix expression.
For the first option (dot) the first expression shall be a glvalue having complete class type.
For the second option (arrow) the first expression shall be a prvalue having pointer to complete class type.
The expression E1->E2 is converted to the equivalent form (*(E1)).E2; the remainder of [expr.ref] will address only the first option (dot).68
In either case, the id-expression shall name a member of the class or of one of its base classes.
[Note
:
Because the name of a class is inserted in its class scope (Clause [class]), the name of a class is also considered a nested member of that class.
end note
]
[Note
:
[basic.lookup.classref] describes how names are looked up after the . and -> operators.
end note
]
Abbreviating postfix-expression.id-expression as E1.E2, E1 is called the object expression.
If E2 is a bit-field, E1.E2 is a bit-field.
The type and value category of E1.E2 are determined as follows.
In the remainder of [expr.ref], cq represents either const or the absence of const and vq represents either volatile or the absence of volatile.
cv represents an arbitrary set of cv-qualifiers, as defined in [basic.type.qualifier].
If E2 is declared to have type “reference to T”, then E1.E2 is an lvalue; the type of E1.E2 is T.
Otherwise, one of the following rules applies.
  • If E2 is a static data member and the type of E2 is T, then E1.E2 is an lvalue; the expression designates the named member of the class.
    The type of E1.E2 is T.
  • If E2 is a non-static data member and the type of E1 is “cq1 vq1 X”, and the type of E2 is “cq2 vq2 T”, the expression designates the named member of the object designated by the first expression.
    If E1 is an lvalue, then E1.E2 is an lvalue; otherwise E1.E2 is an xvalue.
    Let the notation vq12 stand for the “union” of vq1 and vq2; that is, if vq1 or vq2 is volatile, then vq12 is volatile.
    Similarly, let the notation cq12 stand for the “union” of cq1 and cq2; that is, if cq1 or cq2 is const, then cq12 is const.
    If E2 is declared to be a mutable member, then the type of E1.E2 is “vq12 T.
    If E2 is not declared to be a mutable member, then the type of E1.E2 is “cq12 vq12 T.
  • If E2 is a (possibly overloaded) member function, function overload resolution ([over.match]) is used to determine whether E1.E2 refers to a static or a non-static member function.
    • If it refers to a static member function and the type of E2 is “function of parameter-type-list returning T”, then E1.E2 is an lvalue; the expression designates the static member function.
      The type of E1.E2 is the same type as that of E2, namely “function of parameter-type-list returning T.
    • Otherwise, if E1.E2 refers to a non-static member function and the type of E2 is “function of parameter-type-list cv ref-qualifier returning T”, then E1.E2 is a prvalue.
      The expression designates a non-static member function.
      The expression can be used only as the left-hand operand of a member function call ([class.mfct]).
      [Note
      :
      Any redundant set of parentheses surrounding the expression is ignored ([expr.prim]).
      end note
      ]
      The type of E1.E2 is “function of parameter-type-list cv returning T.
  • If E2 is a nested type, the expression E1.E2 is ill-formed.
  • If E2 is a member enumerator and the type of E2 is T, the expression E1.E2 is a prvalue.
    The type of E1.E2 is T.
If E2 is a non-static data member or a non-static member function, the program is ill-formed if the class of which E2 is directly a member is an ambiguous base ([class.member.lookup]) of the naming class ([class.access.base]) of E2.
[Note
:
The program is also ill-formed if the naming class is an ambiguous base of the class type of the object expression; see [class.access.base].
end note
]
If the class member access expression is evaluated, the subexpression evaluation happens even if the result is unnecessary to determine the value of the entire postfix expression, for example if the id-expression denotes a static member.
Note that (*(E1)) is an lvalue.

8.2.6 Increment and decrement [expr.post.incr]

The value of a postfix ++ expression is the value of its operand.
[Note
:
The value obtained is a copy of the original value
end note
]
The operand shall be a modifiable lvalue.
The type of the operand shall be an arithmetic type other than cv bool, or a pointer to a complete object type.
The value of the operand object is modified by adding 1 to it.
The value computation of the ++ expression is sequenced before the modification of the operand object.
With respect to an indeterminately-sequenced function call, the operation of postfix ++ is a single evaluation.
[Note
:
Therefore, a function call shall not intervene between the lvalue-to-rvalue conversion and the side effect associated with any single postfix ++ operator.
end note
]
The result is a prvalue.
The type of the result is the cv-unqualified version of the type of the operand.
If the operand is a bit-field that cannot represent the incremented value, the resulting value of the bit-field is implementation-defined.
See also [expr.add] and [expr.ass].
The operand of postfix -- is decremented analogously to the postfix ++ operator.
[Note
:
For prefix increment and decrement, see [expr.pre.incr].
end note
]

8.2.7 Dynamic cast [expr.dynamic.cast]

The result of the expression dynamic_­cast<T>(v) is the result of converting the expression v to type T.
T shall be a pointer or reference to a complete class type, or “pointer to cv void.
The dynamic_­cast operator shall not cast away constness ([expr.const.cast]).
If T is a pointer type, v shall be a prvalue of a pointer to complete class type, and the result is a prvalue of type T.
If T is an lvalue reference type, v shall be an lvalue of a complete class type, and the result is an lvalue of the type referred to by T.
If T is an rvalue reference type, v shall be a glvalue having a complete class type, and the result is an xvalue of the type referred to by T.
If the type of v is the same as T, or it is the same as T except that the class object type in T is more cv-qualified than the class object type in v, the result is v (converted if necessary).
If the value of v is a null pointer value in the pointer case, the result is the null pointer value of type T.
If T is “pointer to cv1 B” and v has type “pointer to cv2 D” such that B is a base class of D, the result is a pointer to the unique B subobject of the D object pointed to by v.
Similarly, if T is “reference to cv1 B” and v has type cv2 D such that B is a base class of D, the result is the unique B subobject of the D object referred to by v.69
In both the pointer and reference cases, the program is ill-formed if cv2 has greater cv-qualification than cv1 or if B is an inaccessible or ambiguous base class of D.
[Example
:
struct B { };
struct D : B { };
void foo(D* dp) {
  B*  bp = dynamic_cast<B*>(dp);    // equivalent to B* bp = dp;
}
end example
]
Otherwise, v shall be a pointer to or a glvalue of a polymorphic type ([class.virtual]).
If T is “pointer to cv void”, then the result is a pointer to the most derived object pointed to by v.
Otherwise, a runtime check is applied to see if the object pointed or referred to by v can be converted to the type pointed or referred to by T.
If C is the class type to which T points or refers, the runtime check logically executes as follows:
  • If, in the most derived object pointed (referred) to by v, v points (refers) to a public base class subobject of a C object, and if only one object of type C is derived from the subobject pointed (referred) to by v the result points (refers) to that C object.
  • Otherwise, if v points (refers) to a public base class subobject of the most derived object, and the type of the most derived object has a base class, of type C, that is unambiguous and public, the result points (refers) to the C subobject of the most derived object.
  • Otherwise, the runtime check fails.
The value of a failed cast to pointer type is the null pointer value of the required result type.
A failed cast to reference type throws an exception ([except.throw]) of a type that would match a handler ([except.handle]) of type std​::​bad_­cast ([bad.cast]).
[Example
:
class A { virtual void f(); };
class B { virtual void g(); };
class D : public virtual A, private B { };
void g() {
  D   d;
  B*  bp = (B*)&d;                  // cast needed to break protection
  A*  ap = &d;                      // public derivation, no cast needed
  D&  dr = dynamic_cast<D&>(*bp);   // fails
  ap = dynamic_cast<A*>(bp);        // fails
  bp = dynamic_cast<B*>(ap);        // fails
  ap = dynamic_cast<A*>(&d);        // succeeds
  bp = dynamic_cast<B*>(&d);        // ill-formed (not a runtime check)
}

class E : public D, public B { };
class F : public E, public D { };
void h() {
  F   f;
  A*  ap  = &f;                     // succeeds: finds unique A
  D*  dp  = dynamic_cast<D*>(ap);   // fails: yields null; f has two D subobjects
  E*  ep  = (E*)ap;                 // ill-formed: cast from virtual base
  E*  ep1 = dynamic_cast<E*>(ap);   // succeeds
}
end example
]
[Note
:
[class.cdtor] describes the behavior of a dynamic_­cast applied to an object under construction or destruction.
end note
]
The most derived object ([intro.object]) pointed or referred to by v can contain other B objects as base classes, but these are ignored.

8.2.8 Type identification [expr.typeid]

The result of a typeid expression is an lvalue of static type const std​::​type_­info ([type.info]) and dynamic type const std​::​type_­info or const name where name is an implementation-defined class publicly derived from std​::​type_­info which preserves the behavior described in [type.info].70
The lifetime of the object referred to by the lvalue extends to the end of the program.
Whether or not the destructor is called for the std​::​type_­info object at the end of the program is unspecified.
When typeid is applied to a glvalue expression whose type is a polymorphic class type ([class.virtual]), the result refers to a std​::​type_­info object representing the type of the most derived object ([intro.object]) (that is, the dynamic type) to which the glvalue refers.
If the glvalue expression is obtained by applying the unary * operator to a pointer71 and the pointer is a null pointer value ([conv.ptr]), the typeid expression throws an exception ([except.throw]) of a type that would match a handler of type std​::​bad_­typeid exception ([bad.typeid]).
When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers to a std​::​type_­info object representing the static type of the expression.
Lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) conversions are not applied to the expression.
If the expression is a prvalue, the temporary materialization conversion ([conv.rval]) is applied.
The expression is an unevaluated operand (Clause [expr]).
When typeid is applied to a type-id, the result refers to a std​::​type_­info object representing the type of the type-id.
If the type of the type-id is a reference to a possibly cv-qualified type, the result of the typeid expression refers to a std​::​type_­info object representing the cv-unqualified referenced type.
If the type of the type-id is a class type or a reference to a class type, the class shall be completely-defined.
If the type of the expression or type-id is a cv-qualified type, the result of the typeid expression refers to a std​::​type_­info object representing the cv-unqualified type.
[Example
:
class D { /* ... */ };
D d1;
const D d2;

typeid(d1) == typeid(d2);       // yields true
typeid(D)  == typeid(const D);  // yields true
typeid(D)  == typeid(d2);       // yields true
typeid(D)  == typeid(const D&); // yields true
end example
]
If the header <typeinfo> ([type.info]) is not included prior to a use of typeid, the program is ill-formed.
[Note
:
[class.cdtor] describes the behavior of typeid applied to an object under construction or destruction.
end note
]
The recommended name for such a class is extended_­type_­info.
If p is an expression of pointer type, then *p, (*p), *(p), ((*p)), *((p)), and so on all meet this requirement.

8.2.9 Static cast [expr.static.cast]

The result of the expression static_­cast<T>(v) is the result of converting the expression v to type T.
If T is an lvalue reference type or an rvalue reference to function type, the result is an lvalue; if T is an rvalue reference to object type, the result is an xvalue; otherwise, the result is a prvalue.
The static_­cast operator shall not cast away constness ([expr.const.cast]).
An lvalue of type “cv1 B”, where B is a class type, can be cast to type “reference to cv2 D”, where D is a class derived (Clause [class.derived]) from B, if cv2 is the same cv-qualification as, or greater cv-qualification than, cv1.
If B is a virtual base class of D or a base class of a virtual base class of D, or if no valid standard conversion from “pointer to D” to “pointer to B” exists ([conv.ptr]), the program is ill-formed.
An xvalue of type “cv1 B” can be cast to type “rvalue reference to cv2 D” with the same constraints as for an lvalue of type “cv1 B.
If the object of type “cv1 B” is actually a base class subobject of an object of type D, the result refers to the enclosing object of type D.
Otherwise, the behavior is undefined.
[Example
:
struct B { };
struct D : public B { };
D d;
B &br = d;

static_cast<D&>(br);            // produces lvalue to the original d object
end example
]
An lvalue of type “cv1 T1” can be cast to type “rvalue reference to cv2 T2” if “cv2 T2” is reference-compatible with “cv1 T1” ([dcl.init.ref]).
If the value is not a bit-field, the result refers to the object or the specified base class subobject thereof; otherwise, the lvalue-to-rvalue conversion ([conv.lval]) is applied to the bit-field and the resulting prvalue is used as the expression of the static_­cast for the remainder of this section.
If T2 is an inaccessible (Clause [class.access]) or ambiguous ([class.member.lookup]) base class of T1, a program that necessitates such a cast is ill-formed.
An expression e can be explicitly converted to a type T if there is an implicit conversion sequence ([over.best.ics]) from e to T, or if overload resolution for a direct-initialization ([dcl.init]) of an object or reference of type T from e would find at least one viable function ([over.match.viable]).
If T is a reference type, the effect is the same as performing the declaration and initialization
 T t(e);
for some invented temporary variable t ([dcl.init]) and then using the temporary variable as the result of the conversion.
Otherwise, the result object is direct-initialized from e.
[Note
:
The conversion is ill-formed when attempting to convert an expression of class type to an inaccessible or ambiguous base class.
end note
]
Otherwise, the static_­cast shall perform one of the conversions listed below.
No other conversion shall be performed explicitly using a static_­cast.
Any expression can be explicitly converted to type cv void, in which case it becomes a discarded-value expression (Clause [expr]).
[Note
:
However, if the value is in a temporary object ([class.temporary]), the destructor for that object is not executed until the usual time, and the value of the object is preserved for the purpose of executing the destructor.
end note
]
The inverse of any standard conversion sequence (Clause [conv]) not containing an lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), function-to-pointer ([conv.func]), null pointer ([conv.ptr]), null member pointer ([conv.mem]), boolean ([conv.bool]), or function pointer ([conv.fctptr]) conversion, can be performed explicitly using static_­cast.
A program is ill-formed if it uses static_­cast to perform the inverse of an ill-formed standard conversion sequence.
[Example
:
struct B { };
struct D : private B { };
void f() {
  static_cast<D*>((B*)0);               // error: B is a private base of D
  static_cast<int B::*>((int D::*)0);   // error: B is a private base of D
}
end example
]
The lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) conversions are applied to the operand.
Such a static_­cast is subject to the restriction that the explicit conversion does not cast away constness ([expr.const.cast]), and the following additional rules for specific cases:
A value of a scoped enumeration type ([dcl.enum]) can be explicitly converted to an integral type.
When that type is cv bool, the resulting value is false if the original value is zero and true for all other values.
For the remaining integral types, the value is unchanged if the original value can be represented by the specified type.
Otherwise, the resulting value is unspecified.
A value of a scoped enumeration type can also be explicitly converted to a floating-point type; the result is the same as that of converting from the original value to the floating-point type.
A value of integral or enumeration type can be explicitly converted to a complete enumeration type.
The value is unchanged if the original value is within the range of the enumeration values ([dcl.enum]).
Otherwise, the behavior is undefined.
A value of floating-point type can also be explicitly converted to an enumeration type.
The resulting value is the same as converting the original value to the underlying type of the enumeration ([conv.fpint]), and subsequently to the enumeration type.
A prvalue of type “pointer to cv1 B”, where B is a class type, can be converted to a prvalue of type “pointer to cv2 D”, where D is a class derived (Clause [class.derived]) from B, if cv2 is the same cv-qualification as, or greater cv-qualification than, cv1.
If B is a virtual base class of D or a base class of a virtual base class of D, or if no valid standard conversion from “pointer to D” to “pointer to B” exists ([conv.ptr]), the program is ill-formed.
The null pointer value ([conv.ptr]) is converted to the null pointer value of the destination type.
If the prvalue of type “pointer to cv1 B” points to a B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object of type D.
Otherwise, the behavior is undefined.
A prvalue of type “pointer to member of D of type cv1 T” can be converted to a prvalue of type “pointer to member of B of type cv2 T”, where B is a base class (Clause [class.derived]) of D, if cv2 is the same cv-qualification as, or greater cv-qualification than, cv1.72
If no valid standard conversion from “pointer to member of B of type T” to “pointer to member of D of type T” exists ([conv.mem]), the program is ill-formed.
The null member pointer value ([conv.mem]) is converted to the null member pointer value of the destination type.
If class B contains the original member, or is a base or derived class of the class containing the original member, the resulting pointer to member points to the original member.
Otherwise, the behavior is undefined.
[Note
:
Although class B need not contain the original member, the dynamic type of the object with which indirection through the pointer to member is performed must contain the original member; see [expr.mptr.oper].
end note
]
A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1.
If the original pointer value represents the address A of a byte in memory and A does not satisfy the alignment requirement of T, then the resulting pointer value is unspecified.
Otherwise, if the original pointer value points to an object a, and there is an object b of type T (ignoring cv-qualification) that is pointer-interconvertible ([basic.compound]) with a, the result is a pointer to b.
Otherwise, the pointer value is unchanged by the conversion.
[Example
:
T* p1 = new T;
const T* p2 = static_cast<const T*>(static_cast<void*>(p1));
bool b = p1 == p2;  // b will have the value true.
end example
]
Function types (including those used in pointer to member function types) are never cv-qualified; see [dcl.fct].

8.2.10 Reinterpret cast [expr.reinterpret.cast]

The result of the expression reinterpret_­cast<T>(v) is the result of converting the expression v to type T.
If T is an lvalue reference type or an rvalue reference to function type, the result is an lvalue; if T is an rvalue reference to object type, the result is an xvalue; otherwise, the result is a prvalue and the lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions are performed on the expression v.
Conversions that can be performed explicitly using reinterpret_­cast are listed below.
No other conversion can be performed explicitly using reinterpret_­cast.
The reinterpret_­cast operator shall not cast away constness ([expr.const.cast]).
An expression of integral, enumeration, pointer, or pointer-to-member type can be explicitly converted to its own type; such a cast yields the value of its operand.
[Note
:
The mapping performed by reinterpret_­cast might, or might not, produce a representation different from the original value.
end note
]
A pointer can be explicitly converted to any integral type large enough to hold it.
The mapping function is implementation-defined.
[Note
:
It is intended to be unsurprising to those who know the addressing structure of the underlying machine.
end note
]
A value of type std​::​nullptr_­t can be converted to an integral type; the conversion has the same meaning and validity as a conversion of (void*)0 to the integral type.
[Note
:
A reinterpret_­cast cannot be used to convert a value of any type to the type std​::​nullptr_­t.
end note
]
A value of integral type or enumeration type can be explicitly converted to a pointer.
A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined.
[Note
:
Except as described in [basic.stc.dynamic.safety], the result of such a conversion will not be a safely-derived pointer value.
end note
]
A function pointer can be explicitly converted to a function pointer of a different type.
[Note
:
The effect of calling a function through a pointer to a function type ([dcl.fct]) that is not the same as the type used in the definition of the function is undefined.
end note
]
Except that converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.
[Note
:
See also [conv.ptr] for more details of pointer conversions.
end note
]
An object pointer can be explicitly converted to an object pointer of a different type.73
When a prvalue v of object pointer type is converted to the object pointer type “pointer to cv T”, the result is static_­cast<cv T*>(static_­cast<cv void*>(v)).
[Note
:
Converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value.
end note
]
Converting a function pointer to an object pointer type or vice versa is conditionally-supported.
The meaning of such a conversion is implementation-defined, except that if an implementation supports conversions in both directions, converting a prvalue of one type to the other type and back, possibly with different cv-qualification, shall yield the original pointer value.
The null pointer value ([conv.ptr]) is converted to the null pointer value of the destination type.
[Note
:
A null pointer constant of type std​::​nullptr_­t cannot be converted to a pointer type, and a null pointer constant of integral type is not necessarily converted to a null pointer value.
end note
]
A prvalue of type “pointer to member of X of type T1” can be explicitly converted to a prvalue of a different type “pointer to member of Y of type T2” if T1 and T2 are both function types or both object types.74
The null member pointer value ([conv.mem]) is converted to the null member pointer value of the destination type.
The result of this conversion is unspecified, except in the following cases:
  • converting a prvalue of type “pointer to member function” to a different pointer to member function type and back to its original type yields the original pointer to member value.
  • converting a prvalue of type “pointer to data member of X of type T1” to the type “pointer to data member of Y of type T2” (where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer to member value.
A glvalue expression of type T1 can be cast to the type “reference to T2” if an expression of type “pointer to T1” can be explicitly converted to the type “pointer to T2” using a reinterpret_­cast.
The result refers to the same object as the source glvalue, but with the specified type.
[Note
:
That is, for lvalues, a reference cast reinterpret_­cast<T&>(x) has the same effect as the conversion *reinterpret_­cast<T*>(&x) with the built-in & and * operators (and similarly for reinterpret_­cast<T&&>(x)).
end note
]
No temporary is created, no copy is made, and constructors ([class.ctor]) or conversion functions ([class.conv]) are not called.75
The types may have different cv-qualifiers, subject to the overall restriction that a reinterpret_­cast cannot cast away constness.
T1 and T2 may have different cv-qualifiers, subject to the overall restriction that a reinterpret_­cast cannot cast away constness.
This is sometimes referred to as a type pun.

8.2.11 Const cast [expr.const.cast]

The result of the expression const_­cast<T>(v) is of type T.
If T is an lvalue reference to object type, the result is an lvalue; if T is an rvalue reference to object type, the result is an xvalue; otherwise, the result is a prvalue and the lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions are performed on the expression v.
Conversions that can be performed explicitly using const_­cast are listed below.
No other conversion shall be performed explicitly using const_­cast.
[Note
:
Subject to the restrictions in this section, an expression may be cast to its own type using a const_­cast operator.
end note
]
For two similar types T1 and T2 ([conv.qual]), a prvalue of type T1 may be explicitly converted to the type T2 using a const_­cast.
The result of a const_­cast refers to the original entity.
[Example
:
typedef int *A[3];               // array of 3 pointer to int
typedef const int *const CA[3];  // array of 3 const pointer to const int

CA &&r = A{}; // OK, reference binds to temporary array object after qualification conversion to type CA
A &&r1 = const_cast<A>(CA{});    // error: temporary array decayed to pointer
A &&r2 = const_cast<A&&>(CA{});  // OK
end example
]
For two object types T1 and T2, if a pointer to T1 can be explicitly converted to the type “pointer to T2” using a const_­cast, then the following conversions can also be made:
  • an lvalue of type T1 can be explicitly converted to an lvalue of type T2 using the cast const_­cast<T2&>;
  • a glvalue of type T1 can be explicitly converted to an xvalue of type T2 using the cast const_­cast<T2&&>; and
  • if T1 is a class type, a prvalue of type T1 can be explicitly converted to an xvalue of type T2 using the cast const_­cast<T2&&>.
The result of a reference const_­cast refers to the original object if the operand is a glvalue and to the result of applying the temporary materialization conversion ([conv.rval]) otherwise.
A null pointer value ([conv.ptr]) is converted to the null pointer value of the destination type.
The null member pointer value ([conv.mem]) is converted to the null member pointer value of the destination type.
[Note
:
Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_­cast that casts away a const-qualifier76 may produce undefined behavior ([dcl.type.cv]).
end note
]
A conversion from a type T1 to a type T2 casts away constness if T1 and T2 are different, there is a cv-decomposition ([conv.qual]) of T1 yielding n such that T2 has a cv-decomposition of the form
, and there is no qualification conversion that converts T1 to
.
Casting from an lvalue of type T1 to an lvalue of type T2 using an lvalue reference cast or casting from an expression of type T1 to an xvalue of type T2 using an rvalue reference cast casts away constness if a cast from a prvalue of type “pointer to T1” to the type “pointer to T2” casts away constness.
[Note
:
Some conversions which involve only changes in cv-qualification cannot be done using const_­cast. For instance, conversions between pointers to functions are not covered because such conversions lead to values whose use causes undefined behavior.
For the same reasons, conversions between pointers to member functions, and in particular, the conversion from a pointer to a const member function to a pointer to a non-const member function, are not covered.
end note
]
const_­cast is not limited to conversions that cast away a const-qualifier.

8.3 Unary expressions [expr.unary]

Expressions with unary operators group right-to-left.

8.3.1 Unary operators [expr.unary.op]

The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points.
If the type of the expression is “pointer to T”, the type of the result is “T.
[Note
:
Indirection through a pointer to an incomplete type (other than cv void) is valid.
The lvalue thus obtained can be used in limited ways (to initialize a reference, for example); this lvalue must not be converted to a prvalue, see [conv.lval].
end note
]
The result of each of the following unary operators is a prvalue.
The result of the unary & operator is a pointer to its operand.
The operand shall be an lvalue or a qualified-id.
If the operand is a qualified-id naming a non-static or variant member m of some class C with type T, the result has type “pointer to member of class C of type T” and is a prvalue designating C​::​m.
Otherwise, if the type of the expression is T, the result has type “pointer to T” and is a prvalue that is the address of the designated object ([intro.memory]) or a pointer to the designated function.
[Note
:
In particular, the address of an object of type “cv T” is “pointer to cv T”, with the same cv-qualification.
end note
]
For purposes of pointer arithmetic ([expr.add]) and comparison ([expr.rel], [expr.eq]), an object that is not an array element whose address is taken in this way is considered to belong to an array with one element of type T.
[Example
:
struct A { int i; };
struct B : A { };
... &B::i ...       // has type int A​::​*
int a;
int* p1 = &a;
int* p2 = p1 + 1;   // defined behavior
bool b = p2 > p1;   // defined behavior, with value true
end example
]
[Note
:
A pointer to member formed from a mutable non-static data member ([dcl.stc]) does not reflect the mutable specifier associated with the non-static data member.
end note
]
A pointer to member is only formed when an explicit & is used and its operand is a qualified-id not enclosed in parentheses.
[Note
:
That is, the expression &(qualified-id), where the qualified-id is enclosed in parentheses, does not form an expression of type “pointer to member”.
Neither does qualified-id, because there is no implicit conversion from a qualified-id for a non-static member function to the type “pointer to member function” as there is from an lvalue of function type to the type “pointer to function” ([conv.func]).
Nor is &unqualified-id a pointer to member, even within the scope of the unqualified-id's class.
end note
]
If & is applied to an lvalue of incomplete class type and the complete type declares operator&(), it is unspecified whether the operator has the built-in meaning or the operator function is called.
The operand of & shall not be a bit-field.
The address of an overloaded function (Clause [over]) can be taken only in a context that uniquely determines which version of the overloaded function is referred to (see [over.over]).
[Note
:
Since the context might determine whether the operand is a static or non-static member function, the context can also affect whether the expression has type “pointer to function” or “pointer to member function”.
end note
]
The operand of the unary + operator shall have arithmetic, unscoped enumeration, or pointer type and the result is the value of the argument.
Integral promotion is performed on integral or enumeration operands.
The type of the result is the type of the promoted operand.
The operand of the unary - operator shall have arithmetic or unscoped enumeration type and the result is the negation of its operand.
Integral promotion is performed on integral or enumeration operands.
The negative of an unsigned quantity is computed by subtracting its value from , where n is the number of bits in the promoted operand.
The type of the result is the type of the promoted operand.
The operand of the logical negation operator ! is contextually converted to bool (Clause [conv]); its value is true if the converted operand is false and false otherwise.
The type of the result is bool.
The operand of ~ shall have integral or unscoped enumeration type; the result is the ones' complement of its operand.
Integral promotions are performed.
The type of the result is the type of the promoted operand.
There is an ambiguity in the grammar when ~ is followed by a class-name or decltype-specifier.
The ambiguity is resolved by treating ~ as the unary complement operator rather than as the start of an unqualified-id naming a destructor.
[Note
:
Because the grammar does not permit an operator to follow the ., ->, or ​::​ tokens, a ~ followed by a class-name or decltype-specifier in a member access expression or qualified-id is unambiguously parsed as a destructor name.
end note
]

8.3.2 Increment and decrement [expr.pre.incr]

The operand of prefix ++ is modified by adding 1.
The operand shall be a modifiable lvalue.
The type of the operand shall be an arithmetic type other than cv bool, or a pointer to a completely-defined object type.
The result is the updated operand; it is an lvalue, and it is a bit-field if the operand is a bit-field.
The expression ++x is equivalent to x+=1.
[Note
:
See the discussions of addition ([expr.add]) and assignment operators ([expr.ass]) for information on conversions.
end note
]
The operand of prefix -- is modified by subtracting 1.
The requirements on the operand of prefix -- and the properties of its result are otherwise the same as those of prefix ++.
[Note
:
For postfix increment and decrement, see [expr.post.incr].
end note
]

8.3.3 Sizeof [expr.sizeof]

The sizeof operator yields the number of bytes in the object representation of its operand.
The operand is either an expression, which is an unevaluated operand (Clause [expr]), or a parenthesized type-id.
The sizeof operator shall not be applied to an expression that has function or incomplete type, to the parenthesized name of such types, or to a glvalue that designates a bit-field.
sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1.
The result of sizeof applied to any other fundamental type ([basic.fundamental]) is implementation-defined.
[Note
:
In particular, sizeof(bool), sizeof(char16_­t), sizeof(char32_­t), and sizeof(wchar_­t) are implementation-defined.77
end note
]
[Note
:
See [intro.memory] for the definition of byte and [basic.types] for the definition of object representation.
end note
]
When applied to a reference or a reference type, the result is the size of the referenced type.
When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array.
The size of a most derived class shall be greater than zero ([intro.object]).
The result of applying sizeof to a base class subobject is the size of the base class type.78
When applied to an array, the result is the total number of bytes in the array.
This implies that the size of an array of n elements is n times the size of an element.
The sizeof operator can be applied to a pointer to a function, but shall not be applied directly to a function.
The lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions are not applied to the operand of sizeof.
If the operand is a prvalue, the temporary materialization conversion ([conv.rval]) is applied.
The identifier in a sizeof... expression shall name a parameter pack.
The sizeof... operator yields the number of arguments provided for the parameter pack identifier.
A sizeof... expression is a pack expansion ([temp.variadic]).
[Example
:
template<class... Types>
struct count {
  static const std::size_t value = sizeof...(Types);
};
end example
]
The result of sizeof and sizeof... is a constant of type std​::​size_­t.
[Note
:
std​::​size_­t is defined in the standard header <cstddef> ([cstddef.syn], [support.types.layout]).
end note
]
sizeof(bool) is not required to be 1.
The actual size of a base class subobject may be less than the result of applying sizeof to the subobject, due to virtual base classes and less strict padding requirements on base class subobjects.

8.3.4 New [expr.new]

The new-expression attempts to create an object of the type-id or new-type-id to which it is applied.
The type of that object is the allocated type.
This type shall be a complete object type, but not an abstract class type or array thereof ([intro.object], [basic.types], [class.abstract]).
[Note
:
Because references are not objects, references cannot be created by new-expressions.
end note
]
[Note
:
The type-id may be a cv-qualified type, in which case the object created by the new-expression has a cv-qualified type.
end note
]
[Note
:
The lifetime of such an entity is not necessarily restricted to the scope in which it is created.
end note
]
If the entity is a non-array object, the new-expression returns a pointer to the object created.
If it is an array, the new-expression returns a pointer to the initial element of the array.
If a placeholder type ([dcl.spec.auto]) appears in the type-specifier-seq of a new-type-id or type-id of a new-expression, the allocated type is deduced as follows: Let init be the new-initializer, if any, and T be the new-type-id or type-id of the new-expression, then the allocated type is the type deduced for the variable x in the invented declaration ([dcl.spec.auto]):
T x init ;
[Example
:
new auto(1);                    // allocated type is int
auto x = new auto('a');         // allocated type is char, x is of type char*

template<class T> struct A { A(T, T); };
auto y = new A{1, 2};           // allocated type is A<int>
end example
]
The new-type-id in a new-expression is the longest possible sequence of new-declarators.
[Note
:
This prevents ambiguities between the declarator operators &, &&, *, and [] and their expression counterparts.
end note
]
[Example
:
new int * i;                    // syntax error: parsed as (new int*) i, not as (new int)*i
The * is the pointer declarator and not the multiplication operator.
end example
]
[Note
:
Parentheses in a new-type-id of a new-expression can have surprising effects.
[Example
:
new int(*[10])();               // error
is ill-formed because the binding is
(new int) (*[10])();            // error
Instead, the explicitly parenthesized version of the new operator can be used to create objects of compound types ([basic.compound]):
new (int (*[10])());
allocates an array of 10 pointers to functions (taking no argument and returning int).
end example
]
end note
]
When the allocated object is an array (that is, the noptr-new-declarator syntax is used or the new-type-id or type-id denotes an array type), the new-expression yields a pointer to the initial element (if any) of the array.
[Note
:
Both new int and new int[10] have type int* and the type of new int[i][10] is int (*)[10]
end note
]
The attribute-specifier-seq in a noptr-new-declarator appertains to the associated array type.
Every constant-expression in a noptr-new-declarator shall be a converted constant expression ([expr.const]) of type std​::​size_­t and shall evaluate to a strictly positive value.
The expression in a noptr-new-declarator is implicitly converted to std​::​size_­t.
[Example
:
Given the definition int n = 42, new float[n][5] is well-formed (because n is the expression of a noptr-new-declarator), but new float[5][n] is ill-formed (because n is not a constant expression).
end example
]
The expression in a noptr-new-declarator is erroneous if:
  • the expression is of non-class type and its value before converting to std​::​size_­t is less than zero;
  • the expression is of class type and its value before application of the second standard conversion ([over.ics.user])79 is less than zero;
  • its value is such that the size of the allocated object would exceed the implementation-defined limit (Annex [implimits]); or
  • the new-initializer is a braced-init-list and the number of array elements for which initializers are provided (including the terminating '\0' in a string literal ([lex.string])) exceeds the number of elements to initialize.
If the expression is erroneous after converting to std​::​size_­t:
  • if the expression is a core constant expression, the program is ill-formed;
  • otherwise, an allocation function is not called; instead
When the value of the expression is zero, the allocation function is called to allocate an array with no elements.
A new-expression may obtain storage for the object by calling an allocation function ([basic.stc.dynamic.allocation]).
If the new-expression terminates by throwing an exception, it may release storage by calling a deallocation function ([basic.stc.dynamic.deallocation]).
If the allocated type is a non-array type, the allocation function's name is operator new and the deallocation function's name is operator delete.
If the allocated type is an array type, the allocation function's name is operator new[] and the deallocation function's name is operator delete[].
[Note
:
An implementation shall provide default definitions for the global allocation functions ([basic.stc.dynamic], [new.delete.single], [new.delete.array]).
A C++ program can provide alternative definitions of these functions ([replacement.functions]) and/or class-specific versions ([class.free]).
The set of allocation and deallocation functions that may be called by a new-expression may include functions that do not perform allocation or deallocation; for example, see [new.delete.placement].
end note
]
If the new-expression begins with a unary ​::​ operator, the allocation function's name is looked up in the global scope.
Otherwise, if the allocated type is a class type T or array thereof, the allocation function's name is looked up in the scope of T.
If this lookup fails to find the name, or if the allocated type is not a class type, the allocation function's name is looked up in the global scope.
An implementation is allowed to omit a call to a replaceable global allocation function ([new.delete.single], [new.delete.array]).
When it does so, the storage is instead provided by the implementation or provided by extending the allocation of another new-expression.
The implementation may extend the allocation of a new-expression e1 to provide storage for a new-expression e2 if the following would be true were the allocation not extended:
  • the evaluation of e1 is sequenced before the evaluation of e2, and
  • e2 is evaluated whenever e1 obtains storage, and
  • both e1 and e2 invoke the same replaceable global allocation function, and
  • if the allocation function invoked by e1 and e2 is throwing, any exceptions thrown in the evaluation of either e1 or e2 would be first caught in the same handler, and
  • the pointer values produced by e1 and e2 are operands to evaluated delete-expressions, and
  • the evaluation of e2 is sequenced before the evaluation of the delete-expression whose operand is the pointer value produced by e1.
[Example
:
  void mergeable(int x) {
    // These allocations are safe for merging:
    std::unique_ptr<char[]> a{new (std::nothrow) char[8]};
    std::unique_ptr<char[]> b{new (std::nothrow) char[8]};
    std::unique_ptr<char[]> c{new (std::nothrow) char[x]};

    g(a.get(), b.get(), c.get());
  }

  void unmergeable(int x) {
    std::unique_ptr<char[]> a{new char[8]};
    try {
      // Merging this allocation would change its catch handler.
      std::unique_ptr<char[]> b{new char[x]};
    } catch (const std::bad_alloc& e) {
      std::cerr << "Allocation failed: " << e.what() << std::endl;
      throw;
    }
  }
end example
]
When a new-expression calls an allocation function and that allocation has not been extended, the new-expression passes the amount of space requested to the allocation function as the first argument of type std​::​size_­t.
That argument shall be no less than the size of the object being created; it may be greater than the size of the object being created only if the object is an array.
For arrays of char, unsigned char, and std​::​byte, the difference between the result of the new-expression and the address returned by the allocation function shall be an integral multiple of the strictest fundamental alignment requirement ([basic.align]) of any object type whose size is no greater than the size of the array being created.
[Note
:
Because allocation functions are assumed to return pointers to storage that is appropriately aligned for objects of any type with fundamental alignment, this constraint on array allocation overhead permits the common idiom of allocating character arrays into which objects of other types will later be placed.
end note
]
When a new-expression calls an allocation function and that allocation has been extended, the size argument to the allocation call shall be no greater than the sum of the sizes for the omitted calls as specified above, plus the size for the extended call had it not been extended, plus any padding necessary to align the allocated objects within the allocated memory.
The new-placement syntax is used to supply additional arguments to an allocation function; such an expression is called a placement new-expression.
Overload resolution is performed on a function call created by assembling an argument list.
The first argument is the amount of space requested, and has type std​::​size_­t.
If the type of the allocated object has new-extended alignment, the next argument is the type's alignment, and has type std​::​align_­val_­t.
If the new-placement syntax is used, the initializer-clauses in its expression-list are the succeeding arguments.
If no matching function is found and the allocated object type has new-extended alignment, the alignment argument is removed from the argument list, and overload resolution is performed again.
[Example
:
  • new T results in one of the following calls:
    operator new(sizeof(T))
    operator new(sizeof(T), std::align_val_t(alignof(T)))
  • new(2,f) T results in one of the following calls:
    operator new(sizeof(T), 2, f)
    operator new(sizeof(T), std::align_val_t(alignof(T)), 2, f)
  • new T[5] results in one of the following calls:
    operator new[](sizeof(T) * 5 + x)
    operator new[](sizeof(T) * 5 + x, std::align_val_t(alignof(T)))
  • new(2,f) T[5] results in one of the following calls:
    operator new[](sizeof(T) * 5 + x, 2, f)
    operator new[](sizeof(T) * 5 + x, std::align_val_t(alignof(T)), 2, f)
Here, each instance of x is a non-negative unspecified value representing array allocation overhead; the result of the new-expression will be offset by this amount from the value returned by operator new[].
This overhead may be applied in all array new-expressions, including those referencing the library function operator new[](std​::​size_­t, void*) and other placement allocation functions.
The amount of overhead may vary from one invocation of new to another.
end example
]
[Note
:
Unless an allocation function has a non-throwing exception specification ([except.spec]), it indicates failure to allocate storage by throwing a std​::​bad_­alloc exception ([basic.stc.dynamic.allocation], Clause [except], [bad.alloc]); it returns a non-null pointer otherwise.
If the allocation function has a non-throwing exception specification, it returns null to indicate failure to allocate storage and a non-null pointer otherwise.
end note
]
If the allocation function is a non-allocating form ([new.delete.placement]) that returns null, the behavior is undefined.
Otherwise, if the allocation function returns null, initialization shall not be done, the deallocation function shall not be called, and the value of the new-expression shall be null.
[Note
:
When the allocation function returns a value other than null, it must be a pointer to a block of storage in which space for the object has been reserved.
The block of storage is assumed to be appropriately aligned and of the requested size.
The address of the created object will not necessarily be the same as that of the block if the object is an array.
end note
]
A new-expression that creates an object of type T initializes that object as follows:
The invocation of the allocation function is sequenced before the evaluations of expressions in the new-initializer.
Initialization of the allocated object is sequenced before the value computation of the new-expression.
If the new-expression creates an object or an array of objects of class type, access and ambiguity control are done for the allocation function, the deallocation function ([class.free]), and the constructor ([class.ctor]).
If the new-expression creates an array of objects of class type, the destructor is potentially invoked ([class.dtor]).
If any part of the object initialization described above80 terminates by throwing an exception and a suitable deallocation function can be found, the deallocation function is called to free the memory in which the object was being constructed, after which the exception continues to propagate in the context of the new-expression.
If no unambiguous matching deallocation function can be found, propagating the exception does not cause the object's memory to be freed.
[Note
:
This is appropriate when the called allocation function does not allocate memory; otherwise, it is likely to result in a memory leak.
end note
]
If the new-expression begins with a unary ​::​ operator, the deallocation function's name is looked up in the global scope.
Otherwise, if the allocated type is a class type T or an array thereof, the deallocation function's name is looked up in the scope of T.
If this lookup fails to find the name, or if the allocated type is not a class type or array thereof, the deallocation function's name is looked up in the global scope.
A declaration of a placement deallocation function matches the declaration of a placement allocation function if it has the same number of parameters and, after parameter transformations ([dcl.fct]), all parameter types except the first are identical.
If the lookup finds a single matching deallocation function, that function will be called; otherwise, no deallocation function will be called.
If the lookup finds a usual deallocation function with a parameter of type std​::​size_­t ([basic.stc.dynamic.deallocation]) and that function, considered as a placement deallocation function, would have been selected as a match for the allocation function, the program is ill-formed.
For a non-placement allocation function, the normal deallocation function lookup is used to find the matching deallocation function ([expr.delete])
[Example
:
struct S {
  // Placement allocation function:
  static void* operator new(std::size_t, std::size_t);

  // Usual (non-placement) deallocation function:
  static void operator delete(void*, std::size_t);
};

S* p = new (0) S;   // ill-formed: non-placement deallocation function matches
                    // placement allocation function
end example
]
If a new-expression calls a deallocation function, it passes the value returned from the allocation function call as the first argument of type void*.
If a placement deallocation function is called, it is passed the same additional arguments as were passed to the placement allocation function, that is, the same arguments as those specified with the new-placement syntax.
If the implementation is allowed to make a copy of any argument as part of the call to the allocation function, it is allowed to make a copy (of the same original value) as part of the call to the deallocation function or to reuse the copy made as part of the call to the allocation function.
If the copy is elided in one place, it need not be elided in the other.
If the conversion function returns a signed integer type, the second standard conversion converts to the unsigned type std​::​size_­t and thus thwarts any attempt to detect a negative value afterwards.
This may include evaluating a new-initializer and/or calling a constructor.

8.3.5 Delete [expr.delete]

The delete-expression operator destroys a most derived object ([intro.object]) or array created by a new-expression.
delete-expression:
	:: delete cast-expression
	:: delete [ ] cast-expression
The first alternative is for non-array objects, and the second is for arrays.
Whenever the delete keyword is immediately followed by empty square brackets, it shall be interpreted as the second alternative.81
The operand shall be of pointer to object type or of class type.
If of class type, the operand is contextually implicitly converted (Clause [conv]) to a pointer to object type.82
The delete-expression's result has type void.
If the operand has a class type, the operand is converted to a pointer type by calling the above-mentioned conversion function, and the converted operand is used in place of the original operand for the remainder of this section.
In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject ([intro.object]) representing a base class of such an object (Clause [class.derived]).
If not, the behavior is undefined.
In the second alternative (delete array), the value of the operand of delete may be a null pointer value or a pointer value that resulted from a previous array new-expression.83
If not, the behavior is undefined.
[Note
:
This means that the syntax of the delete-expression must match the type of the object allocated by new, not the syntax of the new-expression.
end note
]
[Note
:
A pointer to a const type can be the operand of a delete-expression; it is not necessary to cast away the constness ([expr.const.cast]) of the pointer expression before it is used as the operand of the delete-expression.
end note
]
In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.
In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.
The cast-expression in a delete-expression shall be evaluated exactly once.
If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined.
If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted.
In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see [class.base.init]).
If the value of the operand of the delete-expression is not a null pointer value, then:
[Note
:
The deallocation function is called regardless of whether the destructor for the object or some element of the array throws an exception.
end note
]
If the value of the operand of the delete-expression is a null pointer value, it is unspecified whether a deallocation function will be called as described above.
[Note
:
An implementation provides default definitions of the global deallocation functions operator delete for non-arrays ([new.delete.single]) and operator delete[] for arrays ([new.delete.array]).
A C++ program can provide alternative definitions of these functions ([replacement.functions]), and/or class-specific versions ([class.free]).
end note
]
When the keyword delete in a delete-expression is preceded by the unary ​::​ operator, the deallocation function's name is looked up in global scope.
Otherwise, the lookup considers class-specific deallocation functions ([class.free]).
If no class-specific deallocation function is found, the deallocation function's name is looked up in global scope.
If deallocation function lookup finds more than one usual deallocation function, the function to be called is selected as follows:
  • If the type has new-extended alignment, a function with a parameter of type std​::​align_­val_­t is preferred; otherwise a function without such a parameter is preferred.
    If exactly one preferred function is found, that function is selected and the selection process terminates.
    If more than one preferred function is found, all non-preferred functions are eliminated from further consideration.
  • If the deallocation functions have class scope, the one without a parameter of type std​::​size_­t is selected.
  • If the type is complete and if, for the second alternative (delete array) only, the operand is a pointer to a class type with a non-trivial destructor or a (possibly multi-dimensional) array thereof, the function with a parameter of type std​::​size_­t is selected.
  • Otherwise, it is unspecified whether a deallocation function with a parameter of type std​::​size_­t is selected.
When a delete-expression is executed, the selected deallocation function shall be called with the address of the most-derived object in the delete object case, or the address of the object suitably adjusted for the array allocation overhead ([expr.new]) in the delete array case, as its first argument.
If a deallocation function with a parameter of type std​::​align_­val_­t is used, the alignment of the type of the object to be deleted is passed as the corresponding argument.
If a deallocation function with a parameter of type std​::​size_­t is used, the size of the most-derived type, or of the array plus allocation overhead, respectively, is passed as the corresponding argument.84
[Note
:
If this results in a call to a usual deallocation function, and either the first argument was not the result of a prior call to a usual allocation function or the second argument was not the corresponding argument in said call, the behavior is undefined ([new.delete.single], [new.delete.array]).
end note
]
Access and ambiguity control are done for both the deallocation function and the destructor ([class.dtor], [class.free]).
A lambda expression with a lambda-introducer that consists of empty square brackets can follow the delete keyword if the lambda expression is enclosed in parentheses.
This implies that an object cannot be deleted using a pointer of type void* because void is not an object type.
For nonzero-length arrays, this is the same as a pointer to the first element of the array created by that new-expression.
Zero-length arrays do not have a first element.
If the static type of the object to be deleted is complete and is different from the dynamic type, and the destructor is not virtual, the size might be incorrect, but that case is already undefined, as stated above.

8.3.6 Alignof [expr.alignof]

An alignof expression yields the alignment requirement of its operand type.
The operand shall be a type-id representing a complete object type, or an array thereof, or a reference to one of those types.
The result is an integral constant of type std​::​size_­t.
When alignof is applied to a reference type, the result is the alignment of the referenced type.
When alignof is applied to an array type, the result is the alignment of the element type.

8.3.7 noexcept operator [expr.unary.noexcept]

The noexcept operator determines whether the evaluation of its operand, which is an unevaluated operand (Clause [expr]), can throw an exception ([except.throw]).
The result of the noexcept operator is a constant of type bool and is a prvalue.
The result of the noexcept operator is true unless the expression is potentially-throwing ([except.spec]).

8.4 Explicit type conversion (cast notation) [expr.cast]

The result of the expression (T) cast-expression is of type T.
The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type and an xvalue if T is an rvalue reference to object type; otherwise the result is a prvalue.
[Note
:
If T is a non-class type that is cv-qualified, the cv-qualifiers are discarded when determining the type of the resulting prvalue; see Clause [expr].
end note
]
An explicit type conversion can be expressed using functional notation ([expr.type.conv]), a type conversion operator (dynamic_­cast, static_­cast, reinterpret_­cast, const_­cast), or the cast notation.
Any type conversion not mentioned below and not explicitly defined by the user ([class.conv]) is ill-formed.
The conversions performed by
can be performed using the cast notation of explicit type conversion.
The same semantic restrictions and behaviors apply, with the exception that in performing a static_­cast in the following situations the conversion is valid even if the base class is inaccessible:
  • a pointer to an object of derived class type or an lvalue or rvalue of derived class type may be explicitly converted to a pointer or reference to an unambiguous base class type, respectively;
  • a pointer to member of derived class type may be explicitly converted to a pointer to member of an unambiguous non-virtual base class type;
  • a pointer to an object of an unambiguous non-virtual base class type, a glvalue of an unambiguous non-virtual base class type, or a pointer to member of an unambiguous non-virtual base class type may be explicitly converted to a pointer, a reference, or a pointer to member of a derived class type, respectively.
If a conversion can be interpreted in more than one of the ways listed above, the interpretation that appears first in the list is used, even if a cast resulting from that interpretation is ill-formed.
If a conversion can be interpreted in more than one way as a static_­cast followed by a const_­cast, the conversion is ill-formed.
[Example
:
struct A { };
struct I1 : A { };
struct I2 : A { };
struct D : I1, I2 { };
A* foo( D* p ) {
  return (A*)( p );             // ill-formed static_­cast interpretation
}
end example
]
The operand of a cast using the cast notation can be a prvalue of type “pointer to incomplete class type”.
The destination type of a cast using the cast notation can be “pointer to incomplete class type”.
If both the operand and destination types are class types and one or both are incomplete, it is unspecified whether the static_­cast or the reinterpret_­cast interpretation is used, even if there is an inheritance relationship between the two classes.
[Note
:
For example, if the classes were defined later in the translation unit, a multi-pass compiler would be permitted to interpret a cast between pointers to the classes as if the class types were complete at the point of the cast.
end note
]

8.5 Pointer-to-member operators [expr.mptr.oper]

The pointer-to-member operators ->* and .* group left-to-right.
The binary operator .* binds its second operand, which shall be of type “pointer to member of T” to its first operand, which shall be a glvalue of class T or of a class of which T is an unambiguous and accessible base class.
The result is an object or a function of the type specified by the second operand.
The binary operator ->* binds its second operand, which shall be of type “pointer to member of T” to its first operand, which shall be of type “pointer to U” where U is either T or a class of which T is an unambiguous and accessible base class.
The expression E1->*E2 is converted into the equivalent form (*(E1)).*E2.
Abbreviating pm-expression.*cast-expression as E1.*E2, E1 is called the object expression.
If the dynamic type of E1 does not contain the member to which E2 refers, the behavior is undefined.
Otherwise, the expression E1 is sequenced before the expression E2.
The restrictions on cv-qualification, and the manner in which the cv-qualifiers of the operands are combined to produce the cv-qualifiers of the result, are the same as the rules for E1.E2 given in [expr.ref].
[Note
:
It is not possible to use a pointer to member that refers to a mutable member to modify a const class object.
For example,
struct S {
  S() : i(0) { }
  mutable int i;
};
void f()
{
const S cs;
int S::* pm = &S::i;            // pm refers to mutable member S​::​i
cs.*pm = 88;                    // ill-formed: cs is a const object
}
end note
]
If the result of .* or ->* is a function, then that result can be used only as the operand for the function call operator ().
[Example
:
(ptr_to_obj->*ptr_to_mfct)(10);
calls the member function denoted by ptr_­to_­mfct for the object pointed to by ptr_­to_­obj.
end example
]
In a .* expression whose object expression is an rvalue, the program is ill-formed if the second operand is a pointer to member function with ref-qualifier &.
In a .* expression whose object expression is an lvalue, the program is ill-formed if the second operand is a pointer to member function with ref-qualifier &&.
The result of a .* expression whose second operand is a pointer to a data member is an lvalue if the first operand is an lvalue and an xvalue otherwise.
The result of a .* expression whose second operand is a pointer to a member function is a prvalue.
If the second operand is the null member pointer value ([conv.mem]), the behavior is undefined.

8.6 Multiplicative operators [expr.mul]

The operands of * and / shall have arithmetic or unscoped enumeration type; the operands of % shall have integral or unscoped enumeration type.
The usual arithmetic conversions are performed on the operands and determine the type of the result.
The binary * operator indicates multiplication.
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second.
If the second operand of / or % is zero the behavior is undefined.
For integral operands the / operator yields the algebraic quotient with any fractional part discarded;85 if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a; otherwise, the behavior of both a/b and a%b is undefined.
This is often called truncation towards zero.

8.7 Additive operators [expr.add]

The additive operators + and - group left-to-right.
The usual arithmetic conversions are performed for operands of arithmetic or enumeration type.
additive-expression:
	multiplicative-expression
	additive-expression + multiplicative-expression
	additive-expression - multiplicative-expression
For addition, either both operands shall have arithmetic or unscoped enumeration type, or one operand shall be a pointer to a completely-defined object type and the other shall have integral or unscoped enumeration type.
For subtraction, one of the following shall hold:
  • both operands have arithmetic or unscoped enumeration type; or
  • both operands are pointers to cv-qualified or cv-unqualified versions of the same completely-defined object type; or
  • the left operand is a pointer to a completely-defined object type and the right operand has integral or unscoped enumeration type.
The result of the binary + operator is the sum of the operands.
The result of the binary - operator is the difference resulting from the subtraction of the second operand from the first.
When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand.
If the expression P points to element x[i] of an array object x with n elements,86 the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) element if ; otherwise, the behavior is undefined.
Likewise, the expression P - J points to the (possibly-hypothetical) element if ; otherwise, the behavior is undefined.
When two pointers to elements of the same array object are subtracted, the type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined as std​::​ptrdiff_­t in the <cstddef> header ([support.types]).
If the expressions P and Q point to, respectively, elements x[i] and x[j] of the same array object x, the expression P - Q has the value ; otherwise, the behavior is undefined.
[Note
:
If the value is not in the range of representable values of type std​::​ptrdiff_­t, the behavior is undefined.
end note
]
For addition or subtraction, if the expressions P or Q have type “pointer to cv T”, where T and the array element type are not similar ([conv.qual]), the behavior is undefined.
[Note
:
In particular, a pointer to a base class cannot be used for pointer arithmetic when the array contains objects of a derived class type.
end note
]
If the value 0 is added to or subtracted from a null pointer value, the result is a null pointer value.
If two null pointer values are subtracted, the result compares equal to the value 0 converted to the type std​::​ptrdiff_­t.
An object that is not an array element is considered to belong to a single-element array for this purpose; see [expr.unary.op].
A pointer past the last element of an array x of n elements is considered to be equivalent to a pointer to a hypothetical element x[n] for this purpose; see [basic.compound].

8.8 Shift operators [expr.shift]

The shift operators << and >> group left-to-right.
shift-expression:
	additive-expression
	shift-expression << additive-expression
	shift-expression >> additive-expression
The operands shall be of integral or unscoped enumeration type and integral promotions are performed.
The type of the result is that of the promoted left operand.
The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.
The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled.
If E1 has an unsigned type, the value of the result is , reduced modulo one more than the maximum value representable in the result type.
Otherwise, if E1 has a signed type and non-negative value, and is representable in the corresponding unsigned type of the result type, then that value, converted to the result type, is the resulting value; otherwise, the behavior is undefined.
The value of E1 >> E2 is E1 right-shifted E2 bit positions.
If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of .
If E1 has a signed type and a negative value, the resulting value is implementation-defined.
The expression E1 is sequenced before the expression E2.

8.9 Relational operators [expr.rel]

The relational operators group left-to-right.
[Example
:
a<b<c means (a<b)<c and not (a<b)&&(b<c).
end example
]
The operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) all yield false or true.
The type of the result is bool.
The usual arithmetic conversions are performed on operands of arithmetic or enumeration type.
If both operands are pointers, pointer conversions ([conv.ptr]) and qualification conversions ([conv.qual]) are performed to bring them to their composite pointer type (Clause [expr]).
After conversions, the operands shall have the same type.
Comparing unequal pointers to objects87 is defined as follows:
  • If two pointers point to different elements of the same array, or to subobjects thereof, the pointer to the element with the higher subscript compares greater.
  • If two pointers point to different non-static data members of the same object, or to subobjects of such members, recursively, the pointer to the later declared member compares greater provided the two members have the same access control (Clause [class.access]) and provided their class is not a union.
  • Otherwise, neither pointer compares greater than the other.
If two operands p and q compare equal ([expr.eq]), p<=q and p>=q both yield true and p<q and p>q both yield false.
Otherwise, if a pointer p compares greater than a pointer q, p>=q, p>q, q<=p, and q<p all yield true and p<=q, p<q, q>=p, and q>p all yield false.
Otherwise, the result of each of the operators is unspecified.
If both operands (after conversions) are of arithmetic or enumeration type, each of the operators shall yield true if the specified relationship is true and false if it is false.
An object that is not an array element is considered to belong to a single-element array for this purpose; see [expr.unary.op].
A pointer past the last element of an array x of n elements is considered to be equivalent to a pointer to a hypothetical element x[n] for this purpose; see [basic.compound].

8.10 Equality operators [expr.eq]

The == (equal to) and the != (not equal to) operators group left-to-right.
The operands shall have arithmetic, enumeration, pointer, or pointer to member type, or type std​::​nullptr_­t.
The operators == and != both yield true or false, i.e., a result of type bool.
In each case below, the operands shall have the same type after the specified conversions have been applied.
If at least one of the operands is a pointer, pointer conversions ([conv.ptr]), function pointer conversions ([conv.fctptr]), and qualification conversions ([conv.qual]) are performed on both operands to bring them to their composite pointer type (Clause [expr]).
Comparing pointers is defined as follows:
  • If one pointer represents the address of a complete object, and another pointer represents the address one past the last element of a different complete object,88 the result of the comparison is unspecified.
  • Otherwise, if the pointers are both null, both point to the same function, or both represent the same address ([basic.compound]), they compare equal.
  • Otherwise, the pointers compare unequal.
If at least one of the operands is a pointer to member, pointer to member conversions ([conv.mem]) and qualification conversions ([conv.qual]) are performed on both operands to bring them to their composite pointer type (Clause [expr]).
Comparing pointers to members is defined as follows:
  • If two pointers to members are both the null member pointer value, they compare equal.
  • If only one of two pointers to members is the null member pointer value, they compare unequal.
  • If either is a pointer to a virtual member function, the result is unspecified.
  • If one refers to a member of class C1 and the other refers to a member of a different class C2, where neither is a base class of the other, the result is unspecified.
    [Example
    :
    struct A {};
    struct B : A { int x; };
    struct C : A { int x; };
    
    int A::*bx = (int(A::*))&B::x;
    int A::*cx = (int(A::*))&C::x;
    
    bool b1 = (bx == cx);   // unspecified
    
    end example
    ]
  • If both refer to (possibly different) members of the same union ([class.union]), they compare equal.
  • Otherwise, two pointers to members compare equal if they would refer to the same member of the same most derived object ([intro.object]) or the same subobject if indirection with a hypothetical object of the associated class type were performed, otherwise they compare unequal.
    [Example
    :
    struct B {
      int f();
    };
    struct L : B { };
    struct R : B { };
    struct D : L, R { };
    
    int (B::*pb)() = &B::f;
    int (L::*pl)() = pb;
    int (R::*pr)() = pb;
    int (D::*pdl)() = pl;
    int (D::*pdr)() = pr;
    bool x = (pdl == pdr);          // false
    bool y = (pb == pl);            // true
    
    end example
    ]
Two operands of type std​::​nullptr_­t or one operand of type std​::​nullptr_­t and the other a null pointer constant compare equal.
If two operands compare equal, the result is true for the == operator and false for the != operator.
If two operands compare unequal, the result is false for the == operator and true for the != operator.
Otherwise, the result of each of the operators is unspecified.
If both operands are of arithmetic or enumeration type, the usual arithmetic conversions are performed on both operands; each of the operators shall yield true if the specified relationship is true and false if it is false.
An object that is not an array element is considered to belong to a single-element array for this purpose; see [expr.unary.op].

8.11 Bitwise AND operator [expr.bit.and]

The usual arithmetic conversions are performed; the result is the bitwise AND function of the operands.
The operator applies only to integral or unscoped enumeration operands.

8.12 Bitwise exclusive OR operator [expr.xor]

The usual arithmetic conversions are performed; the result is the bitwise exclusive OR function of the operands.
The operator applies only to integral or unscoped enumeration operands.

8.13 Bitwise inclusive OR operator [expr.or]

The usual arithmetic conversions are performed; the result is the bitwise inclusive OR function of its operands.
The operator applies only to integral or unscoped enumeration operands.

8.14 Logical AND operator [expr.log.and]

The && operator groups left-to-right.
The operands are both contextually converted to bool (Clause [conv]).
The result is true if both operands are true and false otherwise.
Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.
The result is a bool.
If the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression.

8.15 Logical OR operator [expr.log.or]

The || operator groups left-to-right.
The operands are both contextually converted to bool (Clause [conv]).
It returns true if either of its operands is true, and false otherwise.
Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.
The result is a bool.
If the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression.

8.16 Conditional operator [expr.cond]

Conditional expressions group right-to-left.
The first expression is contextually converted to bool (Clause [conv]).
It is evaluated and if it is true, the result of the conditional expression is the value of the second expression, otherwise that of the third expression.
Only one of the second and third expressions is evaluated.
Every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second or third expression.
If either the second or the third operand has type void, one of the following shall hold:
  • The second or the third operand (but not both) is a (possibly parenthesized) throw-expression; the result is of the type and value category of the other.
    The conditional-expression is a bit-field if that operand is a bit-field.
  • Both the second and the third operands have type void; the result is of type void and is a prvalue.
    [Note
    :
    This includes the case where both operands are throw-expressions.
    end note
    ]
Otherwise, if the second and third operand are glvalue bit-fields of the same value category and of types cv1 T and cv2 T, respectively, the operands are considered to be of type cv T for the remainder of this section, where cv is the union of cv1 and cv2.
Otherwise, if the second and third operand have different types and either has (possibly cv-qualified) class type, or if both are glvalues of the same value category and the same type except for cv-qualification, an attempt is made to form an implicit conversion sequence ([over.best.ics]) from each of those operands to the type of the other.
[Note
:
Properties such as access, whether an operand is a bit-field, or whether a conversion function is deleted are ignored for that determination.
end note
]
Attempts are made to form an implicit conversion sequence from an operand expression E1 of type T1 to a target type related to the type T2 of the operand expression E2 as follows:
  • If E2 is an lvalue, the target type is “lvalue reference to T2”, subject to the constraint that in the conversion the reference must bind directly ([dcl.init.ref]) to an lvalue.
  • If E2 is an xvalue, the target type is “rvalue reference to T2”, subject to the constraint that the reference must bind directly.
  • If E2 is a prvalue or if neither of the conversion sequences above can be formed and at least one of the operands has (possibly cv-qualified) class type:
    • if T1 and T2 are the same class type (ignoring cv-qualification), or one is a base class of the other, and T2 is at least as cv-qualified as T1, the target type is T2,
    • otherwise, the target type is the type that E2 would have after applying the lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions.
Using this process, it is determined whether an implicit conversion sequence can be formed from the second operand to the target type determined for the third operand, and vice versa.
If both sequences can be formed, or one can be formed but it is the ambiguous conversion sequence, the program is ill-formed.
If no conversion sequence can be formed, the operands are left unchanged and further checking is performed as described below.
Otherwise, if exactly one conversion sequence can be formed, that conversion is applied to the chosen operand and the converted operand is used in place of the original operand for the remainder of this section.
[Note
:
The conversion might be ill-formed even if an implicit conversion sequence could be formed.
end note
]
If the second and third operands are glvalues of the same value category and have the same type, the result is of that type and value category and it is a bit-field if the second or the third operand is a bit-field, or if both are bit-fields.
Otherwise, the result is a prvalue.
If the second and third operands do not have the same type, and either has (possibly cv-qualified) class type, overload resolution is used to determine the conversions (if any) to be applied to the operands ([over.match.oper], [over.built]).
If the overload resolution fails, the program is ill-formed.
Otherwise, the conversions thus determined are applied, and the converted operands are used in place of the original operands for the remainder of this section.
Lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions are performed on the second and third operands.
After those conversions, one of the following shall hold:
  • The second and third operands have the same type; the result is of that type and the result object is initialized using the selected operand.
  • The second and third operands have arithmetic or enumeration type; the usual arithmetic conversions are performed to bring them to a common type, and the result is of that type.
  • One or both of the second and third operands have pointer type; pointer conversions ([conv.ptr]), function pointer conversions ([conv.fctptr]), and qualification conversions ([conv.qual]) are performed to bring them to their composite pointer type (Clause [expr]).
    The result is of the composite pointer type.
  • One or both of the second and third operands have pointer to member type; pointer to member conversions ([conv.mem]) and qualification conversions ([conv.qual]) are performed to bring them to their composite pointer type (Clause [expr]).
    The result is of the composite pointer type.
  • Both the second and third operands have type std​::​nullptr_­t or one has that type and the other is a null pointer constant.
    The result is of type std​::​nullptr_­t.

8.17 Throwing an exception [expr.throw]

A throw-expression is of type void.
Evaluating a throw-expression with an operand throws an exception ([except.throw]); the type of the exception object is determined by removing any top-level cv-qualifiers from the static type of the operand and adjusting the type from “array of T” or function type T to “pointer to T.
A throw-expression with no operand rethrows the currently handled exception ([except.handle]).
The exception is reactivated with the existing exception object; no new exception object is created.
The exception is no longer considered to be caught.
[Example
:
Code that must be executed because of an exception, but cannot completely handle the exception itself, can be written like this:
try {
    // ...
} catch (...) {     // catch all exceptions
  // respond (partially) to exception
  throw;            // pass the exception to some other handler
}
end example
]
If no exception is presently being handled, evaluating a throw-expression with no operand calls std​::​​terminate() ([except.terminate]).

8.18 Assignment and compound assignment operators [expr.ass]

The assignment operator (=) and the compound assignment operators all group right-to-left.
All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand.
The result in all cases is a bit-field if the left operand is a bit-field.
In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.
The right operand is sequenced before the left operand.
With respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation.
[Note
:
Therefore, a function call shall not intervene between the lvalue-to-rvalue conversion and the side effect associated with any single compound assignment operator.
end note
]
In simple assignment (=), the value of the expression replaces that of the object referred to by the left operand.
If the left operand is not of class type, the expression is implicitly converted (Clause [conv]) to the cv-unqualified type of the left operand.
If the left operand is of class type, the class shall be complete.
Assignment to objects of a class is defined by the copy/move assignment operator ([class.copy], [over.ass]).
[Note
:
For class objects, assignment is not in general the same as initialization ([dcl.init], [class.ctor], [class.init], [class.copy]).
end note
]
When the left operand of an assignment operator is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.
The behavior of an expression of the form E1 op= E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.
In += and -=, E1 shall either have arithmetic type or be a pointer to a possibly cv-qualified completely-defined object type.
In all other cases, E1 shall have arithmetic type.
If the value being stored in an object is read via another object that overlaps in any way the storage of the first object, then the overlap shall be exact and the two objects shall have the same type, otherwise the behavior is undefined.
[Note
:
This restriction applies to the relationship between the left and right sides of the assignment operation; it is not a statement about how the target of the assignment may be aliased in general.
end note
]
A braced-init-list may appear on the right-hand side of
  • an assignment to a scalar, in which case the initializer list shall have at most a single element.
    The meaning of x = {v}, where T is the scalar type of the expression x, is that of x = T{v}.
    The meaning of x = {} is x = T{}.
  • an assignment to an object of class type, in which case the initializer list is passed as the argument to the assignment operator function selected by overload resolution ([over.ass], [over.match]).
[Example
:
complex<double> z;
z = { 1,2 };              // meaning z.operator=({1,2})
z += { 1, 2 };            // meaning z.operator+=({1,2})
int a, b;
a = b = { 1 };            // meaning a=b=1;
a = { 1 } = b;            // syntax error
end example
]

8.19 Comma operator [expr.comma]

The comma operator groups left-to-right.
expression:
	assignment-expression
	expression , assignment-expression
A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded-value expression (Clause [expr]).
Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression.
The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand, and is a bit-field if its right operand is a bit-field.
If the right operand is a temporary expression ([class.temporary]), the result is a temporary expression.
In contexts where comma is given a special meaning,
[Example
:
in lists of arguments to functions ([expr.call]) and lists of initializers ([dcl.init])
end example
]
the comma operator as described in Clause [expr] can appear only in parentheses.
[Example
:
f(a, (t=3, t+2), c);
has three arguments, the second of which has the value 5.
end example
]

8.20 Constant expressions [expr.const]

Certain contexts require expressions that satisfy additional requirements as detailed in this subclause; other contexts have different semantics depending on whether or not an expression satisfies these requirements.
Expressions that satisfy these requirements, assuming that copy elision is performed, are called constant expressions.
[Note
:
Constant expressions can be evaluated during translation.
end note
]
An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine ([intro.execution]), would evaluate one of the following expressions:
  • this ([expr.prim.this]), except in a constexpr function or a constexpr constructor that is being evaluated as part of e;
  • an invocation of a function other than a constexpr constructor for a literal class, a constexpr function, or an implicit invocation of a trivial destructor ([class.dtor])
    [Note
    :
    Overload resolution ([over.match]) is applied as usual
    end note
    ]
    ;
  • an invocation of an undefined constexpr function or an undefined constexpr constructor;
  • an invocation of an instantiated constexpr function or constexpr constructor that fails to satisfy the requirements for a constexpr function or constexpr constructor ([dcl.constexpr]);
  • an expression that would exceed the implementation-defined limits (see Annex [implimits]);
  • an operation that would have undefined behavior as specified in Clauses [intro] through [cpp] of this International Standard
    [Note
    :
    including, for example, signed integer overflow (Clause [expr]), certain pointer arithmetic ([expr.add]), division by zero ([expr.mul]), or certain shift operations ([expr.shift])
    end note
    ]
    ;
  • an lvalue-to-rvalue conversion ([conv.lval]) unless it is applied to
    • a non-volatile glvalue of integral or enumeration type that refers to a complete non-volatile const object with a preceding initialization, initialized with a constant expression, or
    • a non-volatile glvalue that refers to a subobject of a string literal ([lex.string]), or
    • a non-volatile glvalue that refers to a non-volatile object defined with constexpr, or that refers to a non-mutable subobject of such an object, or
    • a non-volatile glvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of e;
  • an lvalue-to-rvalue conversion ([conv.lval]) that is applied to a glvalue that refers to a non-active member of a union or a subobject thereof;
  • an invocation of an implicitly-defined copy/move constructor or copy/move assignment operator for a union whose active member (if any) is mutable, unless the lifetime of the union object began within the evaluation of e;
  • an assignment expression ([expr.ass]) or invocation of an assignment operator ([class.copy]) that would change the active member of a union;
  • an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either
    • it is initialized with a constant expression or
    • its lifetime began within the evaluation of e;
  • in a lambda-expression, a reference to this or to a variable with automatic storage duration defined outside that lambda-expression, where the reference would be an odr-use ([basic.def.odr], [expr.prim.lambda]);
    [Example
    :
    void g() {
      const int n = 0;
      [=] {
        constexpr int i = n;   // OK, n is not odr-used and not captured here
        constexpr int j = *&n; // ill-formed, &n would be an odr-use of n
      };
    }
    end example
    ]
    [Note
    :
    If the odr-use occurs in an invocation of a function call operator of a closure type, it no longer refers to this or to an enclosing automatic variable due to the transformation ([expr.prim.lambda.capture]) of the id-expression into an access of the corresponding data member.
    [Example
    :
    auto monad = [](auto v) { return [=] { return v; }; };
    auto bind = [](auto m) {
      return [=](auto fvm) { return fvm(m()); };
    };
    
    // OK to have captures to automatic objects created during constant expression evaluation.
    static_assert(bind(monad(2))(monad)() == monad(2)());
    end example
    ]
    end note
    ]
  • a conversion from type cv void* to a pointer-to-object type;
  • a dynamic cast ([expr.dynamic.cast]);
  • a reinterpret_­cast ([expr.reinterpret.cast]);
  • a pseudo-destructor call ([expr.pseudo]);
  • modification of an object ([expr.ass], [expr.post.incr], [expr.pre.incr]) unless it is applied to a non-volatile lvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of e;
  • a typeid expression ([expr.typeid]) whose operand is a glvalue of a polymorphic class type;
  • a relational ([expr.rel]) or equality ([expr.eq]) operator where the result is unspecified; or
If e satisfies the constraints of a core constant expression, but evaluation of e would evaluate an operation that has undefined behavior as specified in Clauses [library] through [thread] of this International Standard, it is unspecified whether e is a core constant expression.
[Example
:
int x;                              // not constant
struct A {
  constexpr A(bool b) : m(b?42:x) { }
  int m;
};
constexpr int v = A(true).m;        // OK: constructor call initializes m with the value 42

constexpr int w = A(false).m;       // error: initializer for m is x, which is non-constant

constexpr int f1(int k) {
  constexpr int x = k;              // error: x is not initialized by a constant expression
                                    // because lifetime of k began outside the initializer of x
  return x;
}
constexpr int f2(int k) {
  int x = k;                        // OK: not required to be a constant expression
                                    // because x is not constexpr
  return x;
}

constexpr int incr(int &n) {
  return ++n;
}
constexpr int g(int k) {
  constexpr int x = incr(k);        // error: incr(k) is not a core constant expression
                                    // because lifetime of k began outside the expression incr(k)
  return x;
}
constexpr int h(int k) {
  int x = incr(k);                  // OK: incr(k) is not required to be a core constant expression
  return x;
}
constexpr int y = h(1);             // OK: initializes y with the value 2
                                    // h(1) is a core constant expression because
                                    // the lifetime of k begins inside h(1)
end example
]
An integral constant expression is an expression of integral or unscoped enumeration type, implicitly converted to a prvalue, where the converted expression is a core constant expression.
[Note
:
Such expressions may be used as bit-field lengths ([class.bit]), as enumerator initializers if the underlying type is not fixed ([dcl.enum]), and as alignments ([dcl.align]).
end note
]
A converted constant expression of type T is an expression, implicitly converted to type T, where the converted expression is a constant expression and the implicit conversion sequence contains only
and where the reference binding (if any) binds directly.
[Note
:
Such expressions may be used in new expressions ([expr.new]), as case expressions ([stmt.switch]), as enumerator initializers if the underlying type is fixed ([dcl.enum]), as array bounds ([dcl.array]), and as non-type template arguments ([temp.arg]).
end note
]
A contextually converted constant expression of type bool is an expression, contextually converted to bool (Clause[conv]), where the converted expression is a constant expression and the conversion sequence contains only the conversions above.
A constant expression is either a glvalue core constant expression that refers to an entity that is a permitted result of a constant expression (as defined below), or a prvalue core constant expression whose value satisfies the following constraints:
  • if the value is an object of class type, each non-static data member of reference type refers to an entity that is a permitted result of a constant expression,
  • if the value is of pointer type, it contains the address of an object with static storage duration, the address past the end of such an object ([expr.add]), the address of a function, or a null pointer value, and
  • if the value is an object of class or array type, each subobject satisfies these constraints for the value.
An entity is a permitted result of a constant expression if it is an object with static storage duration that is either not a temporary object or is a temporary object whose value satisfies the above constraints, or it is a function.
[Note
:
Since this International Standard imposes no restrictions on the accuracy of floating-point operations, it is unspecified whether the evaluation of a floating-point expression during translation yields the same result as the evaluation of the same expression (or the same operations on the same values) during program execution.89
[Example
:
bool f() {
    char array[1 + int(1 + 0.2 - 0.1 - 0.1)];  // Must be evaluated during translation
    int size = 1 + int(1 + 0.2 - 0.1 - 0.1);   // May be evaluated at runtime
    return sizeof(array) == size;
}
It is unspecified whether the value of f() will be true or false.
end example
]
end note
]
If an expression of literal class type is used in a context where an integral constant expression is required, then that expression is contextually implicitly converted (Clause [conv]) to an integral or unscoped enumeration type and the selected conversion function shall be constexpr.
[Example
:
struct A {
  constexpr A(int i) : val(i) { }
  constexpr operator int() const { return val; }
  constexpr operator long() const { return 43; }
private:
  int val;
};
template<int> struct X { };
constexpr A a = 42;
X<a> x;             // OK: unique conversion to int
int ary[a];         // error: ambiguous conversion
end example
]
Nonetheless, implementations are encouraged to provide consistent results, irrespective of whether the evaluation was performed during translation and/or during program execution.

9 Statements [stmt.stmt]

The rules for conditions apply both to selection-statements and to the for and while statements ([stmt.iter]).
The declarator shall not specify a function or an array.
The decl-specifier-seq shall not define a class or enumeration.
If the auto type-specifier appears in the decl-specifier-seq, the type of the identifier being declared is deduced from the initializer as described in [dcl.spec.auto].
A name introduced by a declaration in a condition (either introduced by the decl-specifier-seq or the declarator of the condition) is in scope from its point of declaration until the end of the substatements controlled by the condition.
If the name is redeclared in the outermost block of a substatement controlled by the condition, the declaration that redeclares the name is ill-formed.
[Example
:
if (int x = f()) {
  int x;            // ill-formed, redeclaration of x
}
else {
  int x;            // ill-formed, redeclaration of x
}
end example
]
The value of a condition that is an initialized declaration in a statement other than a switch statement is the value of the declared variable contextually converted to bool (Clause [conv]).
If that conversion is ill-formed, the program is ill-formed.
The value of a condition that is an initialized declaration in a switch statement is the value of the declared variable if it has integral or enumeration type, or of that variable implicitly converted to integral or enumeration type otherwise.
The value of a condition that is an expression is the value of the expression, contextually converted to bool for statements other than switch; if that conversion is ill-formed, the program is ill-formed.
The value of the condition will be referred to as simply “the condition” where the usage is unambiguous.
If a condition can be syntactically resolved as either an expression or the declaration of a block-scope name, it is interpreted as a declaration.
In the decl-specifier-seq of a condition, each decl-specifier shall be either a type-specifier or constexpr.

9.1 Labeled statement [stmt.label]

A statement can be labeled.
An identifier label declares the identifier.
The only use of an identifier label is as the target of a goto.
The scope of a label is the function in which it appears.
Labels shall not be redeclared within a function.
A label can be used in a goto statement before its declaration.
Labels have their own name space and do not interfere with other identifiers.
[Note
:
A label may have the same name as another declaration in the same scope or a template-parameter from an enclosing scope.
Unqualified name lookup ([basic.lookup.unqual]) ignores labels.
end note
]
Case labels and default labels shall occur only in switch statements.

9.2 Expression statement [stmt.expr]

Expression statements have the form
expression-statement:
	expression ;
The expression is a discarded-value expression (Clause [expr]).
All side effects from an expression statement are completed before the next statement is executed.
An expression statement with the expression missing is called a null statement.
[Note
:
Most statements are expression statements — usually assignments or function calls.
A null statement is useful to carry a label just before the } of a compound statement and to supply a null body to an iteration statement such as a while statement ([stmt.while]).
end note
]

9.3 Compound statement or block [stmt.block]

So that several statements can be used where one is expected, the compound statement (also, and equivalently, called “block”) is provided.
[Note
:
A declaration is a statement ([stmt.dcl]).
end note
]

9.4 Selection statements [stmt.select]

Selection statements choose one of several flows of control.
[Note
:
An init-statement ends with a semicolon.
end note
]
In Clause [stmt.stmt], the term substatement refers to the contained statement or statements that appear in the syntax notation.
The substatement in a selection-statement (each substatement, in the else form of the if statement) implicitly defines a block scope ([basic.scope]).
If the substatement in a selection-statement is a single statement and not a compound-statement, it is as if it was rewritten to be a compound-statement containing the original substatement.
[Example
:
if (x)
  int i;
can be equivalently rewritten as
if (x) {
  int i;
}
Thus after the if statement, i is no longer in scope.
end example
]

9.4.1 The if statement [stmt.if]

If the condition ([stmt.select]) yields true the first substatement is executed.
If the else part of the selection statement is present and the condition yields false, the second substatement is executed.
If the first substatement is reached via a label, the condition is not evaluated and the second substatement is not executed.
In the second form of if statement (the one including else), if the first substatement is also an if statement then that inner if statement shall contain an else part.90
If the if statement is of the form if constexpr, the value of the condition shall be a contextually converted constant expression of type bool ([expr.const]); this form is called a constexpr if statement.
If the value of the converted condition is false, the first substatement is a discarded statement, otherwise the second substatement, if present, is a discarded statement.
During the instantation of an enclosing templated entity (Clause [temp]), if the condition is not value-dependent after its instantiation, the discarded substatement (if any) is not instantiated.
[Note
:
Odr-uses ([basic.def.odr]) in a discarded statement do not require an entity to be defined.
end note
]
A case or default label appearing within such an if statement shall be associated with a switch statement ([stmt.switch]) within the same if statement.
A label ([stmt.label]) declared in a substatement of a constexpr if statement shall only be referred to by a statement ([stmt.goto]) in the same substatement.
[Example
:
template<typename T, typename ... Rest> void g(T&& p, Rest&& ...rs) {
  // ... handle p

  if constexpr (sizeof...(rs) > 0)
    g(rs...);       // never instantiated with an empty argument list
}

extern int x;       // no definition of x required

int f() {
  if constexpr (true)
    return 0;
  else if (x)
    return x;
  else
    return -x;
}
end example
]
An if statement of the form
if constexpr ( init-statement condition ) statement
is equivalent to
{
	init-statement
	if constexpr ( condition ) statement
}
and an if statement of the form
if constexpr ( init-statement condition ) statement else statement
is equivalent to
{
	init-statement
	if constexpr ( condition ) statement else statement
}
except that names declared in the init-statement are in the same declarative region as those declared in the condition.
In other words, the else is associated with the nearest un-elsed if.

9.4.2 The switch statement [stmt.switch]

The switch statement causes control to be transferred to one of several statements depending on the value of a condition.
The condition shall be of integral type, enumeration type, or class type.
If of class type, the condition is contextually implicitly converted (Clause [conv]) to an integral or enumeration type.
If the (possibly converted) type is subject to integral promotions ([conv.prom]), the condition is converted to the promoted type.
Any statement within the switch statement can be labeled with one or more case labels as follows:
case constant-expression :
where the constant-expression shall be a converted constant expression ([expr.const]) of the adjusted type of the switch condition.
No two of the case constants in the same switch shall have the same value after conversion.
There shall be at most one label of the form
default :
within a switch statement.
Switch statements can be nested; a case or default label is associated with the smallest switch enclosing it.
When the switch statement is executed, its condition is evaluated and compared with each case constant.
If one of the case constants is equal to the value of the condition, control is passed to the statement following the matched case label.
If no case constant matches the condition, and if there is a default label, control passes to the statement labeled by the default label.
If no case matches and if there is no default then none of the statements in the switch is executed.
case and default labels in themselves do not alter the flow of control, which continues unimpeded across such labels.
To exit from a switch, see break, [stmt.break].
[Note
:
Usually, the substatement that is the subject of a switch is compound and case and default labels appear on the top-level statements contained within the (compound) substatement, but this is not required.
Declarations can appear in the substatement of a switch statement.
end note
]
A switch statement of the form
switch ( init-statement condition ) statement
is equivalent to
{
	init-statement
	switch ( condition ) statement
}
except that names declared in the init-statement are in the same declarative region as those declared in the condition.

9.5 Iteration statements [stmt.iter]

The substatement in an iteration-statement implicitly defines a block scope ([basic.scope]) which is entered and exited each time through the loop.
If the substatement in an iteration-statement is a single statement and not a compound-statement, it is as if it was rewritten to be a compound-statement containing the original statement.
[Example
:
while (--x >= 0)
  int i;
can be equivalently rewritten as
while (--x >= 0) {
  int i;
}
Thus after the while statement, i is no longer in scope.
end example
]
If a name introduced in an init-statement or for-range-declaration is redeclared in the outermost block of the substatement, the program is ill-formed.
[Example
:
void f() {
  for (int i = 0; i < 10; ++i)
    int i = 0;          // error: redeclaration
  for (int i : { 1, 2, 3 })
    int i = 1;          // error: redeclaration
}
end example
]

9.5.1 The while statement [stmt.while]

In the while statement the substatement is executed repeatedly until the value of the condition ([stmt.select]) becomes false.
The test takes place before each execution of the substatement.
When the condition of a while statement is a declaration, the scope of the variable that is declared extends from its point of declaration ([basic.scope.pdecl]) to the end of the while statement.
A while statement of the form
while (T t = x) statement
is equivalent to
label:
{                   // start of condition scope
  T t = x;
  if (t) {
    statement
    goto label;
  }
}                   // end of condition scope
The variable created in a condition is destroyed and created with each iteration of the loop.
[Example
:
struct A {
  int val;
  A(int i) : val(i) { }
  ~A() { }
  operator bool() { return val != 0; }
};
int i = 1;
while (A a = i) {
  // ...
  i = 0;
}
In the while-loop, the constructor and destructor are each called twice, once for the condition that succeeds and once for the condition that fails.
end example
]

9.5.2 The do statement [stmt.do]

The expression is contextually converted to bool (Clause [conv]); if that conversion is ill-formed, the program is ill-formed.
In the do statement the substatement is executed repeatedly until the value of the expression becomes false.
The test takes place after each execution of the statement.

9.5.3 The for statement [stmt.for]

The for statement
for ( init-statement condition ; expression ) statement
is equivalent to
{
	init-statement
	while ( condition ) {
		statement
		expression ;
	}
}
except that names declared in the init-statement are in the same declarative region as those declared in the condition, and except that a continue in statement (not enclosed in another iteration statement) will execute expression before re-evaluating condition.
[Note
:
Thus the first statement specifies initialization for the loop; the condition ([stmt.select]) specifies a test, sequenced before each iteration, such that the loop is exited when the condition becomes false; the expression often specifies incrementing that is sequenced after each iteration.
end note
]
Either or both of the condition and the expression can be omitted.
A missing condition makes the implied while clause equivalent to while(true).
If the init-statement is a declaration, the scope of the name(s) declared extends to the end of the for statement.
[Example
:
int i = 42;
int a[10];

for (int i = 0; i < 10; i++)
  a[i] = i;

int j = i;          // j = 42
end example
]

9.5.4 The range-based for statement [stmt.ranged]

The range-based for statement
for ( for-range-declaration : for-range-initializer ) statement
is equivalent to
{
	auto &&__range = for-range-initializer ;
	auto __begin = begin-expr ;
	auto __end = end-expr ;
	for ( ; __begin != __end; ++__begin ) {
		for-range-declaration = *__begin;
		statement
	}
}
where
  • if the for-range-initializer is an expression, it is regarded as if it were surrounded by parentheses (so that a comma operator cannot be reinterpreted as delimiting two init-declarators);
  • _­_­range, _­_­begin, and _­_­end are variables defined for exposition only; and
  • begin-expr and end-expr are determined as follows:
    • if the for-range-initializer is an expression of array type R, begin-expr and end-expr are _­_­range and _­_­range + _­_­bound, respectively, where _­_­bound is the array bound.
      If R is an array of unknown bound or an array of incomplete type, the program is ill-formed;
    • if the for-range-initializer is an expression of class type C, the unqualified-ids begin and end are looked up in the scope of C as if by class member access lookup ([basic.lookup.classref]), and if either (or both) finds at least one declaration, begin-expr and end-expr are _­_­range.begin() and _­_­range.end(), respectively;
    • otherwise, begin-expr and end-expr are begin(_­_­range) and end(_­_­range), respectively, where begin and end are looked up in the associated namespaces ([basic.lookup.argdep]).
      [Note
      :
      Ordinary unqualified lookup ([basic.lookup.unqual]) is not performed.
      end note
      ]
[Example
:
int array[5] = { 1, 2, 3, 4, 5 };
for (int& x : array)
  x *= 2;
end example
]
In the decl-specifier-seq of a for-range-declaration, each decl-specifier shall be either a type-specifier or constexpr.
The decl-specifier-seq shall not define a class or enumeration.

9.6 Jump statements [stmt.jump]

Jump statements unconditionally transfer control.
jump-statement:
	break ;
	continue ;
	return expr-or-braced-init-list ;
	goto identifier ;
On exit from a scope (however accomplished), objects with automatic storage duration ([basic.stc.auto]) that have been constructed in that scope are destroyed in the reverse order of their construction.
[Note
:
For temporaries, see [class.temporary].
end note
]
Transfer out of a loop, out of a block, or back past an initialized variable with automatic storage duration involves the destruction of objects with automatic storage duration that are in scope at the point transferred from but not at the point transferred to.
(See [stmt.dcl] for transfers into blocks).
[Note
:
However, the program can be terminated (by calling std​::​exit() or std​::​abort() ([support.start.term]), for example) without destroying class objects with automatic storage duration.
end note
]

9.6.1 The break statement [stmt.break]

The break statement shall occur only in an iteration-statement or a switch statement and causes termination of the smallest enclosing iteration-statement or switch statement; control passes to the statement following the terminated statement, if any.

9.6.2 The continue statement [stmt.cont]

The continue statement shall occur only in an iteration-statement and causes control to pass to the loop-continuation portion of the smallest enclosing iteration-statement, that is, to the end of the loop.
More precisely, in each of the statements
while (foo) {
  {
    // ...
  }
contin: ;
}
do {
  {
    // ...
  }
contin: ;
} while (foo);
for (;;) {
  {
    // ...
  }
contin: ;
}
a continue not contained in an enclosed iteration statement is equivalent to goto contin.

9.6.3 The return statement [stmt.return]

A function returns to its caller by the return statement.
The expr-or-braced-init-list of a return statement is called its operand.
A return statement with no operand shall be used only in a function whose return type is cv void, a constructor ([class.ctor]), or a destructor ([class.dtor]).
A return statement with an operand of type void shall be used only in a function whose return type is cv void.
A return statement with any other operand shall be used only in a function whose return type is not cv void; the return statement initializes the glvalue result or prvalue result object of the (explicit or implicit) function call by copy-initialization ([dcl.init]) from the operand.
[Note
:
A return statement can involve an invocation of a constructor to perform a copy or move of the operand if it is not a prvalue or if its type differs from the return type of the function.
A copy operation associated with a return statement may be elided or converted to a move operation if an automatic storage duration variable is returned ([class.copy]).
end note
]
[Example
:
std::pair<std::string,int> f(const char* p, int x) {
  return {p,x};
}
end example
]
Flowing off the end of a constructor, a destructor, or a function with a cv void return type is equivalent to a return with no operand.
Otherwise, flowing off the end of a function other than main ([basic.start.main]) results in undefined behavior.
The copy-initialization of the result of the call is sequenced before the destruction of temporaries at the end of the full-expression established by the operand of the return statement, which, in turn, is sequenced before the destruction of local variables ([stmt.jump]) of the block enclosing the return statement.

9.6.4 The goto statement [stmt.goto]

The goto statement unconditionally transfers control to the statement labeled by the identifier.
The identifier shall be a label ([stmt.label]) located in the current function.

9.7 Declaration statement [stmt.dcl]

A declaration statement introduces one or more new identifiers into a block; it has the form
declaration-statement:
	block-declaration
If an identifier introduced by a declaration was previously declared in an outer block, the outer declaration is hidden for the remainder of the block, after which it resumes its force.
Variables with automatic storage duration ([basic.stc.auto]) are initialized each time their declaration-statement is executed.
Variables with automatic storage duration declared in the block are destroyed on exit from the block ([stmt.jump]).
It is possible to transfer into a block, but not in a way that bypasses declarations with initialization.
A program that jumps91 from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer.
[Example
:
void f() {
  // ...
  goto lx;          // ill-formed: jump into scope of a
  // ...
ly:
  X a = 1;
  // ...
lx:
  goto ly;          // OK, jump implies destructor call for a followed by
                    // construction again immediately following label ly
}
end example
]
Dynamic initialization of a block-scope variable with static storage duration ([basic.stc.static]) or thread storage duration ([basic.stc.thread]) is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization.
If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration.
If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.92
If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.
[Example
:
int foo(int i) {
  static int s = foo(2*i);      // recursive call - undefined
  return i+1;
}
end example
]
The destructor for a block-scope object with static or thread storage duration will be executed if and only if it was constructed.
[Note
:
[basic.start.term] describes the order in which block-scope objects with static and thread storage duration are destroyed.
end note
]
The transfer from the condition of a switch statement to a case label is considered a jump in this respect.
The implementation must not introduce any deadlock around execution of the initializer.
Deadlocks might still be caused by the program logic; the implementation need only avoid deadlocks due to its own synchronization operations.

9.8 Ambiguity resolution [stmt.ambig]

There is an ambiguity in the grammar involving expression-statements and declarations: An expression-statement with a function-style explicit type conversion ([expr.type.conv]) as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a (.
In those cases the statement is a declaration.
[Note
:
If the statement cannot syntactically be a declaration, there is no ambiguity, so this rule does not apply.
The whole statement might need to be examined to determine whether this is the case.
This resolves the meaning of many examples.
[Example
:
Assuming T is a simple-type-specifier ([dcl.type]),
T(a)->m = 7;        // expression-statement
T(a)++;             // expression-statement
T(a,5)<<c;          // expression-statement

T(*d)(int);         //  declaration
T(e)[5];            //  declaration
T(f) = { 1, 2 };    //  declaration
T(*g)(double(3));   //  declaration
In the last example above, g, which is a pointer to T, is initialized to double(3).
This is of course ill-formed for semantic reasons, but that does not affect the syntactic analysis.
end example
]
The remaining cases are declarations.
[Example
:
class T {
  // ...
public:
  T();
  T(int);
  T(int, int);
};
T(a);               //  declaration
T(*b)();            //  declaration
T(c)=7;             //  declaration
T(d),e,f=3;         //  declaration
extern int h;
T(g)(h,2);          //  declaration
end example
]
end note
]
The disambiguation is purely syntactic; that is, the meaning of the names occurring in such a statement, beyond whether they are type-names or not, is not generally used in or changed by the disambiguation.
Class templates are instantiated as necessary to determine if a qualified name is a type-name.
Disambiguation precedes parsing, and a statement disambiguated as a declaration may be an ill-formed declaration.
If, during parsing, a name in a template parameter is bound differently than it would be bound during a trial parse, the program is ill-formed.
No diagnostic is required.
[Note
:
This can occur only when the name is declared earlier in the declaration.
end note
]
[Example
:
struct T1 {
  T1 operator()(int x) { return T1(x); }
  int operator=(int x) { return x; }
  T1(int) { }
};
struct T2 { T2(int){ } };
int a, (*(*b)(T2))(int), c, d;

void f() {
  // disambiguation requires this to be parsed as a declaration:
  T1(a) = 3,
  T2(4),                        // T2 will be declared as a variable of type T1, but this will not
  (*(*b)(T2(c)))(int(d));       // allow the last part of the declaration to parse properly,
                                // since it depends on T2 being a type-name
}
end example
]

10 Declarations [dcl.dcl]

Declarations generally specify how names are to be interpreted.
Declarations have the form
Attributes are described in [dcl.attr].
decl-specifiers, the principal components of a decl-specifier-seq, are described in [dcl.spec].
declarators, the components of an init-declarator-list, are described in Clause [dcl.decl].
The attribute-specifier-seq appertains to each of the entities declared by the declarators of the init-declarator-list.
[Note
:
In the declaration for an entity, attributes appertaining to that entity may appear at the start of the declaration and after the declarator-id for that declaration.
end note
]
[Example
:
[[noreturn]] void f [[noreturn]] ();    // OK
end example
]
Except where otherwise specified, the meaning of an attribute-declaration is implementation-defined.
A declaration occurs in a scope ([basic.scope]); the scope rules are summarized in [basic.lookup].
A declaration that declares a function or defines a class, namespace, template, or function also has one or more scopes nested within it.
These nested scopes, in turn, can have declarations nested within them.
Unless otherwise stated, utterances in Clause [dcl.dcl] about components in, of, or contained by a declaration or subcomponent thereof refer only to those components of the declaration that are not nested within scopes nested within the declaration.
In a simple-declaration, the optional init-declarator-list can be omitted only when declaring a class (Clause [class]) or enumeration ([dcl.enum]), that is, when the decl-specifier-seq contains either a class-specifier, an elaborated-type-specifier with a class-key ([class.name]), or an enum-specifier.
In these cases and whenever a class-specifier or enum-specifier is present in the decl-specifier-seq, the identifiers in these specifiers are among the names being declared by the declaration (as class-names, enum-names, or enumerators, depending on the syntax).
In such cases, the decl-specifier-seq shall introduce one or more names into the program, or shall redeclare a name introduced by a previous declaration.
[Example
:
enum { };           // ill-formed
typedef class { };  // ill-formed
end example
]
In a static_assert-declaration, the constant-expression shall be a contextually converted constant expression of type bool ([expr.const]).
If the value of the expression when so converted is true, the declaration has no effect.
Otherwise, the program is ill-formed, and the resulting diagnostic message ([intro.compliance]) shall include the text of the string-literal, if one is supplied, except that characters not in the basic source character set ([lex.charset]) are not required to appear in the diagnostic message.
[Example
:
static_assert(char(-1) < 0, "this library requires plain 'char' to be signed");
end example
]
An empty-declaration has no effect.
The decl-specifier-seq shall contain only the type-specifier auto ([dcl.spec.auto]) and cv-qualifiers.
The initializer shall be of the form “= assignment-expression”, of the form “{ assignment-expression }”, or of the form “( assignment-expression )”, where the assignment-expression is of array or non-union class type.
Each init-declarator in the init-declarator-list contains exactly one declarator-id, which is the name declared by that init-declarator and hence one of the names declared by the declaration.
The defining-type-specifiers in the decl-specifier-seq and the recursive declarator structure of the init-declarator describe a type ([dcl.meaning]), which is then associated with the name being declared by the init-declarator.
If the decl-specifier-seq contains the typedef specifier, the declaration is called a typedef declaration and the name of each init-declarator is declared to be a typedef-name, synonymous with its associated type ([dcl.typedef]).
If the decl-specifier-seq contains no typedef specifier, the declaration is called a function declaration if the type associated with the name is a function type ([dcl.fct]) and an object declaration otherwise.
Syntactic components beyond those found in the general form of declaration are added to a function declaration to make a function-definition.
An object declaration, however, is also a definition unless it contains the extern specifier and has no initializer ([basic.def]).
A definition causes the appropriate amount of storage to be reserved and any appropriate initialization ([dcl.init]) to be done.
A nodeclspec-function-declaration shall declare a constructor, destructor, or conversion function.93
[Note
:
A nodeclspec-function-declaration can only be used in a template-declaration (Clause [temp]), explicit-instantiation ([temp.explicit]), or explicit-specialization ([temp.expl.spec]).
end note
]
The “implicit int” rule of C is no longer supported.

10.1 Specifiers [dcl.spec]

The specifiers that can be used in a declaration are
The attribute-specifier-seq affects the type only for the declaration it appears in, not other declarations involving the same type.
Each decl-specifier shall appear at most once in a complete decl-specifier-seq, except that long may appear twice.
If a type-name is encountered while parsing a decl-specifier-seq, it is interpreted as part of the decl-specifier-seq if and only if there is no previous defining-type-specifier other than a cv-qualifier in the decl-specifier-seq.
The sequence shall be self-consistent as described below.
[Example
:
typedef char* Pc;
static Pc;                      // error: name missing
Here, the declaration static Pc is ill-formed because no name was specified for the static variable of type Pc.
To get a variable called Pc, a type-specifier (other than const or volatile) has to be present to indicate that the typedef-name Pc is the name being (re)declared, rather than being part of the decl-specifier sequence.
For another example,
void f(const Pc);               // void f(char* const) (not const char*)
void g(const int Pc);           // void g(const int)
end example
]
[Note
:
Since signed, unsigned, long, and short by default imply int, a type-name appearing after one of those specifiers is treated as the name being (re)declared.
[Example
:
void h(unsigned Pc);            // void h(unsigned int)
void k(unsigned int Pc);        // void k(unsigned int)
end example
]
end note
]

10.1.1 Storage class specifiers [dcl.stc]

The storage class specifiers are
storage-class-specifier:
	static
	thread_local
	extern
	mutable
At most one storage-class-specifier shall appear in a given decl-specifier-seq, except that thread_­local may appear with static or extern.
If thread_­local appears in any declaration of a variable it shall be present in all declarations of that entity.
If a storage-class-specifier appears in a decl-specifier-seq, there can be no typedef specifier in the same decl-specifier-seq and the init-declarator-list or member-declarator-list of the declaration shall not be empty (except for an anonymous union declared in a named namespace or in the global namespace, which shall be declared static ([class.union.anon])).
The storage-class-specifier applies to the name declared by each init-declarator in the list and not to any names declared by other specifiers.
A storage-class-specifier other than thread_­local shall not be specified in an explicit specialization ([temp.expl.spec]) or an explicit instantiation ([temp.explicit]) directive.
[Note
:
A variable declared without a storage-class-specifier at block scope or declared as a function parameter has automatic storage duration by default ([basic.stc.auto]).
end note
]
The thread_­local specifier indicates that the named entity has thread storage duration ([basic.stc.thread]).
It shall be applied only to the names of variables of namespace or block scope and to the names of static data members.
When thread_­local is applied to a variable of block scope the storage-class-specifier static is implied if no other storage-class-specifier appears in the decl-specifier-seq.
The static specifier can be applied only to names of variables and functions and to anonymous unions ([class.union.anon]).
There can be no static function declarations within a block, nor any static function parameters.
A static specifier used in the declaration of a variable declares the variable to have static storage duration ([basic.stc.static]), unless accompanied by the thread_­local specifier, which declares the variable to have thread storage duration ([basic.stc.thread]).
A static specifier can be used in declarations of class members; [class.static] describes its effect.
For the linkage of a name declared with a static specifier, see [basic.link].
The extern specifier can be applied only to the names of variables and functions.
The extern specifier cannot be used in the declaration of class members or function parameters.
For the linkage of a name declared with an extern specifier, see [basic.link].
[Note
:
The extern keyword can also be used in explicit-instantiations and linkage-specifications, but it is not a storage-class-specifier in such contexts.
end note
]
The linkages implied by successive declarations for a given entity shall agree.
That is, within a given scope, each declaration declaring the same variable name or the same overloading of a function name shall imply the same linkage.
Each function in a given set of overloaded functions can have a different linkage, however.
[Example
:
static char* f();               // f() has internal linkage
char* f()                       // f() still has internal linkage
  { /* ... */ }

char* g();                      // g() has external linkage
static char* g()                // error: inconsistent linkage
  { /* ... */ }

void h();
inline void h();                // external linkage

inline void l();
void l();                       // external linkage

inline void m();
extern void m();                // external linkage

static void n();
inline void n();                // internal linkage

static int a;                   // a has internal linkage
int a;                          // error: two definitions

static int b;                   // b has internal linkage
extern int b;                   // b still has internal linkage

int c;                          // c has external linkage
static int c;                   // error: inconsistent linkage

extern int d;                   // d has external linkage
static int d;                   // error: inconsistent linkage
end example
]
The name of a declared but undefined class can be used in an extern declaration.
Such a declaration can only be used in ways that do not require a complete class type.
[Example
:
struct S;
extern S a;
extern S f();
extern void g(S);

void h() {
  g(a);                         // error: S is incomplete
  f();                          // error: S is incomplete
}
end example
]
The mutable specifier shall appear only in the declaration of a non-static data member ([class.mem]) whose type is neither const-qualified nor a reference type.
[Example
:
class X {
  mutable const int* p;         // OK
  mutable int* const q;         // ill-formed
};
end example
]
The mutable specifier on a class data member nullifies a const specifier applied to the containing class object and permits modification of the mutable class member even though the rest of the object is const ([dcl.type.cv]).

10.1.2 Function specifiers [dcl.fct.spec]

Function-specifiers can be used only in function declarations.
function-specifier:
	virtual
	explicit
The virtual specifier shall be used only in the initial declaration of a non-static class member function; see [class.virtual].
The explicit specifier shall be used only in the declaration of a constructor or conversion function within its class definition; see [class.conv.ctor] and [class.conv.fct].

10.1.3 The typedef specifier [dcl.typedef]

Declarations containing the decl-specifier typedef declare identifiers that can be used later for naming fundamental ([basic.fundamental]) or compound ([basic.compound]) types.
The typedef specifier shall not be combined in a decl-specifier-seq with any other kind of specifier except a defining-type-specifier, and it shall not be used in the decl-specifier-seq of a parameter-declaration nor in the decl-specifier-seq of a function-definition ([dcl.fct.def]).
If a typedef specifier appears in a declaration without a declarator, the program is ill-formed.
typedef-name:
	identifier
A name declared with the typedef specifier becomes a typedef-name.
Within the scope of its declaration, a typedef-name is syntactically equivalent to a keyword and names the type associated with the identifier in the way described in Clause [dcl.decl].
A typedef-name is thus a synonym for another type.
A typedef-name does not introduce a new type the way a class declaration ([class.name]) or enum declaration does.
[Example
:
After
typedef int MILES, *KLICKSP;
the constructions
MILES distance;
extern KLICKSP metricp;
are all correct declarations; the type of distance is int and that of metricp is “pointer to int.
end example
]
A typedef-name can also be introduced by an alias-declaration.
The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name.
Such a typedef-name has the same semantics as if it were introduced by the typedef specifier.
In particular, it does not define a new type.
[Example
:
using handler_t = void (*)(int);
extern handler_t ignore;
extern void (*ignore)(int);         // redeclare ignore
using cell = pair<void*, cell*>;    // ill-formed
end example
]
The defining-type-specifier-seq of the defining-type-id shall not define a class or enumeration if the alias-declaration is the declaration of a template-declaration.
In a given non-class scope, a typedef specifier can be used to redefine the name of any type declared in that scope to refer to the type to which it already refers.
[Example
:
typedef struct s { /* ... */ } s;
typedef int I;
typedef int I;
typedef I I;
end example
]
In a given class scope, a typedef specifier can be used to redefine any class-name declared in that scope that is not also a typedef-name to refer to the type to which it already refers.
[Example
:
struct S {
  typedef struct A { } A;       // OK
  typedef struct B B;           // OK
  typedef A A;                  // error
};
end example
]
If a typedef specifier is used to redefine in a given scope an entity that can be referenced using an elaborated-type-specifier, the entity can continue to be referenced by an elaborated-type-specifier or as an enumeration or class name in an enumeration or class definition respectively.
[Example
:
struct S;
typedef struct S S;
int main() {
  struct S* p;                  // OK
}
struct S { };                   // OK
end example
]
In a given scope, a typedef specifier shall not be used to redefine the name of any type declared in that scope to refer to a different type.
[Example
:
class complex { /* ... */ };
typedef int complex;            // error: redefinition
end example
]
Similarly, in a given scope, a class or enumeration shall not be declared with the same name as a typedef-name that is declared in that scope and refers to a type other than the class or enumeration itself.
[Example
:
typedef int complex;
class complex { /* ... */ };    // error: redefinition
end example
]
[Note
:
A typedef-name that names a class type, or a cv-qualified version thereof, is also a class-name ([class.name]).
If a typedef-name is used to identify the subject of an elaborated-type-specifier ([dcl.type.elab]), a class definition (Clause [class]), a constructor declaration ([class.ctor]), or a destructor declaration ([class.dtor]), the program is ill-formed.
end note
]
[Example
:
struct S {
  S();
  ~S();
};

typedef struct S T;

S a = T();                      // OK
struct T * p;                   // error
end example
]
If the typedef declaration defines an unnamed class (or enum), the first typedef-name declared by the declaration to be that class type (or enum type) is used to denote the class type (or enum type) for linkage purposes only ([basic.link]).
[Example
:
typedef struct { } *ps, S;      // S is the class name for linkage purposes
end example
]

10.1.4 The friend specifier [dcl.friend]

The friend specifier is used to specify access to class members; see [class.friend].

10.1.5 The constexpr specifier [dcl.constexpr]

The constexpr specifier shall be applied only to the definition of a variable or variable template or the declaration of a function or function template.
A function or static data member declared with the constexpr specifier is implicitly an inline function or variable ([dcl.inline]).
If any declaration of a function or function template has a constexpr specifier, then all its declarations shall contain the constexpr specifier.
[Note
:
An explicit specialization can differ from the template declaration with respect to the constexpr specifier.
end note
]
[Note
:
Function parameters cannot be declared constexpr.
end note
]
[Example
:
constexpr void square(int &x);  // OK: declaration
constexpr int bufsz = 1024;     // OK: definition
constexpr struct pixel {        // error: pixel is a type
  int x;
  int y;
  constexpr pixel(int);         // OK: declaration
};
constexpr pixel::pixel(int a)
  : x(a), y(x)                  // OK: definition
  { square(x); }
constexpr pixel small(2);       // error: square not defined, so small(2)
                                // not constant ([expr.const]) so constexpr not satisfied

constexpr void square(int &x) { // OK: definition
  x *= x;
}
constexpr pixel large(4);       // OK: square defined
int next(constexpr int x) {     // error: not for parameters
     return x + 1;
}
extern constexpr int memsz;     // error: not a definition
end example
]
A constexpr specifier used in the declaration of a function that is not a constructor declares that function to be a constexpr function.
Similarly, a constexpr specifier used in a constructor declaration declares that constructor to be a constexpr constructor.
The definition of a constexpr function shall satisfy the following requirements:
[Example
:
constexpr int square(int x)
  { return x * x; }             // OK
constexpr long long_max()
  { return 2147483647; }        // OK
constexpr int abs(int x) {
  if (x < 0)
    x = -x;
  return x;                     // OK
}
constexpr int first(int n) {
  static int value = n;         // error: variable has static storage duration
  return value;
}
constexpr int uninit() {
  int a;                        // error: variable is uninitialized
  return a;
}
constexpr int prev(int x)
  { return --x; }               // OK
constexpr int g(int x, int n) { // OK
  int r = 1;
  while (--n > 0) r *= x;
  return r;
}
end example
]
The definition of a constexpr constructor shall satisfy the following requirements:
In addition, either its function-body shall be = delete, or it shall satisfy the following requirements:
  • either its function-body shall be = default, or the compound-statement of its function-body shall satisfy the requirements for a function-body of a constexpr function;
  • every non-variant non-static data member and base class subobject shall be initialized ([class.base.init]);
  • if the class is a union having variant members ([class.union]), exactly one of them shall be initialized;
  • if the class is a union-like class, but is not a union, for each of its anonymous union members having variant members, exactly one of them shall be initialized;
  • for a non-delegating constructor, every constructor selected to initialize non-static data members and base class subobjects shall be a constexpr constructor;
  • for a delegating constructor, the target constructor shall be a constexpr constructor.
[Example
:
struct Length {
  constexpr explicit Length(int i = 0) : val(i) { }
private:
  int val;
};
end example
]
For a constexpr function or constexpr constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression ([expr.const]), or, for a constructor, a constant initializer for some object ([basic.start.static]), the program is ill-formed, no diagnostic required.
[Example
:
constexpr int f(bool b)
  { return b ? throw 0 : 0; }           // OK
constexpr int f() { return f(true); }   // ill-formed, no diagnostic required

struct B {
  constexpr B(int x) : i(0) { }         // x is unused
  int i;
};

int global;

struct D : B {
  constexpr D() : B(global) { }         // ill-formed, no diagnostic required
                                        // lvalue-to-rvalue conversion on non-constant global
};
end example
]
If the instantiated template specialization of a constexpr function template or member function of a class template would fail to satisfy the requirements for a constexpr function or constexpr constructor, that specialization is still a constexpr function or constexpr constructor, even though a call to such a function cannot appear in a constant expression.
If no specialization of the template would satisfy the requirements for a constexpr function or constexpr constructor when considered as a non-template function or constructor, the template is ill-formed, no diagnostic required.
A call to a constexpr function produces the same result as a call to an equivalent non-constexpr function in all respects except that
The constexpr specifier has no effect on the type of a constexpr function or a constexpr constructor.
[Example
:
constexpr int bar(int x, int y)         // OK
    { return x + y + x*y; }
// ...
int bar(int x, int y)                   // error: redefinition of bar
    { return x * 2 + 3 * y; }
end example
]
A constexpr specifier used in an object declaration declares the object as const.
Such an object shall have literal type and shall be initialized.
In any constexpr variable declaration, the full-expression of the initialization shall be a constant expression ([expr.const]).
[Example
:
struct pixel {
  int x, y;
};
constexpr pixel ur = { 1294, 1024 };    // OK
constexpr pixel origin;                 // error: initializer missing
end example
]

10.1.6 The inline specifier [dcl.inline]

The inline specifier can be applied only to the declaration or definition of a variable or function.
A function declaration ([dcl.fct], [class.mfct], [class.friend]) with an inline specifier declares an inline function.
The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism.
An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions specified in this section shall still be respected.
A variable declaration with an inline specifier declares an inline variable.
A function defined within a class definition is an inline function.
The inline specifier shall not appear on a block scope declaration.94
If the inline specifier is used in a friend function declaration, that declaration shall be a definition or the function shall have previously been declared inline.
An inline function or variable shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case ([basic.def.odr]).
[Note
:
A call to the inline function or a use of the inline variable may be encountered before its definition appears in the translation unit.
end note
]
If the definition of a function or variable appears in a translation unit before its first declaration as inline, the program is ill-formed.
If a function or variable with external linkage is declared inline in one translation unit, it shall be declared inline in all translation units in which it appears; no diagnostic is required.
An inline function or variable with external linkage shall have the same address in all translation units.
[Note
:
A static local variable in an inline function with external linkage always refers to the same object.
A type defined within the body of an inline function with external linkage is the same type in every translation unit.
end note
]
The inline keyword has no effect on the linkage of a function.

10.1.7 Type specifiers [dcl.type]

As a general rule, at most one defining-type-specifier is allowed in the complete decl-specifier-seq of a declaration or in a defining-type-specifier-seq, and at most one type-specifier is allowed in a type-specifier-seq.
The only exceptions to this rule are the following:
  • const can be combined with any type specifier except itself.
  • volatile can be combined with any type specifier except itself.
  • signed or unsigned can be combined with char, long, short, or int.
  • short or long can be combined with int.
  • long can be combined with double.
  • long can be combined with long.
Except in a declaration of a constructor, destructor, or conversion function, at least one defining-type-specifier that is not a cv-qualifier shall appear in a complete type-specifier-seq or a complete decl-specifier-seq.95
[Note
:
enum-specifiers, class-specifiers, and typename-specifiers are discussed in [dcl.enum], Clause [class], and [temp.res], respectively.
The remaining type-specifiers are discussed in the rest of this section.
end note
]
There is no special provision for a decl-specifier-seq that lacks a type-specifier or that has a type-specifier that only specifies cv-qualifiers.
The “implicit int” rule of C is no longer supported.

10.1.7.1 The cv-qualifiers [dcl.type.cv]

There are two cv-qualifiers, const and volatile.
Each cv-qualifier shall appear at most once in a cv-qualifier-seq.
If a cv-qualifier appears in a decl-specifier-seq, the init-declarator-list or member-declarator-list of the declaration shall not be empty.
[Note
:
[basic.type.qualifier] and [dcl.fct] describe how cv-qualifiers affect object and function types.
end note
]
Redundant cv-qualifications are ignored.
[Note
:
For example, these could be introduced by typedefs.
end note
]
[Note
:
Declaring a variable const can affect its linkage ([dcl.stc]) and its usability in constant expressions ([expr.const]).
As described in [dcl.init], the definition of an object or subobject of const-qualified type must specify an initializer or be subject to default-initialization.
end note
]
A pointer or reference to a cv-qualified type need not actually point or refer to a cv-qualified object, but it is treated as if it does; a const-qualified access path cannot be used to modify an object even if the object referenced is a non-const object and can be modified through some other access path.
[Note
:
Cv-qualifiers are supported by the type system so that they cannot be subverted without casting ([expr.const.cast]).
end note
]
Except that any class member declared mutable ([dcl.stc]) can be modified, any attempt to modify a const object during its lifetime ([basic.life]) results in undefined behavior.
[Example
:
const int ci = 3;                       // cv-qualified (initialized as required)
ci = 4;                                 // ill-formed: attempt to modify const

int i = 2;                              // not cv-qualified
const int* cip;                         // pointer to const int
cip = &i;                               // OK: cv-qualified access path to unqualified
*cip = 4;                               // ill-formed: attempt to modify through ptr to const

int* ip;
ip = const_cast<int*>(cip);             // cast needed to convert const int* to int*
*ip = 4;                                // defined: *ip points to i, a non-const object

const int* ciq = new const int (3);     // initialized as required
int* iq = const_cast<int*>(ciq);        // cast required
*iq = 4;                                // undefined: modifies a const object
For another example,
struct X {
  mutable int i;
  int j;
};
struct Y {
  X x;
  Y();
};

const Y y;
y.x.i++;                                // well-formed: mutable member can be modified
y.x.j++;                                // ill-formed: const-qualified member modified
Y* p = const_cast<Y*>(&y);              // cast away const-ness of y
p->x.i = 99;                            // well-formed: mutable member can be modified
p->x.j = 99;                            // undefined: modifies a const member
end example
]
The semantics of an access through a volatile glvalue are implementation-defined.
If an attempt is made to access an object defined with a volatile-qualified type through the use of a non-volatile glvalue, the behavior is undefined.
[Note
:
volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.
Furthermore, for some implementations, volatile might indicate that special hardware instructions are required to access the object.
See [intro.execution] for detailed semantics.
In general, the semantics of volatile are intended to be the same in C++ as they are in C.
end note
]

10.1.7.2 Simple type specifiers [dcl.type.simple]

The simple type specifiers are
The simple-type-specifier auto is a placeholder for a type to be deduced ([dcl.spec.auto]).
A type-specifier of the form typename nested-name-specifier template-name is a placeholder for a deduced class type ([dcl.type.class.deduct]).
The template-name shall name a class template that is not an injected-class-name.
The other simple-type-specifiers specify either a previously-declared type, a type determined from an expression, or one of the fundamental types ([basic.fundamental]).
Table 11 summarizes the valid combinations of simple-type-specifiers and the types they specify.
Table 11simple-type-specifiers and the types they specify
Specifier(s)
Type
type-name
the type named
simple-template-id
the type as defined in [temp.names]
template-name
placeholder for a type to be deduced
char
“char”
unsigned char
“unsigned char”
signed char
“signed char”
char16_t
“char16_t”
char32_t
“char32_t”
bool
“bool”
unsigned
“unsigned int”
unsigned int
“unsigned int”
signed
“int”
signed int
“int”
int
“int”
unsigned short int
“unsigned short int”
unsigned short
“unsigned short int”
unsigned long int
“unsigned long int”
unsigned long
“unsigned long int”
unsigned long long int
“unsigned long long int”
unsigned long long
“unsigned long long int”
signed long int
“long int”
signed long
“long int”
signed long long int
“long long int”
signed long long
“long long int”
long long int
“long long int”
long long
“long long int”
long int
“long int”
long
“long int”
signed short int
“short int”
signed short
“short int”
short int
“short int”
short
“short int”
wchar_t
“wchar_t”
float
“float”
double
“double”
long double
“long double”
void
“void”
auto
placeholder for a type to be deduced
decltype(auto)
placeholder for a type to be deduced
decltype(expression)
the type as defined below
When multiple simple-type-specifiers are allowed, they can be freely intermixed with other decl-specifiers in any order.
[Note
:
It is implementation-defined whether objects of char type are represented as signed or unsigned quantities.
The signed specifier forces char objects to be signed; it is redundant in other contexts.
end note
]
For an expression e, the type denoted by decltype(e) is defined as follows:
  • if e is an unparenthesized id-expression naming a structured binding ([dcl.struct.bind]), decltype(e) is the referenced type as given in the specification of the structured binding declaration;
  • otherwise, if e is an unparenthesized id-expression or an unparenthesized class member access ([expr.ref]), decltype(e) is the type of the entity named by e.
    If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed;
  • otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;
  • otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;
  • otherwise, decltype(e) is the type of e.
The operand of the decltype specifier is an unevaluated operand (Clause [expr]).
[Example
:
const int&& foo();
int i;
struct A { double x; };
const A* a = new A();
decltype(foo()) x1 = 17;        // type is const int&&
decltype(i) x2;                 // type is int
decltype(a->x) x3;              // type is double
decltype((a->x)) x4 = x3;       // type is const double&
end example
]
[Note
:
The rules for determining types involving decltype(auto) are specified in [dcl.spec.auto].
end note
]
If the operand of a decltype-specifier is a prvalue, the temporary materialization conversion is not applied ([conv.rval]) and no result object is provided for the prvalue.
The type of the prvalue may be incomplete.
[Note
:
As a result, storage is not allocated for the prvalue and it is not destroyed.
Thus, a class type is not instantiated as a result of being the type of a function call in this context.
In this context, the common purpose of writing the expression is merely to refer to its type.
In that sense, a decltype-specifier is analogous to a use of a typedef-name, so the usual reasons for requiring a complete type do not apply.
In particular, it is not necessary to allocate storage for a temporary object or to enforce the semantic constraints associated with invoking the type's destructor.
end note
]
[Note
:
Unlike the preceding rule, parentheses have no special meaning in this context.
end note
]
[Example
:
template<class T> struct A { ~A() = delete; };
template<class T> auto h()
  -> A<T>;
template<class T> auto i(T)     // identity
  -> T;
template<class T> auto f(T)     // #1
  -> decltype(i(h<T>()));       // forces completion of A<T> and implicitly uses A<T>​::​~A()
                                // for the temporary introduced by the use of h().
                                // (A temporary is not introduced as a result of the use of i().)
template<class T> auto f(T)     // #2
  -> void;
auto g() -> void {
  f(42);                        // OK: calls #2. (#1 is not a viable candidate: type deduction
                                // fails ([temp.deduct]) because A<int>​::​~A() is implicitly used in its
                                // decltype-specifier)
}
template<class T> auto q(T)
  -> decltype((h<T>()));        // does not force completion of A<T>; A<T>​::​~A() is not implicitly
                                // used within the context of this decltype-specifier
void r() {
  q(42);                        // Error: deduction against q succeeds, so overload resolution selects
                                // the specialization “q(T) -> decltype((h<T>())) [with T=int]”.
                                // The return type is A<int>, so a temporary is introduced and its
                                // destructor is used, so the program is ill-formed.
}
end example
]

10.1.7.3 Elaborated type specifiers [dcl.type.elab]

An attribute-specifier-seq shall not appear in an elaborated-type-specifier unless the latter is the sole constituent of a declaration.
If an elaborated-type-specifier is the sole constituent of a declaration, the declaration is ill-formed unless it is an explicit specialization ([temp.expl.spec]), an explicit instantiation ([temp.explicit]) or it has one of the following forms:
class-key attribute-specifier-seq identifier ;
friend class-key :: identifier ;
friend class-key :: simple-template-id ;
friend class-key nested-name-specifier identifier ;
friend class-key nested-name-specifier template simple-template-id ;
In the first case, the attribute-specifier-seq, if any, appertains to the class being declared; the attributes in the attribute-specifier-seq are thereafter considered attributes of the class whenever it is named.
[basic.lookup.elab] describes how name lookup proceeds for the identifier in an elaborated-type-specifier.
If the identifier resolves to a class-name or enum-name, the elaborated-type-specifier introduces it into the declaration the same way a simple-type-specifier introduces its type-name.
If the identifier resolves to a typedef-name or the simple-template-id resolves to an alias template specialization, the elaborated-type-specifier is ill-formed.
[Note
:
This implies that, within a class template with a template type-parameter T, the declaration
friend class T;
is ill-formed.
However, the similar declaration friend T; is allowed ([class.friend]).
end note
]
The class-key or enum keyword present in the elaborated-type-specifier shall agree in kind with the declaration to which the name in the elaborated-type-specifier refers.
This rule also applies to the form of elaborated-type-specifier that declares a class-name or friend class since it can be construed as referring to the definition of the class.
Thus, in any elaborated-type-specifier, the enum keyword shall be used to refer to an enumeration ([dcl.enum]), the union class-key shall be used to refer to a union (Clause [class]), and either the class or struct class-key shall be used to refer to a class (Clause [class]) declared using the class or struct class-key.
[Example
:
enum class E { a, b };
enum E x = E::a;                // OK
end example
]

10.1.7.4 The auto specifier [dcl.spec.auto]

The auto and decltype(auto) type-specifiers are used to designate a placeholder type that will be replaced later by deduction from an initializer.
The auto type-specifier is also used to introduce a function type having a trailing-return-type or to signify that a lambda is a generic lambda ([expr.prim.lambda.closure]).
The auto type-specifier is also used to introduce a structured binding declaration ([dcl.struct.bind]).
The placeholder type can appear with a function declarator in the decl-specifier-seq, type-specifier-seq, conversion-function-id, or trailing-return-type, in any context where such a declarator is valid.
If the function declarator includes a trailing-return-type ([dcl.fct]), that trailing-return-type specifies the declared return type of the function.
Otherwise, the function declarator shall declare a function.
If the declared return type of the function contains a placeholder type, the return type of the function is deduced from non-discarded return statements, if any, in the body of the function ([stmt.if]).
[Example
:
auto glambda = [](int i, auto a) { return i; };     // OK: a generic lambda
end example
]
The type of a variable declared using auto or decltype(auto) is deduced from its initializer.
This use is allowed in an initializing declaration ([dcl.init]) of a variable.
auto or decltype(auto) shall appear as one of the decl-specifiers in the decl-specifier-seq and the decl-specifier-seq shall be followed by one or more declarators, each of which shall be followed by a non-empty initializer.
In an initializer of the form
( expression-list )
[Example
:
auto x = 5;                     // OK: x has type int
const auto *v = &x, u = 6;      // OK: v has type const int*, u has type const int
static auto y = 0.0;            // OK: y has type double
auto int r;                     // error: auto is not a storage-class-specifier
auto f() -> int;                // OK: f returns int
auto g() { return 0.0; }        // OK: g returns double
auto h();                       // OK: h's return type will be deduced when it is defined
end example
]
A placeholder type can also be used in the type-specifier-seq in the new-type-id or type-id of a new-expression and as a decl-specifier of the parameter-declaration's decl-specifier-seq in a template-parameter.
A program that uses auto or decltype(auto) in a context not explicitly allowed in this section is ill-formed.
If the init-declarator-list contains more than one init-declarator, they shall all form declarations of variables.
The type of each declared variable is determined by placeholder type deduction ([dcl.type.auto.deduct]), and if the type that replaces the placeholder type is not the same in each deduction, the program is ill-formed.
[Example
:
auto x = 5, *y = &x;            // OK: auto is int
auto a = 5, b = { 1, 2 };       // error: different types for auto
end example
]
If a function with a declared return type that contains a placeholder type has multiple non-discarded return statements, the return type is deduced for each such return statement.
If the type deduced is not the same in each deduction, the program is ill-formed.
If a function with a declared return type that uses a placeholder type has no non-discarded return statements, the return type is deduced as though from a return statement with no operand at the closing brace of the function body.
[Example
:
auto  f() { }                   // OK, return type is void
auto* g() { }                   // error, cannot deduce auto* from void()
end example
]
If the type of an entity with an undeduced placeholder type is needed to determine the type of an expression, the program is ill-formed.
Once a non-discarded return statement has been seen in a function, however, the return type deduced from that statement can be used in the rest of the function, including in other return statements.
[Example
:
auto n = n;                     // error, n's type is unknown
auto f();
void g() { &f; }                // error, f's return type is unknown
auto sum(int i) {
  if (i == 1)
    return i;                   // sum's return type is int
  else
    return sum(i-1)+i;          // OK, sum's return type has been deduced
}
end example
]
Return type deduction for a function template with a placeholder in its declared type occurs when the definition is instantiated even if the function body contains a return statement with a non-type-dependent operand.
[Note
:
Therefore, any use of a specialization of the function template will cause an implicit instantiation.
Any errors that arise from this instantiation are not in the immediate context of the function type and can result in the program being ill-formed ([temp.deduct]).
end note
]
[Example
:
template <class T> auto f(T t) { return t; }    // return type deduced at instantiation time
typedef decltype(f(1)) fint_t;                  // instantiates f<int> to deduce return type
template<class T> auto f(T* t) { return *t; }
void g() { int (*p)(int*) = &f; }               // instantiates both fs to determine return types,
                                                // chooses second
end example
]
Redeclarations or specializations of a function or function template with a declared return type that uses a placeholder type shall also use that placeholder, not a deduced type.
[Example
:
auto f();
auto f() { return 42; }                         // return type is int
auto f();                                       // OK
int f();                                        // error, cannot be overloaded with auto f()
decltype(auto) f();                             // error, auto and decltype(auto) don't match

template <typename T> auto g(T t) { return t; } // #1
template auto g(int);                           // OK, return type is int
template char g(char);                          // error, no matching template
template<> auto g(double);                      // OK, forward declaration with unknown return type

template <class T> T g(T t) { return t; }       // OK, not functionally equivalent to #1
template char g(char);                          // OK, now there is a matching template
template auto g(float);                         // still matches #1

void h() { return g(42); }                      // error, ambiguous

template <typename T> struct A {
  friend T frf(T);
};
auto frf(int i) { return i; }                   // not a friend of A<int>
end example
]
A function declared with a return type that uses a placeholder type shall not be virtual ([class.virtual]).
An explicit instantiation declaration ([temp.explicit]) does not cause the instantiation of an entity declared using a placeholder type, but it also does not prevent that entity from being instantiated as needed to determine its type.
[Example
:
template <typename T> auto f(T t) { return t; }
extern template auto f(int);    // does not instantiate f<int>
int (*p)(int) = f;              // instantiates f<int> to determine its return type, but an explicit
                                // instantiation definition is still required somewhere in the program
end example
]

10.1.7.4.1 Placeholder type deduction [dcl.type.auto.deduct]

Placeholder type deduction is the process by which a type containing a placeholder type is replaced by a deduced type.
A type T containing a placeholder type, and a corresponding initializer e, are determined as follows:
  • for a non-discarded return statement that occurs in a function declared with a return type that contains a placeholder type, T is the declared return type and e is the operand of the return statement.
    If the return statement has no operand, then e is void();
  • for a variable declared with a type that contains a placeholder type, T is the declared type of the variable and e is the initializer.
    If the initialization is direct-list-initialization, the initializer shall be a braced-init-list containing only a single assignment-expression and e is the assignment-expression;
  • for a non-type template parameter declared with a type that contains a placeholder type, T is the declared type of the non-type template parameter and e is the corresponding template argument.
In the case of a return statement with no operand or with an operand of type void, T shall be either decltype(auto) or cv auto.
If the deduction is for a return statement and e is a braced-init-list ([dcl.init.list]), the program is ill-formed.
If the placeholder is the auto type-specifier, the deduced type T' replacing T is determined using the rules for template argument deduction.
Obtain P from T by replacing the occurrences of auto with either a new invented type template parameter U or, if the initialization is copy-list-initialization, with std​::​initializer_­list<U>.
Deduce a value for U using the rules of template argument deduction from a function call ([temp.deduct.call]), where P is a function template parameter type and the corresponding argument is e.
If the deduction fails, the declaration is ill-formed.
Otherwise, T' is obtained by substituting the deduced U into P.
[Example
:
auto x1 = { 1, 2 };             // decltype(x1) is std​::​initializer_­list<int>
auto x2 = { 1, 2.0 };           // error: cannot deduce element type
auto x3{ 1, 2 };                // error: not a single element
auto x4 = { 3 };                // decltype(x4) is std​::​initializer_­list<int>
auto x5{ 3 };                   // decltype(x5) is int
end example
]
[Example
:
const auto &i = expr;
The type of i is the deduced type of the parameter u in the call f(expr) of the following invented function template:
template <class U> void f(const U& u);
end example
]
If the placeholder is the decltype(auto) type-specifier, T shall be the placeholder alone.
The type deduced for T is determined as described in [dcl.type.simple], as though e had been the operand of the decltype.
[Example
:
int i;
int&& f();
auto           x2a(i);          // decltype(x2a) is int
decltype(auto) x2d(i);          // decltype(x2d) is int
auto           x3a = i;         // decltype(x3a) is int
decltype(auto) x3d = i;         // decltype(x3d) is int
auto           x4a = (i);       // decltype(x4a) is int
decltype(auto) x4d = (i);       // decltype(x4d) is int&
auto           x5a = f();       // decltype(x5a) is int
decltype(auto) x5d = f();       // decltype(x5d) is int&&
auto           x6a = { 1, 2 };  // decltype(x6a) is std​::​initializer_­list<int>
decltype(auto) x6d = { 1, 2 };  // error, { 1, 2 } is not an expression
auto          *x7a = &i;        // decltype(x7a) is int*
decltype(auto)*x7d = &i;        // error, declared type is not plain decltype(auto)
end example
]

10.1.7.5 Deduced class template specialization types [dcl.type.class.deduct]

If a placeholder for a deduced class type appears as a decl-specifier in the decl-specifier-seq of an initializing declaration ([dcl.init]) of a variable, the placeholder is replaced by the return type of the function selected by overload resolution for class template deduction ([over.match.class.deduct]).
If the decl-specifier-seq is followed by an init-declarator-list or member-declarator-list containing more than one declarator, the type that replaces the placeholder shall be the same in each deduction.
A placeholder for a deduced class type can also be used in the type-specifier-seq in the new-type-id or type-id of a new-expression, or as the simple-type-specifier in an explicit type conversion (functional notation) ([expr.type.conv]).
A placeholder for a deduced class type shall not appear in any other context.
[Example
:
template<class T> struct container {
    container(T t) {}
    template<class Iter> container(Iter beg, Iter end);
};
template<class Iter>
container(Iter b, Iter e) -> container<typename std::iterator_traits<Iter>::value_type>;
std::vector<double> v = { /* ... */ };

container c(7);                         // OK, deduces int for T
auto d = container(v.begin(), v.end()); // OK, deduces double for T
container e{5, 6};                      // error, int is not an iterator
end example
]

10.2 Enumeration declarations [dcl.enum]

An enumeration is a distinct type ([basic.compound]) with named constants.
Its name becomes an enum-name within its scope.
A : following “enum nested-name-specifier identifier” within the decl-specifier-seq of a member-declaration is parsed as part of an enum-base.
[Note
:
This resolves a potential ambiguity between the declaration of an enumeration with an enum-base and the declaration of an unnamed bit-field of enumeration type.
[Example
:
   struct S {
     enum E : int {};
     enum E : int {};           // error: redeclaration of enumeration
   };
end example
]
end note
]
If an opaque-enum-declaration contains a nested-name-specifier, the declaration shall be an explicit specialization ([temp.expl.spec]).
The enumeration type declared with an enum-key of only enum is an unscoped enumeration, and its enumerators are unscoped enumerators.
The enum-keys enum class and enum struct are semantically equivalent; an enumeration type declared with one of these is a scoped enumeration, and its enumerators are scoped enumerators.
The optional identifier shall not be omitted in the declaration of a scoped enumeration.
The type-specifier-seq of an enum-base shall name an integral type; any cv-qualification is ignored.
An opaque-enum-declaration declaring an unscoped enumeration shall not omit the enum-base.
The identifiers in an enumerator-list are declared as constants, and can appear wherever constants are required.
An enumerator-definition with = gives the associated enumerator the value indicated by the constant-expression.
If the first enumerator has no initializer, the value of the corresponding constant is zero.
An enumerator-definition without an initializer gives the enumerator the value obtained by increasing the value of the previous enumerator by one.
[Example
:
enum { a, b, c=0 };
enum { d, e, f=e+2 };
defines a, c, and d to be zero, b and e to be 1, and f to be 3.
end example
]
The optional attribute-specifier-seq in an enumerator appertains to that enumerator.
An opaque-enum-declaration is either a redeclaration of an enumeration in the current scope or a declaration of a new enumeration.
[Note
:
An enumeration declared by an opaque-enum-declaration has fixed underlying type and is a complete type.
The list of enumerators can be provided in a later redeclaration with an enum-specifier.
end note
]
A scoped enumeration shall not be later redeclared as unscoped or with a different underlying type.
An unscoped enumeration shall not be later redeclared as scoped and each redeclaration shall include an enum-base specifying the same underlying type as in the original declaration.
If the enum-key is followed by a nested-name-specifier, the enum-specifier shall refer to an enumeration that was previously declared directly in the class or namespace to which the nested-name-specifier refers (i.e., neither inherited nor introduced by a using-declaration), and the enum-specifier shall appear in a namespace enclosing the previous declaration.
Each enumeration defines a type that is different from all other types.
Each enumeration also has an underlying type.
The underlying type can be explicitly specified using an enum-base.
For a scoped enumeration type, the underlying type is int if it is not explicitly specified.
In both of these cases, the underlying type is said to be fixed.
Following the closing brace of an enum-specifier, each enumerator has the type of its enumeration.
If the underlying type is fixed, the type of each enumerator prior to the closing brace is the underlying type and the constant-expression in the enumerator-definition shall be a converted constant expression of the underlying type ([expr.const]).
If the underlying type is not fixed, the type of each enumerator prior to the closing brace is determined as follows:
  • If an initializer is specified for an enumerator, the constant-expression shall be an integral constant expression ([expr.const]).
    If the expression has unscoped enumeration type, the enumerator has the underlying type of that enumeration type, otherwise it has the same type as the expression.
  • If no initializer is specified for the first enumerator, its type is an unspecified signed integral type.
  • Otherwise the type of the enumerator is the same as that of the preceding enumerator unless the incremented value is not representable in that type, in which case the type is an unspecified integral type sufficient to contain the incremented value.
    If no such type exists, the program is ill-formed.
An enumeration whose underlying type is fixed is an incomplete type from its point of declaration ([basic.scope.pdecl]) to immediately after its enum-base (if any), at which point it becomes a complete type.
An enumeration whose underlying type is not fixed is an incomplete type from its point of declaration to immediately after the closing } of its enum-specifier, at which point it becomes a complete type.
For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration.
If no integral type can represent all the enumerator values, the enumeration is ill-formed.
It is implementation-defined which integral type is used as the underlying type except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int.
If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0.
For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type.
Otherwise, for an enumeration where is the smallest enumerator and is the largest, the values of the enumeration are the values in the range to , defined as follows: Let K be 1 for a two's complement representation and 0 for a ones' complement or sign-magnitude representation.
is the smallest value greater than or equal to and equal to , where M is a non-negative integer.
is zero if is non-negative and otherwise.
The size of the smallest bit-field large enough to hold all the values of the enumeration type is if is zero and otherwise.
It is possible to define an enumeration that has values not defined by any of its enumerators.
If the enumerator-list is empty, the values of the enumeration are as if the enumeration had a single enumerator with value 0.96
Two enumeration types are layout-compatible enumerations if they have the same underlying type.
The value of an enumerator or an object of an unscoped enumeration type is converted to an integer by integral promotion ([conv.prom]).
[Example
:
  enum color { red, yellow, green=20, blue };
  color col = red;
  color* cp = &col;
  if (*cp == blue)              // ...
makes color a type describing various colors, and then declares col as an object of that type, and cp as a pointer to an object of that type.
The possible values of an object of type color are red, yellow, green, blue; these values can be converted to the integral values 0, 1, 20, and 21.
Since enumerations are distinct types, objects of type color can be assigned only values of type color.
color c = 1;                    // error: type mismatch, no conversion from int to color
int i = yellow;                 // OK: yellow converted to integral value 1, integral promotion
Note that this implicit enum to int conversion is not provided for a scoped enumeration:
enum class Col { red, yellow, green };
int x = Col::red;               // error: no Col to int conversion
Col y = Col::red;
if (y) { }                      // error: no Col to bool conversion
end example
]
Each enum-name and each unscoped enumerator is declared in the scope that immediately contains the enum-specifier.
Each scoped enumerator is declared in the scope of the enumeration.
These names obey the scope rules defined for all names in [basic.scope] and [basic.lookup].
[Example
:
enum direction { left='l', right='r' };

void g()  {
  direction d;                  // OK
  d = left;                     // OK
  d = direction::right;         // OK
}

enum class altitude { high='h', low='l' };

void h()  {
  altitude a;                   // OK
  a = high;                     // error: high not in scope
  a = altitude::low;            // OK
}
end example
]
An enumerator declared in class scope can be referred to using the class member access operators (​::​, . (dot) and -> (arrow)), see [expr.ref].
[Example
:
struct X {
  enum direction { left='l', right='r' };
  int f(int i) { return i==left ? 0 : i==right ? 1 : 2; }
};

void g(X* p) {
  direction d;                  // error: direction not in scope
  int i;
  i = p->f(left);               // error: left not in scope
  i = p->f(X::right);           // OK
  i = p->f(p->left);            // OK
  // ...
}
end example
]
If an enum-head contains a nested-name-specifier, the enum-specifier shall refer to an enumeration that was previously declared directly in the class or namespace to which the nested-name-specifier refers, or in an element of the inline namespace set ([namespace.def]) of that namespace (i.e., not merely inherited or introduced by a using-declaration), and the enum-specifier shall appear in a namespace enclosing the previous declaration.
In such cases, the nested-name-specifier of the enum-head of the definition shall not begin with a decltype-specifier.
This set of values is used to define promotion and conversion semantics for the enumeration type.
It does not preclude an expression of enumeration type from having a value that falls outside this range.

10.3 Namespaces [basic.namespace]

A namespace is an optionally-named declarative region.
The name of a namespace can be used to access entities declared in that namespace; that is, the members of the namespace.
Unlike other declarative regions, the definition of a namespace can be split over several parts of one or more translation units.
The outermost declarative region of a translation unit is a namespace; see [basic.scope.namespace].

10.3.1 Namespace definition [namespace.def]

Every namespace-definition shall appear in the global scope or in a namespace scope ([basic.scope.namespace]).
In a named-namespace-definition, the identifier is the name of the namespace.
If the identifier, when looked up ([basic.lookup.unqual]), refers to a namespace-name (but not a namespace-alias) that was introduced in the namespace in which the named-namespace-definition appears or that was introduced in a member of the inline namespace set of that namespace, the namespace-definition extends the previously-declared namespace.
Otherwise, the identifier is introduced as a namespace-name into the declarative region in which the named-namespace-definition appears.
Because a namespace-definition contains declarations in its namespace-body and a namespace-definition is itself a declaration, it follows that namespace-definitions can be nested.
[Example
:
namespace Outer {
  int i;
  namespace Inner {
    void f() { i++; }           // Outer​::​i
    int i;
    void g() { i++; }           // Inner​::​i
  }
}
end example
]
The enclosing namespaces of a declaration are those namespaces in which the declaration lexically appears, except for a redeclaration of a namespace member outside its original namespace (e.g., a definition as specified in [namespace.memdef]).
Such a redeclaration has the same enclosing namespaces as the original declaration.
[Example
:
namespace Q {
  namespace V {
    void f();                   // enclosing namespaces are the global namespace, Q, and Q​::​V
    class C { void m(); };
  }
  void V::f() {                 // enclosing namespaces are the global namespace, Q, and Q​::​V
    extern void h();            // ... so this declares Q​::​V​::​h
  }
  void V::C::m() {              // enclosing namespaces are the global namespace, Q, and Q​::​V
  }
}
end example
]
If the optional initial inline keyword appears in a namespace-definition for a particular namespace, that namespace is declared to be an inline namespace.
The inline keyword may be used on a namespace-definition that extends a namespace only if it was previously used on the namespace-definition that initially declared the namespace-name for that namespace.
The optional attribute-specifier-seq in a named-namespace-definition appertains to the namespace being defined or extended.
Members of an inline namespace can be used in most respects as though they were members of the enclosing namespace.
Specifically, the inline namespace and its enclosing namespace are both added to the set of associated namespaces used in argument-dependent lookup ([basic.lookup.argdep]) whenever one of them is, and a using-directive that names the inline namespace is implicitly inserted into the enclosing namespace as for an unnamed namespace ([namespace.unnamed]).
Furthermore, each member of the inline namespace can subsequently be partially specialized ([temp.class.spec]), explicitly instantiated ([temp.explicit]), or explicitly specialized ([temp.expl.spec]) as though it were a member of the enclosing namespace.
Finally, looking up a name in the enclosing namespace via explicit qualification ([namespace.qual]) will include members of the inline namespace brought in by the using-directive even if there are declarations of that name in the enclosing namespace.
These properties are transitive: if a namespace N contains an inline namespace M, which in turn contains an inline namespace O, then the members of O can be used as though they were members of M or N.
The inline namespace set of N is the transitive closure of all inline namespaces in N.
The enclosing namespace set of O is the set of namespaces consisting of the innermost non-inline namespace enclosing an inline namespace O, together with any intervening inline namespaces.
A nested-namespace-definition with an enclosing-namespace-specifier E, identifier I and namespace-body B is equivalent to
namespace E { namespace I { B } }
[Example
:
namespace A::B::C {
  int i;
}
The above has the same effect as:
namespace A {
  namespace B {
    namespace C {
      int i;
    }
  }
}
end example
]

10.3.1.1 Unnamed namespaces [namespace.unnamed]

An unnamed-namespace-definition behaves as if it were replaced by
inline namespace unique { /* empty body */ }
using namespace unique ;
namespace unique { namespace-body }
where inline appears if and only if it appears in the unnamed-namespace-definition and all occurrences of unique in a translation unit are replaced by the same identifier, and this identifier differs from all other identifiers in the translation unit.
The optional attribute-specifier-seq in the unnamed-namespace-definition appertains to unique.
[Example
:
namespace { int i; }            // unique​::​i
void f() { i++; }               // unique​::​i++

namespace A {
  namespace {
    int i;                      // A​::​unique​::​i
    int j;                      // A​::​unique​::​j
  }
  void g() { i++; }             // A​::​unique​::​i++
}

using namespace A;
void h() {
  i++;                          // error: unique​::​i or A​::​unique​::​i
  A::i++;                       // A​::​unique​::​i
  j++;                          // A​::​unique​::​j
}
end example
]

10.3.1.2 Namespace member definitions [namespace.memdef]

A declaration in a namespace N (excluding declarations in nested scopes) whose declarator-id is an unqualified-id ([dcl.meaning]), whose class-head-name or enum-head-name is an identifier, or whose elaborated-type-specifier is of the form class-key attribute-specifier-seq identifier ([dcl.type.elab]), or that is an opaque-enum-declaration, declares (or redeclares) its unqualified-id or identifier as a member of N.
[Note
:
An explicit instantiation ([temp.explicit]) or explicit specialization ([temp.expl.spec]) of a template does not introduce a name and thus may be declared using an unqualified-id in a member of the enclosing namespace set, if the primary template is declared in an inline namespace.
end note
]
[Example
:
namespace X {
  void f() { /* ... */ }        // OK: introduces X​::​f()

  namespace M {
    void g();                   // OK: introduces X​::​M​::​g()
  }
  using M::g;
  void g();                     // error: conflicts with X​::​M​::​g()
}
end example
]
Members of a named namespace can also be defined outside that namespace by explicit qualification ([namespace.qual]) of the name being defined, provided that the entity being defined was already declared in the namespace and the definition appears after the point of declaration in a namespace that encloses the declaration's namespace.
[Example
:
namespace Q {
  namespace V {
    void f();
  }
  void V::f() { /* ... */ }     // OK
  void V::g() { /* ... */ }     // error: g() is not yet a member of V
  namespace V {
    void g();
  }
}

namespace R {
  void Q::V::g() { /* ... */ }  // error: R doesn't enclose Q
}
end example
]
If a friend declaration in a non-local class first declares a class, function, class template or function template97 the friend is a member of the innermost enclosing namespace.
The friend declaration does not by itself make the name visible to unqualified lookup ([basic.lookup.unqual]) or qualified lookup ([basic.lookup.qual]).
[Note
:
The name of the friend will be visible in its namespace if a matching declaration is provided at namespace scope (either before or after the class definition granting friendship).
end note
]
If a friend function or function template is called, its name may be found by the name lookup that considers functions from namespaces and classes associated with the types of the function arguments ([basic.lookup.argdep]).
If the name in a friend declaration is neither qualified nor a template-id and the declaration is a function or an elaborated-type-specifier, the lookup to determine whether the entity has been previously declared shall not consider any scopes outside the innermost enclosing namespace.
[Note
:
The other forms of friend declarations cannot declare a new member of the innermost enclosing namespace and thus follow the usual lookup rules.
end note
]
[Example
:
// Assume f and g have not yet been declared.
void h(int);
template <class T> void f2(T);
namespace A {
  class X {
    friend void f(X);           // A​::​f(X) is a friend
    class Y {
      friend void g();          // A​::​g is a friend
      friend void h(int);       // A​::​h is a friend
                                // ​::​h not considered
      friend void f2<>(int);    // ​::​f2<>(int) is a friend
    };
  };

  // A​::​f, A​::​g and A​::​h are not visible here
  X x;
  void g() { f(x); }            // definition of A​::​g
  void f(X) { /* ... */ }       // definition of A​::​f
  void h(int) { /* ... */ }     // definition of A​::​h
  // A​::​f, A​::​g and A​::​h are visible here and known to be friends
}

using A::x;

void h() {
  A::f(x);
  A::X::f(x);                   // error: f is not a member of A​::​X
  A::X::Y::g();                 // error: g is not a member of A​::​X​::​Y
}
end example
]
this implies that the name of the class or function is unqualified.

10.3.2 Namespace alias [namespace.alias]

The identifier in a namespace-alias-definition is a synonym for the name of the namespace denoted by the qualified-namespace-specifier and becomes a namespace-alias.
[Note
:
When looking up a namespace-name in a namespace-alias-definition, only namespace names are considered, see [basic.lookup.udir].
end note
]
In a declarative region, a namespace-alias-definition can be used to redefine a namespace-alias declared in that declarative region to refer only to the namespace to which it already refers.
[Example
:
The following declarations are well-formed:
namespace Company_with_very_long_name { /* ... */ }
namespace CWVLN = Company_with_very_long_name;
namespace CWVLN = Company_with_very_long_name;  // OK: duplicate
namespace CWVLN = CWVLN;
end example
]

10.3.3 The using declaration [namespace.udecl]

Each using-declarator in a using-declaration98 introduces a set of declarations into the declarative region in which the using-declaration appears.
The set of declarations introduced by the using-declarator is found by performing qualified name lookup ([basic.lookup.qual], [class.member.lookup]) for the name in the using-declarator, excluding functions that are hidden as described below.
If the using-declarator does not name a constructor, the unqualified-id is declared in the declarative region in which the using-declaration appears as a synonym for each declaration introduced by the using-declarator.
[Note
:
Only the specified name is so declared; specifying an enumeration name in a using-declaration does not declare its enumerators in the using-declaration's declarative region.
end note
]
If the using-declarator names a constructor, it declares that the class inherits the set of constructor declarations introduced by the using-declarator from the nominated base class.
Every using-declaration is a declaration and a member-declaration and can therefore be used in a class definition.
[Example
:
struct B {
  void f(char);
  void g(char);
  enum E { e };
  union { int x; };
};

struct D : B {
  using B::f;
  void f(int) { f('c'); }       // calls B​::​f(char)
  void g(int) { g('c'); }       // recursively calls D​::​g(int)
};
end example
]
In a using-declaration used as a member-declaration, each using-declarator's nested-name-specifier shall name a base class of the class being defined.
If a using-declarator names a constructor, its nested-name-specifier shall name a direct base class of the class being defined.
[Example
:
template <typename... bases>
struct X : bases... {
  using bases::g...;
};

X<B, D> x;                      // OK: B​::​g and D​::​g introduced
end example
]
[Example
:
class C {
  int g();
};

class D2 : public B {
  using B::f;                   // OK: B is a base of D2
  using B::e;                   // OK: e is an enumerator of base B
  using B::x;                   // OK: x is a union member of base B
  using C::g;                   // error: C isn't a base of D2
};
end example
]
[Note
:
Since destructors do not have names, a using-declaration cannot refer to a destructor for a base class.
Since specializations of member templates for conversion functions are not found by name lookup, they are not considered when a using-declaration specifies a conversion function ([temp.mem]).
end note
]
If a constructor or assignment operator brought from a base class into a derived class has the signature of a copy/move constructor or assignment operator for the derived class ([class.copy]), the using-declaration does not by itself suppress the implicit declaration of the derived class member; the member from the base class is hidden or overridden by the implicitly-declared copy/move constructor or assignment operator of the derived class, as described below.
A using-declaration shall not name a template-id.
[Example
:
struct A {
  template <class T> void f(T);
  template <class T> struct X { };
};
struct B : A {
  using A::f<double>;           // ill-formed
  using A::X<int>;              // ill-formed
};
end example
]
A using-declaration shall not name a namespace.
A using-declaration shall not name a scoped enumerator.
A using-declaration that names a class member shall be a member-declaration.
[Example
:
struct X {
  int i;
  static int s;
};

void f() {
  using X::i;                   // error: X​::​i is a class member and this is not a member declaration.
  using X::s;                   // error: X​::​s is a class member and this is not a member declaration.
}
end example
]
Members declared by a using-declaration can be referred to by explicit qualification just like other member names ([namespace.qual]).
[Example
:
void f();

namespace A {
  void g();
}

namespace X {
  using ::f;                    // global f
  using A::g;                   // A's g
}

void h()
{
  X::f();                       // calls ​::​f
  X::g();                       // calls A​::​g
}
end example
]
A using-declaration is a declaration and can therefore be used repeatedly where (and only where) multiple declarations are allowed.
[Example
:
namespace A {
  int i;
}

namespace A1 {
  using A::i, A::i;             // OK: double declaration
}

struct B {
  int i;
};

struct X : B {
  using B::i, B::i;             // error: double member declaration
};
end example
]
[Note
:
For a using-declaration whose nested-name-specifier names a namespace, members added to the namespace after the using-declaration are not in the set of introduced declarations, so they are not considered when a use of the name is made.
Thus, additional overloads added after the using-declaration are ignored, but default function arguments ([dcl.fct.default]), default template arguments ([temp.param]), and template specializations ([temp.class.spec], [temp.expl.spec]) are considered.
end note
]
[Example
:
namespace A {
  void f(int);
}

using A::f;         // f is a synonym for A​::​f; that is, for A​::​f(int).
namespace A {
  void f(char);
}

void foo() {
  f('a');           // calls f(int), even though f(char) exists.
}

void bar() {
  using A::f;       // f is a synonym for A​::​f; that is, for A​::​f(int) and A​::​f(char).
  f('a');           // calls f(char)
}
end example
]
[Note
:
Partial specializations of class templates are found by looking up the primary class template and then considering all partial specializations of that template.
If a using-declaration names a class template, partial specializations introduced after the using-declaration are effectively visible because the primary template is visible ([temp.class.spec]).
end note
]
Since a using-declaration is a declaration, the restrictions on declarations of the same name in the same declarative region ([basic.scope]) also apply to using-declarations.
[Example
:
namespace A {
  int x;
}

namespace B {
  int i;
  struct g { };
  struct x { };
  void f(int);
  void f(double);
  void g(char);     // OK: hides struct g
}

void func() {
  int i;
  using B::i;       // error: i declared twice
  void f(char);
  using B::f;       // OK: each f is a function
  f(3.5);           // calls B​::​f(double)
  using B::g;
  g('a');           // calls B​::​g(char)
  struct g g1;      // g1 has class type B​::​g
  using B::x;
  using A::x;       // OK: hides struct B​::​x
  x = 99;           // assigns to A​::​x
  struct x x1;      // x1 has class type B​::​x
}
end example
]
If a function declaration in namespace scope or block scope has the same name and the same parameter-type-list ([dcl.fct]) as a function introduced by a using-declaration, and the declarations do not declare the same function, the program is ill-formed.
If a function template declaration in namespace scope has the same name, parameter-type-list, return type, and template parameter list as a function template introduced by a using-declaration, the program is ill-formed.
[Note
:
Two using-declarations may introduce functions with the same name and the same parameter-type-list.
If, for a call to an unqualified function name, function overload resolution selects the functions introduced by such using-declarations, the function call is ill-formed.
[Example
:
namespace B {
  void f(int);
  void f(double);
}
namespace C {
  void f(int);
  void f(double);
  void f(char);
}

void h() {
  using B::f;       // B​::​f(int) and B​::​f(double)
  using C::f;       // C​::​f(int), C​::​f(double), and C​::​f(char)
  f('h');           // calls C​::​f(char)
  f(1);             // error: ambiguous: B​::​f(int) or C​::​f(int)?
  void f(int);      // error: f(int) conflicts with C​::​f(int) and B​::​f(int)
}
end example
]
end note
]
When a using-declarator brings declarations from a base class into a derived class, member functions and member function templates in the derived class override and/or hide member functions and member function templates with the same name, parameter-type-list ([dcl.fct]), cv-qualification, and ref-qualifier (if any) in a base class (rather than conflicting).
Such hidden or overridden declarations are excluded from the set of declarations introduced by the using-declarator.
[Example
:
struct B {
  virtual void f(int);
  virtual void f(char);
  void g(int);
  void h(int);
};

struct D : B {
  using B::f;
  void f(int);      // OK: D​::​f(int) overrides B​::​f(int);

  using B::g;
  void g(char);     // OK

  using B::h;
  void h(int);      // OK: D​::​h(int) hides B​::​h(int)
};

void k(D* p)
{
  p->f(1);          // calls D​::​f(int)
  p->f('a');        // calls B​::​f(char)
  p->g(1);          // calls B​::​g(int)
  p->g('a');        // calls D​::​g(char)
}

struct B1 {
  B1(int);
};

struct B2 {
  B2(int);
};

struct D1 : B1, B2 {
  using B1::B1;
  using B2::B2;
};
D1 d1(0);           // ill-formed: ambiguous

struct D2 : B1, B2 {
  using B1::B1;
  using B2::B2;
  D2(int);          // OK: D2​::​D2(int) hides B1​::​B1(int) and B2​::​B2(int)
};
D2 d2(0);           // calls D2​::​D2(int)
end example
]
For the purpose of overload resolution, the functions that are introduced by a using-declaration into a derived class are treated as though they were members of the derived class.
In particular, the implicit this parameter shall be treated as if it were a pointer to the derived class rather than to the base class.
This has no effect on the type of the function, and in all other respects the function remains a member of the base class.
Likewise, constructors that are introduced by a using-declaration are treated as though they were constructors of the derived class when looking up the constructors of the derived class ([class.qual]) or forming a set of overload candidates ([over.match.ctor], [over.match.copy], [over.match.list]).
If such a constructor is selected to perform the initialization of an object of class type, all subobjects other than the base class from which the constructor originated are implicitly initialized ([class.inhctor.init]).
In a using-declarator that does not name a constructor, all members of the set of introduced declarations shall be accessible.
In a using-declarator that names a constructor, no access check is performed.
In particular, if a derived class uses a using-declarator to access a member of a base class, the member name shall be accessible.
If the name is that of an overloaded member function, then all functions named shall be accessible.
The base class members mentioned by a using-declarator shall be visible in the scope of at least one of the direct base classes of the class where the using-declarator is specified.
[Note
:
Because a using-declarator designates a base class member (and not a member subobject or a member function of a base class subobject), a using-declarator cannot be used to resolve inherited member ambiguities.
[Example
:
struct A { int x(); };
struct B : A { };
struct C : A {
  using A::x;
  int x(int);
};

struct D : B, C {
  using C::x;
  int x(double);
};
int f(D* d) {
  return d->x();    // error: overload resolution selects A​::​x, but A is an ambiguous base class
}
end example
]
end note
]
A synonym created by a using-declaration has the usual accessibility for a member-declaration.
A using-declarator that names a constructor does not create a synonym; instead, the additional constructors are accessible if they would be accessible when used to construct an object of the corresponding base class, and the accessibility of the using-declaration is ignored.
[Example
:
class A {
private:
    void f(char);
public:
    void f(int);
protected:
    void g();
};

class B : public A {
  using A::f;       // error: A​::​f(char) is inaccessible
public:
  using A::g;       // B​::​g is a public synonym for A​::​g
};
end example
]
If a using-declarator uses the keyword typename and specifies a dependent name ([temp.dep]), the name introduced by the using-declaration is treated as a typedef-name.
A using-declaration with more than one using-declarator is equivalent to a corresponding sequence of using-declarations with one using-declarator each.

10.3.4 Using directive [namespace.udir]

A using-directive shall not appear in class scope, but may appear in namespace scope or in block scope.
[Note
:
When looking up a namespace-name in a using-directive, only namespace names are considered, see [basic.lookup.udir].
end note
]
The optional attribute-specifier-seq appertains to the using-directive.
A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive.
During unqualified name lookup ([basic.lookup.unqual]), the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace.
[Note
:
In this context, “contains” means “contains directly or indirectly”.
end note
]
A using-directive does not add any members to the declarative region in which it appears.
[Example
:
namespace A {
  int i;
  namespace B {
    namespace C {
      int i;
    }
    using namespace A::B::C;
    void f1() {
      i = 5;        // OK, C​::​i visible in B and hides A​::​i
    }
  }
  namespace D {
    using namespace B;
    using namespace C;
    void f2() {
      i = 5;        // ambiguous, B​::​C​::​i or A​::​i?
    }
  }
  void f3() {
    i = 5;          // uses A​::​i
  }
}
void f4() {
  i = 5;            // ill-formed; neither i is visible
}
end example
]
For unqualified lookup ([basic.lookup.unqual]), the using-directive is transitive: if a scope contains a using-directive that nominates a second namespace that itself contains using-directives, the effect is as if the using-directives from the second namespace also appeared in the first.
[Note
:
For qualified lookup, see [namespace.qual].
end note
]
[Example
:
namespace M {
  int i;
}

namespace N {
  int i;
  using namespace M;
}

void f() {
  using namespace N;
  i = 7;            // error: both M​::​i and N​::​i are visible
}
For another example,
namespace A {
  int i;
}
namespace B {
  int i;
  int j;
  namespace C {
    namespace D {
      using namespace A;
      int j;
      int k;
      int a = i;    // B​::​i hides A​::​i
    }
    using namespace D;
    int k = 89;     // no problem yet
    int l = k;      // ambiguous: C​::​k or D​::​k
    int m = i;      // B​::​i hides A​::​i
    int n = j;      // D​::​j hides B​::​j
  }
}
end example
]
If a namespace is extended ([namespace.def]) after a using-directive for that namespace is given, the additional members of the extended namespace and the members of namespaces nominated by using-directives in the extending namespace-definition can be used after the extending namespace-definition.
If name lookup finds a declaration for a name in two different namespaces, and the declarations do not declare the same entity and do not declare functions, the use of the name is ill-formed.
[Note
:
In particular, the name of a variable, function or enumerator does not hide the name of a class or enumeration declared in a different namespace.
For example,
namespace A {
  class X { };
  extern "C"   int g();
  extern "C++" int h();
}
namespace B {
  void X(int);
  extern "C"   int g();
  extern "C++" int h(int);
}
using namespace A;
using namespace B;

void f() {
  X(1);             // error: name X found in two namespaces
  g();              // OK: name g refers to the same entity
  h();              // OK: overload resolution selects A​::​h
}
end note
]
During overload resolution, all functions from the transitive search are considered for argument matching.
The set of declarations found by the transitive search is unordered.
[Note
:
In particular, the order in which namespaces were considered and the relationships among the namespaces implied by the using-directives do not cause preference to be given to any of the declarations found by the search.
end note
]
An ambiguity exists if the best match finds two functions with the same signature, even if one is in a namespace reachable through using-directives in the namespace of the other.99
[Example
:
namespace D {
  int d1;
  void f(char);
}
using namespace D;

int d1;             // OK: no conflict with D​::​d1

namespace E {
  int e;
  void f(int);
}

namespace D {       // namespace extension
  int d2;
  using namespace E;
  void f(int);
}

void f() {
  d1++;             // error: ambiguous ​::​d1 or D​::​d1?
  ::d1++;           // OK
  D::d1++;          // OK
  d2++;             // OK: D​::​d2
  e++;              // OK: E​::​e
  f(1);             // error: ambiguous: D​::​f(int) or E​::​f(int)?
  f('a');           // OK: D​::​f(char)
}
end example
]
During name lookup in a class hierarchy, some ambiguities may be resolved by considering whether one member hides the other along some paths ([class.member.lookup]).
There is no such disambiguation when considering the set of names found as a result of following using-directives.

10.4 The asm declaration [dcl.asm]

An asm declaration has the form
asm-definition:
	attribute-specifier-seq asm ( string-literal ) ;
The asm declaration is conditionally-supported; its meaning is implementation-defined.
The optional attribute-specifier-seq in an asm-definition appertains to the asm declaration.
[Note
:
Typically it is used to pass information through the implementation to an assembler.
end note
]

10.6 Attributes [dcl.attr]

10.6.1 Attribute syntax and semantics [dcl.attr.grammar]

If an attribute-specifier contains an attribute-using-prefix, the attribute-list following that attribute-using-prefix shall not contain an attribute-scoped-token and every attribute-token in that attribute-list is treated as if its identifier were prefixed with N​::​, where N is the attribute-namespace specified in the attribute-using-prefix.
[Note
:
This rule imposes no constraints on how an attribute-using-prefix affects the tokens in an attribute-argument-clause.
end note
]
[Example
:
[[using CC: opt(1), debug]]         // same as [[CC​::​opt(1), CC​::​debug]]
  void f() {}
[[using CC: opt(1)]] [[CC::debug]]  // same as [[CC​::​opt(1)]] [[CC​::​debug]]
  void g() {}
[[using CC: CC::opt(1)]]            // error: cannot combine using and scoped attribute token
  void h() {}
end example
]
[Note
:
For each individual attribute, the form of the balanced-token-seq will be specified.
end note
]
In an attribute-list, an ellipsis may appear only if that attribute's specification permits it.
An attribute followed by an ellipsis is a pack expansion ([temp.variadic]).
An attribute-specifier that contains no attributes has no effect.
The order in which the attribute-tokens appear in an attribute-list is not significant.
If a keyword ([lex.key]) or an alternative token ([lex.digraph]) that satisfies the syntactic requirements of an identifier is contained in an attribute-token, it is considered an identifier.
No name lookup ([basic.lookup]) is performed on any of the identifiers contained in an attribute-token.
The attribute-token determines additional requirements on the attribute-argument-clause (if any).
Each attribute-specifier-seq is said to appertain to some entity or statement, identified by the syntactic context where it appears (Clause [stmt.stmt], Clause [dcl.dcl], Clause [dcl.decl]).
If an attribute-specifier-seq that appertains to some entity or statement contains an attribute or alignment-specifier that is not allowed to apply to that entity or statement, the program is ill-formed.
If an attribute-specifier-seq appertains to a friend declaration ([class.friend]), that declaration shall be a definition.
No attribute-specifier-seq shall appertain to an explicit instantiation ([temp.explicit]).
For an attribute-token (including an attribute-scoped-token) not specified in this International Standard, the behavior is implementation-defined.
Any attribute-token that is not recognized by the implementation is ignored.
[Note
:
Each implementation should choose a distinctive name for the attribute-namespace in an attribute-scoped-token.
end note
]
Two consecutive left square bracket tokens shall appear only when introducing an attribute-specifier or within the balanced-token-seq of an attribute-argument-clause.
[Note
:
If two consecutive left square brackets appear where an attribute-specifier is not allowed, the program is ill-formed even if the brackets match an alternative grammar production.
end note
]
[Example
:
int p[10];
void f() {
  int x = 42, y[5];
  int(p[[x] { return x; }()]);  // error: invalid attribute on a nested declarator-id and
                                // not a function-style cast of an element of p.
  y[[] { return 2; }()] = 2;    // error even though attributes are not allowed in this context.
  int i [[vendor::attr([[]])]]; // well-formed implementation-defined attribute.
}
end example
]

10.6.2 Alignment specifier [dcl.align]

An alignment-specifier may be applied to a variable or to a class data member, but it shall not be applied to a bit-field, a function parameter, or an exception-declaration ([except.handle]).
An alignment-specifier may also be applied to the declaration or definition of a class (in an elaborated-type-specifier or class-head, respectively) and to the declaration or definition of an enumeration (in an opaque-enum-declaration or enum-head, respectively ([dcl.enum])).
An alignment-specifier with an ellipsis is a pack expansion ([temp.variadic]).
When the alignment-specifier is of the form alignas( constant-expression ):
  • the constant-expression shall be an integral constant expression
  • if the constant expression does not evaluate to an alignment value ([basic.align]), or evaluates to an extended alignment and the implementation does not support that alignment in the context of the declaration, the program is ill-formed.
An alignment-specifier of the form alignas( type-id ) has the same effect as alignas(​alignof( type-id )) ([expr.alignof]).
The alignment requirement of an entity is the strictest nonzero alignment specified by its alignment-specifiers, if any; otherwise, the alignment-specifiers have no effect.
The combined effect of all alignment-specifiers in a declaration shall not specify an alignment that is less strict than the alignment that would be required for the entity being declared if all alignment-specifiers appertaining to that entity were omitted.
[Example
:
struct alignas(8) S {};
struct alignas(1) U {
  S s;
};  // error: U specifies an alignment that is less strict than if the alignas(1) were omitted.
end example
]
If the defining declaration of an entity has an alignment-specifier, any non-defining declaration of that entity shall either specify equivalent alignment or have no alignment-specifier.
Conversely, if any declaration of an entity has an alignment-specifier, every defining declaration of that entity shall specify an equivalent alignment.
No diagnostic is required if declarations of an entity have different alignment-specifiers in different translation units.
[Example
:
// Translation unit #1:
struct S { int x; } s, *p = &s;

// Translation unit #2:
struct alignas(16) S;           // error: definition of S lacks alignment, no diagnostic required
extern S* p;
end example
]
[Example
:
An aligned buffer with an alignment requirement of A and holding N elements of type T can be declared as:
alignas(T) alignas(A) T buffer[N];
Specifying alignas(T) ensures that the final requested alignment will not be weaker than alignof(T), and therefore the program will not be ill-formed.
end example
]
[Example
:
alignas(double) void f();                           // error: alignment applied to function
alignas(double) unsigned char c[sizeof(double)];    // array of characters, suitably aligned for a double
extern unsigned char c[sizeof(double)];             // no alignas necessary
alignas(float)
  extern unsigned char c[sizeof(double)];           // error: different alignment in declaration
end example
]

10.6.3 Carries dependency attribute [dcl.attr.depend]

The attribute-token carries_­dependency specifies dependency propagation into and out of functions.
It shall appear at most once in each attribute-list and no attribute-argument-clause shall be present.
The attribute may be applied to the declarator-id of a parameter-declaration in a function declaration or lambda, in which case it specifies that the initialization of the parameter carries a dependency to ([intro.multithread]) each lvalue-to-rvalue conversion ([conv.lval]) of that object.
The attribute may also be applied to the declarator-id of a function declaration, in which case it specifies that the return value, if any, carries a dependency to the evaluation of the function call expression.
The first declaration of a function shall specify the carries_­dependency attribute for its declarator-id if any declaration of the function specifies the carries_­dependency attribute.
Furthermore, the first declaration of a function shall specify the carries_­dependency attribute for a parameter if any declaration of that function specifies the carries_­dependency attribute for that parameter.
If a function or one of its parameters is declared with the carries_­dependency attribute in its first declaration in one translation unit and the same function or one of its parameters is declared without the carries_­dependency attribute in its first declaration in another translation unit, the program is ill-formed, no diagnostic required.
[Note
:
The carries_­dependency attribute does not change the meaning of the program, but may result in generation of more efficient code.
end note
]
[Example
:
/* Translation unit A. */

struct foo { int* a; int* b; };
std::atomic<struct foo *> foo_head[10];
int foo_array[10][10];

[[carries_dependency]] struct foo* f(int i) {
  return foo_head[i].load(memory_order_consume);
}

int g(int* x, int* y [[carries_dependency]]) {
  return kill_dependency(foo_array[*x][*y]);
}

/* Translation unit B. */

[[carries_dependency]] struct foo* f(int i);
int g(int* x, int* y [[carries_dependency]]);

int c = 3;

void h(int i) {
  struct foo* p;

  p = f(i);
  do_something_with(g(&c, p->a));
  do_something_with(g(p->a, &c));
}
The carries_­dependency attribute on function f means that the return value carries a dependency out of f, so that the implementation need not constrain ordering upon return from f.
Implementations of f and its caller may choose to preserve dependencies instead of emitting hardware memory ordering instructions (a.
k.
a.
fences).
Function g's second parameter has a carries_­dependency attribute, but its first parameter does not.
Therefore, function h's first call to g carries a dependency into g, but its second call does not.
The implementation might need to insert a fence prior to the second call to g.
end example
]

10.6.4 Deprecated attribute [dcl.attr.deprecated]

The attribute-token deprecated can be used to mark names and entities whose use is still allowed, but is discouraged for some reason.
[Note
:
In particular, deprecated is appropriate for names and entities that are deemed obsolescent or unsafe.
end note
]
It shall appear at most once in each attribute-list.
An attribute-argument-clause may be present and, if present, it shall have the form:
( string-literal )
[Note
:
The string-literal in the attribute-argument-clause could be used to explain the rationale for deprecation and/or to suggest a replacing entity.
end note
]
The attribute may be applied to the declaration of a class, a typedef-name, a variable, a non-static data member, a function, a namespace, an enumeration, an enumerator, or a template specialization.
A name or entity declared without the deprecated attribute can later be redeclared with the attribute and vice-versa.
[Note
:
Thus, an entity initially declared without the attribute can be marked as deprecated by a subsequent redeclaration.
However, after an entity is marked as deprecated, later redeclarations do not un-deprecate the entity.
end note
]
Redeclarations using different forms of the attribute (with or without the attribute-argument-clause or with different attribute-argument-clauses) are allowed.
[Note
:
Implementations may use the deprecated attribute to produce a diagnostic message in case the program refers to a name or entity other than to declare it, after a declaration that specifies the attribute.
The diagnostic message may include the text provided within the attribute-argument-clause of any deprecated attribute applied to the name or entity.
end note
]

10.6.5 Fallthrough attribute [dcl.attr.fallthrough]

The attribute-token fallthrough may be applied to a null statement ([stmt.expr]); such a statement is a fallthrough statement.
The attribute-token fallthrough shall appear at most once in each attribute-list and no attribute-argument-clause shall be present.
A fallthrough statement may only appear within an enclosing switch statement ([stmt.switch]).
The next statement that would be executed after a fallthrough statement shall be a labeled statement whose label is a case label or default label for the same switch statement.
The program is ill-formed if there is no such statement.
[Note
:
The use of a fallthrough statement is intended to suppress a warning that an implementation might otherwise issue for a case or default label that is reachable from another case or default label along some path of execution.
Implementations are encouraged to issue a warning if a fallthrough statement is not dynamically reachable.
end note
]
[Example
:
void f(int n) {
  void g(), h(), i();
  switch (n) {
  case 1:
  case 2:
    g();
    [[fallthrough]];
  case 3:                       // warning on fallthrough discouraged
    h();
  case 4:                       // implementation may warn on fallthrough
    i();
    [[fallthrough]];            // ill-formed
  }
}
end example
]

10.6.6 Maybe unused attribute [dcl.attr.unused]

The attribute-token maybe_­unused indicates that a name or entity is possibly intentionally unused.
It shall appear at most once in each attribute-list and no attribute-argument-clause shall be present.
The attribute may be applied to the declaration of a class, a typedef-name, a variable, a non-static data member, a function, an enumeration, or an enumerator.
[Note
:
For an entity marked maybe_­unused, implementations are encouraged not to emit a warning that the entity is unused, or that the entity is used despite the presence of the attribute.
end note
]
A name or entity declared without the maybe_­unused attribute can later be redeclared with the attribute and vice versa.
An entity is considered marked after the first declaration that marks it.
[Example
:
[[maybe_unused]] void f([[maybe_unused]] bool thing1,
                        [[maybe_unused]] bool thing2) {
  [[maybe_unused]] bool b = thing1 && thing2;
  assert(b);
}
Implementations are encouraged not to warn that b is unused, whether or not NDEBUG is defined.
end example
]

10.6.7 Nodiscard attribute [dcl.attr.nodiscard]

The attribute-token nodiscard may be applied to the declarator-id in a function declaration or to the declaration of a class or enumeration.
It shall appear at most once in each attribute-list and no attribute-argument-clause shall be present.
[Note
:
A nodiscard call is a function call expression that calls a function previously declared nodiscard, or whose return type is a possibly cv-qualified class or enumeration type marked nodiscard.
Appearance of a nodiscard call as a potentially-evaluated discarded-value expression (Clause [expr]) is discouraged unless explicitly cast to void.
Implementations are encouraged to issue a warning in such cases.
This is typically because discarding the return value of a nodiscard call has surprising consequences.
end note
]
[Example
:
struct [[nodiscard]] error_info { /* ... */ };
error_info enable_missile_safety_mode();
void launch_missiles();
void test_missiles() {
  enable_missile_safety_mode(); // warning encouraged
  launch_missiles();
}
error_info &foo();
void f() { foo(); }             // warning not encouraged: not a nodiscard call, because neither
                                // the (reference) return type nor the function is declared nodiscard
end example
]

10.6.8 Noreturn attribute [dcl.attr.noreturn]

The attribute-token noreturn specifies that a function does not return.
It shall appear at most once in each attribute-list and no attribute-argument-clause shall be present.
The attribute may be applied to the declarator-id in a function declaration.
The first declaration of a function shall specify the noreturn attribute if any declaration of that function specifies the noreturn attribute.
If a function is declared with the noreturn attribute in one translation unit and the same function is declared without the noreturn attribute in another translation unit, the program is ill-formed, no diagnostic required.
If a function f is called where f was previously declared with the noreturn attribute and f eventually returns, the behavior is undefined.
[Note
:
The function may terminate by throwing an exception.
end note
]
[Note
:
Implementations are encouraged to issue a warning if a function marked [[noreturn]] might return.
end note
]
[Example
:
[[ noreturn ]] void f() {
  throw "error";                // OK
}

[[ noreturn ]] void q(int i) {  // behavior is undefined if called with an argument <= 0
  if (i > 0)
    throw "positive";
}
end example
]

11 Declarators [dcl.decl]

A declarator declares a single variable, function, or type, within a declaration.
The init-declarator-list appearing in a declaration is a comma-separated sequence of declarators, each of which can have an initializer.
The three components of a simple-declaration are the attributes ([dcl.attr]), the specifiers (decl-specifier-seq; [dcl.spec]) and the declarators (init-declarator-list).
The specifiers indicate the type, storage class or other properties of the entities being declared.
The declarators specify the names of these entities and (optionally) modify the type of the specifiers with operators such as * (pointer to) and () (function returning).
Initial values can also be specified in a declarator; initializers are discussed in [dcl.init] and [class.init].
Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.
[Note
:
A declaration with several declarators is usually equivalent to the corresponding sequence of declarations each with a single declarator.
That is
T D1, D2, ... Dn;
is usually equivalent to
T D1; T D2; ... T Dn;
where T is a decl-specifier-seq and each Di is an init-declarator.
One exception is when a name introduced by one of the declarators hides a type name used by the decl-specifiers, so that when the same decl-specifiers are used in a subsequent declaration, they do not have the same meaning, as in
struct S { ... };
S S, T;                 // declare two instances of struct S
which is not equivalent to
struct S { ... };
S S;
S T;                    // error
Another exception is when T is auto ([dcl.spec.auto]), for example:
auto i = 1, j = 2.0;    // error: deduced types for i and j do not match
as opposed to
auto i = 1;             // OK: i deduced to have type int
auto j = 2.0;           // OK: j deduced to have type double
end note
]

11.1 Type names [dcl.name]

To specify type conversions explicitly, and as an argument of sizeof, alignof, new, or typeid, the name of a type shall be specified.
This can be done with a type-id, which is syntactically a declaration for a variable or function of that type that omits the name of the entity.
The named type is then the same as the type of the hypothetical identifier.
[Example
:
int                 // int i
int *               // int *pi
int *[3]            // int *p[3]
int (*)[3]          // int (*p3i)[3]
int *()             // int *f()
int (*)(double)     // int (*pf)(double)
name respectively the types “int”, “pointer to int”, “array of 3 pointers to int”, “pointer to array of 3 int”, “function of (no parameters) returning pointer to int”, and “pointer to a function of (double) returning int.
end example
]
A type can also be named (often more easily) by using a typedef ([dcl.typedef]).

11.2 Ambiguity resolution [dcl.ambig.res]

The ambiguity arising from the similarity between a function-style cast and a declaration mentioned in [stmt.ambig] can also occur in the context of a declaration.
In that context, the choice is between a function declaration with a redundant set of parentheses around a parameter name and an object declaration with a function-style cast as the initializer.
Just as for the ambiguities mentioned in [stmt.ambig], the resolution is to consider any construct that could possibly be a declaration a declaration.
[Note
:
A declaration can be explicitly disambiguated by adding parentheses around the argument.
The ambiguity can be avoided by use of copy-initialization or list-initialization syntax, or by use of a non-function-style cast.
end note
]
[Example
:
struct S {
  S(int);
};

void foo(double a) {
  S w(int(a));                  // function declaration
  S x(int());                   // function declaration
  S y((int(a)));                // object declaration
  S y((int)a);                  // object declaration
  S z = int(a);                 // object declaration
}
end example
]
An ambiguity can arise from the similarity between a function-style cast and a type-id.
The resolution is that any construct that could possibly be a type-id in its syntactic context shall be considered a type-id.
[Example
:
template <class T> struct X {};
template <int N> struct Y {};
X<int()> a;                     // type-id
X<int(1)> b;                    // expression (ill-formed)
Y<int()> c;                     // type-id (ill-formed)
Y<int(1)> d;                    // expression

void foo(signed char a) {
  sizeof(int());                // type-id (ill-formed)
  sizeof(int(a));               // expression
  sizeof(int(unsigned(a)));     // type-id (ill-formed)

  (int())+1;                    // type-id (ill-formed)
  (int(a))+1;                   // expression
  (int(unsigned(a)))+1;         // type-id (ill-formed)
}
end example
]
Another ambiguity arises in a parameter-declaration-clause when a type-name is nested in parentheses.
In this case, the choice is between the declaration of a parameter of type pointer to function and the declaration of a parameter with redundant parentheses around the declarator-id.
The resolution is to consider the type-name as a simple-type-specifier rather than a declarator-id.
[Example
:
class C { };
void f(int(C)) { }              // void f(int(*fp)(C c)) { }
                                // not: void f(int C) { }

int g(C);

void foo() {
  f(1);                         // error: cannot convert 1 to function pointer
  f(g);                         // OK
}
For another example,
class C { };
void h(int *(C[10]));           // void h(int *(*_­fp)(C _­parm[10]));
                                // not: void h(int *C[10]);
end example
]

11.3 Meaning of declarators [dcl.meaning]

A declarator contains exactly one declarator-id; it names the identifier that is declared.
An unqualified-id occurring in a declarator-id shall be a simple identifier except for the declaration of some special functions ([class.ctor], [class.conv], [class.dtor], [over.oper]) and for the declaration of template specializations or partial specializations ([temp.spec]).
When the declarator-id is qualified, the declaration shall refer to a previously declared member of the class or namespace to which the qualifier refers (or, in the case of a namespace, of an element of the inline namespace set of that namespace ([namespace.def])) or to a specialization thereof; the member shall not merely have been introduced by a using-declaration in the scope of the class or namespace nominated by the nested-name-specifier of the declarator-id.
The nested-name-specifier of a qualified declarator-id shall not begin with a decltype-specifier.
[Note
:
If the qualifier is the global ​::​ scope resolution operator, the declarator-id refers to a name declared in the global namespace scope.
end note
]
The optional attribute-specifier-seq following a declarator-id appertains to the entity that is declared.
A static, thread_­local, extern, mutable, friend, inline, virtual, constexpr, explicit, or typedef specifier applies directly to each declarator-id in an init-declarator-list or member-declarator-list; the type specified for each declarator-id depends on both the decl-specifier-seq and its declarator.
Thus, a declaration of a particular identifier has the form
T D
where T is of the form attribute-specifier-seq decl-specifier-seq and D is a declarator.
Following is a recursive procedure for determining the type specified for the contained declarator-id by such a declaration.
First, the decl-specifier-seq determines a type.
In a declaration
T D
the decl-specifier-seq T determines the type T.
[Example
:
In the declaration
int unsigned i;
the type specifiers int unsigned determine the type “unsigned int” ([dcl.type.simple]).
end example
]
In a declaration attribute-specifier-seq T D where D is an unadorned identifier the type of this identifier is “T.
In a declaration T D where D has the form
( D1 )
the type of the contained declarator-id is the same as that of the contained declarator-id in the declaration
T D1
Parentheses do not alter the type of the embedded declarator-id, but they can alter the binding of complex declarators.

11.3.1 Pointers [dcl.ptr]

In a declaration T D where D has the form
* attribute-specifier-seq cv-qualifier-seq D1
and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T”, then the type of the identifier of D is “derived-declarator-type-list cv-qualifier-seq pointer to T.
The cv-qualifiers apply to the pointer and not to the object pointed to.
Similarly, the optional attribute-specifier-seq appertains to the pointer and not to the object pointed to.
[Example
:
The declarations
const int ci = 10, *pc = &ci, *const cpc = pc, **ppc;
int i, *p, *const cp = &i;
declare ci, a constant integer; pc, a pointer to a constant integer; cpc, a constant pointer to a constant integer; ppc, a pointer to a pointer to a constant integer; i, an integer; p, a pointer to integer; and cp, a constant pointer to integer.
The value of ci, cpc, and cp cannot be changed after initialization.
The value of pc can be changed, and so can the object pointed to by cp.
Examples of some correct operations are
i = ci;
*cp = ci;
pc++;
pc = cpc;
pc = p;
ppc = &pc;
Examples of ill-formed operations are
ci = 1;             // error
ci++;               // error
*pc = 2;            // error
cp = &ci;           // error
cpc++;              // error
p = pc;             // error
ppc = &p;           // error
Each is unacceptable because it would either change the value of an object declared const or allow it to be changed through a cv-unqualified pointer later, for example:
*ppc = &ci;         // OK, but would make p point to ci because of previous error
*p = 5;             // clobber ci
end example
]
[Note
:
Forming a pointer to reference type is ill-formed; see [dcl.ref].
Forming a function pointer type is ill-formed if the function type has cv-qualifiers or a ref-qualifier; see [dcl.fct].
Since the address of a bit-field ([class.bit]) cannot be taken, a pointer can never point to a bit-field.
end note
]

11.3.2 References [dcl.ref]

In a declaration T D where D has either of the forms
& attribute-specifier-seq D1
&& attribute-specifier-seq D1
and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T”, then the type of the identifier of D is “derived-declarator-type-list reference to T.
The optional attribute-specifier-seq appertains to the reference type.
Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name ([dcl.typedef], [temp.param]) or decltype-specifier, in which case the cv-qualifiers are ignored.
[Example
:
typedef int& A;
const A aref = 3;   // ill-formed; lvalue reference to non-const initialized with rvalue
The type of aref is “lvalue reference to int”, not “lvalue reference to const int.
end example
]
[Note
:
A reference can be thought of as a name of an object.
end note
]
A declarator that specifies the type “reference to cv void” is ill-formed.
A reference type that is declared using & is called an lvalue reference, and a reference type that is declared using && is called an rvalue reference.
Lvalue references and rvalue references are distinct types.
Except where explicitly noted, they are semantically equivalent and commonly referred to as references.
[Example
:
void f(double& a) { a += 3.14; }
// ...
double d = 0;
f(d);
declares a to be a reference parameter of f so the call f(d) will add 3.14 to d.
int v[20];
// ...
int& g(int i) { return v[i]; }
// ...
g(3) = 7;
declares the function g() to return a reference to an integer so g(3)=7 will assign 7 to the fourth element of the array v.
For another example,
struct link {
  link* next;
};

link* first;

void h(link*& p) {  // p is a reference to pointer
  p->next = first;
  first = p;
  p = 0;
}

void k() {
   link* q = new link;
   h(q);
}
declares p to be a reference to a pointer to link so h(q) will leave q with the value zero.
end example
]
It is unspecified whether or not a reference requires storage ([basic.stc]).
There shall be no references to references, no arrays of references, and no pointers to references.
The declaration of a reference shall contain an initializer ([dcl.init.ref]) except when the declaration contains an explicit extern specifier ([dcl.stc]), is a class member ([class.mem]) declaration within a class definition, or is the declaration of a parameter or a return type ([dcl.fct]); see [basic.def].
A reference shall be initialized to refer to a valid object or function.
[Note
:
In particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by indirection through a null pointer, which causes undefined behavior.
As described in [class.bit], a reference cannot be bound directly to a bit-field.
end note
]
If a typedef-name ([dcl.typedef], [temp.param]) or a decltype-specifier denotes a type TR that is a reference to a type T, an attempt to create the type “lvalue reference to cv TR” creates the type “lvalue reference to T”, while an attempt to create the type “rvalue reference to cv TR” creates the type TR.
[Note
:
This rule is known as reference collapsing.
end note
]
[Example
:
int i;
typedef int& LRI;
typedef int&& RRI;

LRI& r1 = i;                    // r1 has the type int&
const LRI& r2 = i;              // r2 has the type int&
const LRI&& r3 = i;             // r3 has the type int&

RRI& r4 = i;                    // r4 has the type int&
RRI&& r5 = 5;                   // r5 has the type int&&

decltype(r2)& r6 = i;           // r6 has the type int&
decltype(r2)&& r7 = i;          // r7 has the type int&
end example
]
[Note
:
Forming a reference to function type is ill-formed if the function type has cv-qualifiers or a ref-qualifier; see [dcl.fct].
end note
]

11.3.3 Pointers to members [dcl.mptr]

In a declaration T D where D has the form
nested-name-specifier * attribute-specifier-seq cv-qualifier-seq D1
and the nested-name-specifier denotes a class, and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T”, then the type of the identifier of D is “derived-declarator-type-list cv-qualifier-seq pointer to member of class nested-name-specifier of type T.
The optional attribute-specifier-seq appertains to the pointer-to-member.
[Example
:
struct X {
  void f(int);
  int a;
};
struct Y;

int X::* pmi = &X::a;
void (X::* pmf)(int) = &X::f;
double X::* pmd;
char Y::* pmc;
declares pmi, pmf, pmd and pmc to be a pointer to a member of X of type int, a pointer to a member of X of type void(int), a pointer to a member of X of type double and a pointer to a member of Y of type char respectively.
The declaration of pmd is well-formed even though X has no members of type double.
Similarly, the declaration of pmc is well-formed even though Y is an incomplete type.
pmi and pmf can be used like this:
X obj;
// ...
obj.*pmi = 7;       // assign 7 to an integer member of obj
(obj.*pmf)(7);      // call a function member of obj with the argument 7
end example
]
A pointer to member shall not point to a static member of a class ([class.static]), a member with reference type, or “cv void.
[Note
:
The type “pointer to member” is distinct from the type “pointer”, that is, a pointer to member is declared only by the pointer to member declarator syntax, and never by the pointer declarator syntax.
There is no “reference-to-member” type in C++.
end note
]

11.3.4 Arrays [dcl.array]

In a declaration T D where D has the form
D1 [ constant-expression ] attribute-specifier-seq
and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T”, then the type of the identifier of D is an array type; if the type of the identifier of D contains the auto type-specifier, the program is ill-formed.
T is called the array element type; this type shall not be a reference type, cv void, a function type or an abstract class type.
If the constant-expression is present, it shall be a converted constant expression of type std​::​size_­t and its value shall be greater than zero.
The constant expression specifies the bound of (number of elements in) the array.
If the value of the constant expression is N, the array has N elements numbered 0 to N-1, and the type of the identifier of D is “derived-declarator-type-list array of N T.
An object of array type contains a contiguously allocated non-empty set of N subobjects of type T.
Except as noted below, if the constant expression is omitted, the type of the identifier of D is “derived-declarator-type-list array of unknown bound of T”, an incomplete object type.
The type “derived-declarator-type-list array of N T” is a different type from the type “derived-declarator-type-list array of unknown bound of T”, see [basic.types].
Any type of the form “cv-qualifier-seq array of N T” is adjusted to “array of N cv-qualifier-seq T”, and similarly for “array of unknown bound of T.
The optional attribute-specifier-seq appertains to the array.
[Example
:
typedef int A[5], AA[2][3];
typedef const A CA;             // type is “array of 5 const inttypedef const AA CAA;           // type is “array of 2 array of 3 const int
end example
]
[Note
:
An “array of N cv-qualifier-seq T” has cv-qualified type; see [basic.type.qualifier].
end note
]
An array can be constructed from one of the fundamental types (except void), from a pointer, from a pointer to member, from a class, from an enumeration type, or from another array.
When several “array of” specifications are adjacent, a multidimensional array type is created; only the first of the constant expressions that specify the bounds of the arrays may be omitted.
In addition to declarations in which an incomplete object type is allowed, an array bound may be omitted in some cases in the declaration of a function parameter ([dcl.fct]).
An array bound may also be omitted when the declarator is followed by an initializer or when a declarator for a static data member is followed by a brace-or-equal-initializer ([class.mem]).
In both cases the bound is calculated from the number of initial elements (say, N) supplied ([dcl.init.aggr]), and the type of the identifier of D is “array of N T.
Furthermore, if there is a preceding declaration of the entity in the same scope in which the bound was specified, an omitted array bound is taken to be the same as in that earlier declaration, and similarly for the definition of a static data member of a class.
[Example
:
float fa[17], *afp[17];
declares an array of float numbers and an array of pointers to float numbers.
For another example,
static int x3d[3][5][7];
declares a static three-dimensional array of integers, with rank .
In complete detail, x3d is an array of three items; each item is an array of five arrays; each of the latter arrays is an array of seven integers.
Any of the expressions x3d, x3d[i], x3d[i][j], x3d[i][j][k] can reasonably appear in an expression.
Finally,
extern int x[10];
struct S {
  static int y[10];
};

int x[];                // OK: bound is 10
int S::y[];             // OK: bound is 10

void f() {
  extern int x[];
  int i = sizeof(x);    // error: incomplete object type
}
end example
]
[Note
:
Conversions affecting expressions of array type are described in [conv.array].
Objects of array types cannot be modified, see [basic.lval].
end note
]
[Note
:
Except where it has been declared for a class ([over.sub]), the subscript operator [] is interpreted in such a way that E1[E2] is identical to *((E1)+(E2)) ([expr.sub]).
Because of the conversion rules that apply to +, if E1 is an array and E2 an integer, then E1[E2] refers to the E2-th member of E1.
Therefore, despite its asymmetric appearance, subscripting is a commutative operation.
end note
]
[Note
:
A consistent rule is followed for multidimensional arrays.
If E is an n-dimensional array of rank , then E appearing in an expression that is subject to the array-to-pointer conversion ([conv.array]) is converted to a pointer to an -dimensional array with rank .
If the * operator, either explicitly or implicitly as a result of subscripting, is applied to this pointer, the result is the pointed-to -dimensional array, which itself is immediately converted into a pointer.
[Example
:
Consider
int x[3][5];
Here x is a array of integers.
When x appears in an expression, it is converted to a pointer to (the first of three) five-membered arrays of integers.
In the expression x[i] which is equivalent to *(x+i), x is first converted to a pointer as described; then x+i is converted to the type of x, which involves multiplying i by the length of the object to which the pointer points, namely five integer objects.
The results are added and indirection applied to yield an array (of five integers), which in turn is converted to a pointer to the first of the integers.
If there is another subscript the same argument applies again; this time the result is an integer.
end example
]
end note
]
[Note
:
It follows from all this that arrays in C++ are stored row-wise (last subscript varies fastest) and that the first subscript in the declaration helps determine the amount of storage consumed by an array but plays no other part in subscript calculations.
end note
]

11.3.5 Functions [dcl.fct]

In a declaration T D where D has the form
D1 ( parameter-declaration-clause ) cv-qualifier-seq
ref-qualifier noexcept-specifier attribute-specifier-seq
and the type of the contained declarator-id in the declaration T D1 is “derived-declarator-type-list T”, the type of the declarator-id in D is “derived-declarator-type-list noexcept function of (parameter-declaration-clause) cv-qualifier-seq ref-qualifier returning T”, where the optional noexcept is present if and only if the exception specification ([except.spec]) is non-throwing.
The optional attribute-specifier-seq appertains to the function type.
In a declaration T D where D has the form
D1 ( parameter-declaration-clause ) cv-qualifier-seq
ref-qualifier noexcept-specifier attribute-specifier-seq trailing-return-type
and the type of the contained declarator-id in the declaration T D1 is “derived-declarator-type-list T”, T shall be the single type-specifier auto.
The type of the declarator-id in D is “derived-declarator-type-list noexcept function of (parameter-declaration-clause) cv-qualifier-seq ref-qualifier returning U”, where U is the type specified by the trailing-return-type, and where the optional noexcept is present if and only if the exception specification is non-throwing.
The optional attribute-specifier-seq appertains to the function type.
The parameter-declaration-clause determines the arguments that can be specified, and their processing, when the function is called.
[Note
:
The parameter-declaration-clause is used to convert the arguments specified on the function call; see [expr.call].
end note
]
If the parameter-declaration-clause is empty, the function takes no arguments.
A parameter list consisting of a single unnamed parameter of non-dependent type void is equivalent to an empty parameter list.
Except for this special case, a parameter shall not have type cv void.
If the parameter-declaration-clause terminates with an ellipsis or a function parameter pack ([temp.variadic]), the number of arguments shall be equal to or greater than the number of parameters that do not have a default argument and are not function parameter packs.
Where syntactically correct and where “...” is not part of an abstract-declarator, “, ...” is synonymous with “....
[Example
:
The declaration
int printf(const char*, ...);
declares a function that can be called with varying numbers and types of arguments.
printf("hello world");
printf("a=%d b=%d", a, b);
However, the first argument must be of a type that can be converted to a const char*
end example
]
[Note
:
The standard header <cstdarg> contains a mechanism for accessing arguments passed using the ellipsis (see [expr.call] and [support.runtime]).
end note
]
A single name can be used for several different functions in a single scope; this is function overloading (Clause [over]).
All declarations for a function shall agree exactly in both the return type and the parameter-type-list.
The type of a function is determined using the following rules.
The type of each parameter (including function parameter packs) is determined from its own decl-specifier-seq and declarator.
After determining the type of each parameter, any parameter of type “array of T” or of function type T is adjusted to be “pointer to T.
After producing the list of parameter types, any top-level cv-qualifiers modifying a parameter type are deleted when forming the function type.
The resulting list of transformed parameter types and the presence or absence of the ellipsis or a function parameter pack is the function's parameter-type-list.
[Note
:
This transformation does not affect the types of the parameters.
For example, int(*)(const int p, decltype(p)*) and int(*)(int, const int*) are identical types.
end note
]
A function type with a cv-qualifier-seq or a ref-qualifier (including a type named by typedef-name ([dcl.typedef], [temp.param])) shall appear only as:
[Example
:
typedef int FIC(int) const;
FIC f;              // ill-formed: does not declare a member function
struct S {
  FIC f;            // OK
};
FIC S::*pm = &S::f; // OK
end example
]
The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type.
In the latter case, the cv-qualifiers are ignored.
[Note
:
A function type that has a cv-qualifier-seq is not a cv-qualified type; there are no cv-qualified function types.
end note
]
[Example
:
typedef void F();
struct S {
  const F f;        // OK: equivalent to: void f();
};
end example
]
The return type, the parameter-type-list, the ref-qualifier, the cv-qualifier-seq, and the exception specification, but not the default arguments ([dcl.fct.default]), are part of the function type.
[Note
:
Function types are checked during the assignments and initializations of pointers to functions, references to functions, and pointers to member functions.
end note
]
[Example
:
The declaration
int fseek(FILE*, long, int);
declares a function taking three arguments of the specified types, and returning int ([dcl.type]).
end example
]
Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things.
There shall be no arrays of functions, although there can be arrays of pointers to functions.
Types shall not be defined in return or parameter types.
The type of a parameter or the return type for a function definition shall not be an incomplete (possibly cv-qualified) class type in the context of the function definition unless the function is deleted ([dcl.fct.def.delete]).
A typedef of function type may be used to declare a function but shall not be used to define a function ([dcl.fct.def]).
[Example
:
typedef void F();
F  fv;              // OK: equivalent to void fv();
F  fv { }           // ill-formed
void fv() { }       // OK: definition of fv
end example
]
An identifier can optionally be provided as a parameter name; if present in a function definition ([dcl.fct.def]), it names a parameter.
[Note
:
In particular, parameter names are also optional in function definitions and names used for a parameter in different declarations and the definition of a function need not be the same.
If a parameter name is present in a function declaration that is not a definition, it cannot be used outside of its function declarator because that is the extent of its potential scope ([basic.scope.proto]).
end note
]
[Example
:
The declaration
int i,
    *pi,
    f(),
    *fpi(int),
    (*pif)(const char*, const char*),
    (*fpif(int))(int);
declares an integer i, a pointer pi to an integer, a function f taking no arguments and returning an integer, a function fpi taking an integer argument and returning a pointer to an integer, a pointer pif to a function which takes two pointers to constant characters and returns an integer, a function fpif taking an integer argument and returning a pointer to a function that takes an integer argument and returns an integer.
It is especially useful to compare fpi and pif.
The binding of *fpi(int) is *(fpi(int)), so the declaration suggests, and the same construction in an expression requires, the calling of a function fpi, and then using indirection through the (pointer) result to yield an integer.
In the declarator (*pif)(const char*, const char*), the extra parentheses are necessary to indicate that indirection through a pointer to a function yields a function, which is then called.
end example
]
[Note
:
Typedefs and trailing-return-types are sometimes convenient when the return type of a function is complex.
For example, the function fpif above could have been declared
typedef int  IFUNC(int);
IFUNC*  fpif(int);
or
auto fpif(int)->int(*)(int);
A trailing-return-type is most useful for a type that would be more complicated to specify before the declarator-id:
template <class T, class U> auto add(T t, U u) -> decltype(t + u);
rather than
template <class T, class U> decltype((*(T*)0) + (*(U*)0)) add(T t, U u);
end note
]
A non-template function is a function that is not a function template specialization.
[Note
:
A function template is not a function.
end note
]
A declarator-id or abstract-declarator containing an ellipsis shall only be used in a parameter-declaration.
Such a parameter-declaration is a parameter pack ([temp.variadic]).
When it is part of a parameter-declaration-clause, the parameter pack is a function parameter pack ([temp.variadic]).
[Note
:
Otherwise, the parameter-declaration is part of a template-parameter-list and the parameter pack is a template parameter pack; see [temp.param].
end note
]
A function parameter pack is a pack expansion ([temp.variadic]).
[Example
:
template<typename... T> void f(T (* ...t)(int, int));

int add(int, int);
float subtract(int, int);

void g() {
  f(add, subtract);
}
end example
]
There is a syntactic ambiguity when an ellipsis occurs at the end of a parameter-declaration-clause without a preceding comma.
In this case, the ellipsis is parsed as part of the abstract-declarator if the type of the parameter either names a template parameter pack that has not been expanded or contains auto; otherwise, it is parsed as part of the parameter-declaration-clause.101
As indicated by syntax, cv-qualifiers are a significant component in function return types.
One can explicitly disambiguate the parse either by introducing a comma (so the ellipsis will be parsed as part of the parameter-declaration-clause) or by introducing a name for the parameter (so the ellipsis will be parsed as part of the declarator-id).

11.3.6 Default arguments [dcl.fct.default]

If an initializer-clause is specified in a parameter-declaration this initializer-clause is used as a default argument.
Default arguments will be used in calls where trailing arguments are missing.
[Example
:
The declaration
void point(int = 3, int = 4);
declares a function that can be called with zero, one, or two arguments of type int.
It can be called in any of these ways:
point(1,2);  point(1);  point();
The last two calls are equivalent to point(1,4) and point(3,4), respectively.
end example
]
A default argument shall be specified only in the parameter-declaration-clause of a function declaration or lambda-declarator or in a template-parameter; in the latter case, the initializer-clause shall be an assignment-expression.
A default argument shall not be specified for a parameter pack.
If it is specified in a parameter-declaration-clause, it shall not occur within a declarator or abstract-declarator of a parameter-declaration.102
For non-template functions, default arguments can be added in later declarations of a function in the same scope.
Declarations in different scopes have completely distinct sets of default arguments.
That is, declarations in inner scopes do not acquire default arguments from declarations in outer scopes, and vice versa.
In a given function declaration, each parameter subsequent to a parameter with a default argument shall have a default argument supplied in this or a previous declaration or shall be a function parameter pack.
A default argument shall not be redefined by a later declaration (not even to the same value).
[Example
:
void g(int = 0, ...);           // OK, ellipsis is not a parameter so it can follow
                                // a parameter with a default argument
void f(int, int);
void f(int, int = 7);
void h() {
  f(3);                         // OK, calls f(3, 7)
  void f(int = 1, int);         // error: does not use default from surrounding scope
}
void m() {
  void f(int, int);             // has no defaults
  f(4);                         // error: wrong number of arguments
  void f(int, int = 5);         // OK
  f(4);                         // OK, calls f(4, 5);
  void f(int, int = 5);         // error: cannot redefine, even to same value
}
void n() {
  f(6);                         // OK, calls f(6, 7)
}
end example
]
For a given inline function defined in different translation units, the accumulated sets of default arguments at the end of the translation units shall be the same; see [basic.def.odr].
If a friend declaration specifies a default argument expression, that declaration shall be a definition and shall be the only declaration of the function or function template in the translation unit.
The default argument has the same semantic constraints as the initializer in a declaration of a variable of the parameter type, using the copy-initialization semantics ([dcl.init]).
The names in the default argument are bound, and the semantic constraints are checked, at the point where the default argument appears.
Name lookup and checking of semantic constraints for default arguments in function templates and in member functions of class templates are performed as described in [temp.inst].
[Example
:
In the following code, g will be called with the value f(2):
int a = 1;
int f(int);
int g(int x = f(a));            // default argument: f(​::​a)

void h() {
  a = 2;
  {
  int a = 3;
  g();                          // g(f(​::​a))
  }
}
end example
]
[Note
:
In member function declarations, names in default arguments are looked up as described in [basic.lookup.unqual].
Access checking applies to names in default arguments as described in Clause [class.access].
end note
]
Except for member functions of class templates, the default arguments in a member function definition that appears outside of the class definition are added to the set of default arguments provided by the member function declaration in the class definition; the program is ill-formed if a default constructor ([class.ctor]), copy or move constructor, or copy or move assignment operator ([class.copy]) is so declared.
Default arguments for a member function of a class template shall be specified on the initial declaration of the member function within the class template.
[Example
:
class C {
  void f(int i = 3);
  void g(int i, int j = 99);
};

void C::f(int i = 3) {}         // error: default argument already specified in class scope
void C::g(int i = 88, int j) {} // in this translation unit, C​::​g can be called with no argument
end example
]
A local variable shall not appear as a potentially-evaluated expression in a default argument.
[Example
:
void f() {
  int i;
  extern void g(int x = i);         // error
  extern void h(int x = sizeof(i)); // OK
  // ...
}
end example
]
[Note
:
The keyword this may not appear in a default argument of a member function; see [expr.prim.this].
[Example
:
class A {
  void f(A* p = this) { }           // error
};
end example
]
end note
]
A default argument is evaluated each time the function is called with no argument for the corresponding parameter.
A parameter shall not appear as a potentially-evaluated expression in a default argument.
Parameters of a function declared before a default argument are in scope and can hide namespace and class member names.
[Example
:
int a;
int f(int a, int b = a);            // error: parameter a used as default argument
typedef int I;
int g(float I, int b = I(2));       // error: parameter I found
int h(int a, int b = sizeof(a));    // OK, unevaluated operand
end example
]
A non-static member shall not appear in a default argument unless it appears as the id-expression of a class member access expression ([expr.ref]) or unless it is used to form a pointer to member ([expr.unary.op]).
[Example
:
The declaration of X​::​mem1() in the following example is ill-formed because no object is supplied for the non-static member X​::​a used as an initializer.
int b;
class X {
  int a;
  int mem1(int i = a);              // error: non-static member a used as default argument
  int mem2(int i = b);              // OK;  use X​::​b
  static int b;
};
The declaration of X​::​mem2() is meaningful, however, since no object is needed to access the static member X​::​b.
Classes, objects, and members are described in Clause [class].
end example
]
A default argument is not part of the type of a function.
[Example
:
int f(int = 0);

void h() {
  int j = f(1);
  int k = f();                      // OK, means f(0)
}

int (*p1)(int) = &f;
int (*p2)() = &f;                   // error: type mismatch
end example
]
When a declaration of a function is introduced by way of a using-declaration, any default argument information associated with the declaration is made known as well.
If the function is redeclared thereafter in the namespace with additional default arguments, the additional arguments are also known at any point following the redeclaration where the using-declaration is in scope.
A virtual function call ([class.virtual]) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object.
An overriding function in a derived class does not acquire default arguments from the function it overrides.
[Example
:
struct A {
  virtual void f(int a = 7);
};
struct B : public A {
  void f(int a);
};
void m() {
  B* pb = new B;
  A* pa = pb;
  pa->f();          // OK, calls pa->B​::​f(7)
  pb->f();          // error: wrong number of arguments for B​::​f()
}
end example
]
This means that default arguments cannot appear, for example, in declarations of pointers to functions, references to functions, or typedef declarations.

11.4 Function definitions [dcl.fct.def]

11.4.1 In general [dcl.fct.def.general]

Function definitions have the form
function-definition:
	attribute-specifier-seq decl-specifier-seq declarator virt-specifier-seq function-body
function-body:
	ctor-initializer compound-statement
	function-try-block
	= default ;
	= delete ;
Any informal reference to the body of a function should be interpreted as a reference to the non-terminal function-body.
The optional attribute-specifier-seq in a function-definition appertains to the function.
In a function-definition, either void declarator ; or declarator ; shall be a well-formed function declaration as described in [dcl.fct].
A function shall be defined only in namespace or class scope.
[Example
:
A simple example of a complete function definition is
int max(int a, int b, int c) {
  int m = (a > b) ? a : b;
  return (m > c) ? m : c;
}
Here int is the decl-specifier-seq; max(int a, int b, int c) is the declarator; { /* ... */ } is the function-body.
end example
]
A ctor-initializer is used only in a constructor; see [class.ctor] and [class.init].
[Note
:
A cv-qualifier-seq affects the type of this in the body of a member function; see [dcl.ref].
end note
]
[Note
:
Unused parameters need not be named.
For example,
void print(int a, int) {
  std::printf("a = %d\n",a);
}
end note
]
In the function-body, a function-local predefined variable denotes a block-scope object of static storage duration that is implicitly defined (see [basic.scope.block]).
The function-local predefined variable _­_­func_­_­ is defined as if a definition of the form
static const char __func__[] = "function-name";
had been provided, where function-name is an implementation-defined string.
It is unspecified whether such a variable has an address distinct from that of any other object in the program.103
[Example
:
struct S {
  S() : s(__func__) { }             // OK
  const char* s;
};
void f(const char* s = __func__);   // error: _­_­func_­_­ is undeclared
end example
]
Implementations are permitted to provide additional predefined variables with names that are reserved to the implementation ([lex.name]).
If a predefined variable is not odr-used ([basic.def.odr]), its string value need not be present in the program image.

11.4.2 Explicitly-defaulted functions [dcl.fct.def.default]

A function definition of the form:
attribute-specifier-seq decl-specifier-seq declarator virt-specifier-seq  = default ;
is called an explicitly-defaulted definition.
A function that is explicitly defaulted shall
  • be a special member function,
  • have the same declared function type (except for possibly differing ref-qualifiers and except that in the case of a copy constructor or copy assignment operator, the parameter type may be “reference to non-const T”, where T is the name of the member function's class) as if it had been implicitly declared, and
  • not have default arguments.
An explicitly-defaulted function that is not defined as deleted may be declared constexpr only if it would have been implicitly declared as constexpr.
If a function is explicitly defaulted on its first declaration, it is implicitly considered to be constexpr if the implicit declaration would be.
If a function that is explicitly defaulted is declared with a noexcept-specifier that does not produce the same exception specification as the implicit declaration ([except.spec]), then
  • if the function is explicitly defaulted on its first declaration, it is defined as deleted;
  • otherwise, the program is ill-formed.
[Example
:
struct S {
  constexpr S() = default;              // ill-formed: implicit S() is not constexpr
  S(int a = 0) = default;               // ill-formed: default argument
  void operator=(const S&) = default;   // ill-formed: non-matching return type
  ~S() noexcept(false) = default;       // deleted: exception specification does not match
private:
  int i;
  S(S&);                                // OK: private copy constructor
};
S::S(S&) = default;                     // OK: defines copy constructor
end example
]
Explicitly-defaulted functions and implicitly-declared functions are collectively called defaulted functions, and the implementation shall provide implicit definitions for them ([class.ctor] [class.dtor], [class.copy]), which might mean defining them as deleted.
A function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration.
A user-provided explicitly-defaulted function (i.e., explicitly defaulted after its first declaration) is defined at the point where it is explicitly defaulted; if such a function is implicitly defined as deleted, the program is ill-formed.
[Note
:
Declaring a function as defaulted after its first declaration can provide efficient execution and concise definition while enabling a stable binary interface to an evolving code base.
end note
]
[Example
:
struct trivial {
  trivial() = default;
  trivial(const trivial&) = default;
  trivial(trivial&&) = default;
  trivial& operator=(const trivial&) = default;
  trivial& operator=(trivial&&) = default;
  ~trivial() = default;
};

struct nontrivial1 {
  nontrivial1();
};
nontrivial1::nontrivial1() = default;   // not first declaration
end example
]

11.4.3 Deleted definitions [dcl.fct.def.delete]

A function definition of the form:
A function with a deleted definition is also called a deleted function.
A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed.
[Note
:
This includes calling the function implicitly or explicitly and forming a pointer or pointer-to-member to the function.
It applies even for references in expressions that are not potentially-evaluated.
If a function is overloaded, it is referenced only if the function is selected by overload resolution.
The implicit odr-use ([basic.def.odr]) of a virtual function does not, by itself, constitute a reference.
end note
]
[Example
:
One can enforce non-default-initialization and non-integral initialization with
struct onlydouble {
  onlydouble() = delete;                // OK, but redundant
  onlydouble(std::intmax_t) = delete;
  onlydouble(double);
};
end example
]
[Example
:
One can prevent use of a class in certain new-expressions by using deleted definitions of a user-declared operator new for that class.
struct sometype {
  void* operator new(std::size_t) = delete;
  void* operator new[](std::size_t) = delete;
};
sometype* p = new sometype;     // error, deleted class operator new
sometype* q = new sometype[3];  // error, deleted class operator new[]
end example
]
[Example
:
One can make a class uncopyable, i.e. move-only, by using deleted definitions of the copy constructor and copy assignment operator, and then providing defaulted definitions of the move constructor and move assignment operator.
struct moveonly {
  moveonly() = default;
  moveonly(const moveonly&) = delete;
  moveonly(moveonly&&) = default;
  moveonly& operator=(const moveonly&) = delete;
  moveonly& operator=(moveonly&&) = default;
  ~moveonly() = default;
};
moveonly* p;
moveonly q(*p);                 // error, deleted copy constructor
end example
]
A deleted function is implicitly an inline function ([dcl.inline]).
[Note
:
The one-definition rule ([basic.def.odr]) applies to deleted definitions.
end note
]
A deleted definition of a function shall be the first declaration of the function or, for an explicit specialization of a function template, the first declaration of that specialization.
An implicitly declared allocation or deallocation function ([basic.stc.dynamic]) shall not be defined as deleted.
[Example
:
struct sometype {
  sometype();
};
sometype::sometype() = delete;  // ill-formed; not first declaration
end example
]

11.5 Structured binding declarations [dcl.struct.bind]

A structured binding declaration introduces the identifiers v, v, v, .
Let cv denote the cv-qualifiers in the decl-specifier-seq.
First, a variable with a unique name e is introduced.
If the assignment-expression in the initializer has array type A and no ref-qualifier is present, e has type cv A and each element is copy-initialized or direct-initialized from the corresponding element of the assignment-expression as specified by the form of the initializer.
Otherwise, e is defined as-if by
attribute-specifier-seq decl-specifier-seq ref-qualifier e initializer ;
where the declaration is never interpreted as a function declaration and the parts of the declaration other than the declarator-id are taken from the corresponding structured binding declaration.
The type of the id-expression e is called E.
[Note
:
E is never a reference type (Clause [expr]).
end note
]
If E is an array type with element type T, the number of elements in the identifier-list shall be equal to the number of elements of E.
Each v is the name of an lvalue that refers to the element i of the array and whose type is T; the referenced type is T.
[Note
:
The top-level cv-qualifiers of T are cv.
end note
]
[Example
:
  auto f() -> int(&)[2];
  auto [ x, y ] = f();          // x and y refer to elements in a copy of the array return value
  auto& [ xr, yr ] = f();       // xr and yr refer to elements in the array referred to by f's return value
end example
]
Otherwise, if the qualified-id std​::​tuple_­size<E> names a complete type, the expression std​::​tuple_­size<E>​::​value shall be a well-formed integral constant expression and the number of elements in the identifier-list shall be equal to the value of that expression.
The unqualified-id get is looked up in the scope of E by class member access lookup ([basic.lookup.classref]), and if that finds at least one declaration, the initializer is e.get<i>().
Otherwise, the initializer is get<i>(e), where get is looked up in the associated namespaces ([basic.lookup.argdep]).
In either case, get<i> is interpreted as a template-id.
[Note
:
Ordinary unqualified lookup ([basic.lookup.unqual]) is not performed.
end note
]
In either case, e is an lvalue if the type of the entity e is an lvalue reference and an xvalue otherwise.
Given the type designated by std​::​tuple_­element<i, E>​::​type, each v is a variable of type “reference to ” initialized with the initializer, where the reference is an lvalue reference if the initializer is an lvalue and an rvalue reference otherwise; the referenced type is .
Otherwise, all of E's non-static data members shall be public direct members of E or of the same unambiguous public base class of E, E shall not have an anonymous union member, and the number of elements in the identifier-list shall be equal to the number of non-static data members of E.
Designating the non-static data members of E as m, m, m, .
(in declaration order), each v is the name of an lvalue that refers to the member m of e and whose type is cv , where is the declared type of that member; the referenced type is cv .
The lvalue is a bit-field if that member is a bit-field.
[Example
:
struct S { int x1 : 2; volatile double y1; };
S f();
const auto [ x, y ] = f();
The type of the id-expression x is “const int”, the type of the id-expression y is “const volatile double.
end example
]

11.6 Initializers [dcl.init]

A declarator can specify an initial value for the identifier being declared.
The identifier designates a variable being initialized.
The process of initialization described in the remainder of [dcl.init] applies also to initializations specified by other syntactic contexts, such as the initialization of function parameters ([expr.call]) or the initialization of return values ([stmt.return]).
Except for objects declared with the constexpr specifier, for which see [dcl.constexpr], an initializer in the definition of a variable can consist of arbitrary expressions involving literals and previously declared variables and functions, regardless of the variable's storage duration.
[Example
:
int f(int);
int a = 2;
int b = f(a);
int c(b);
end example
]
[Note
:
Default arguments are more restricted; see [dcl.fct.default].
end note
]
[Note
:
The order of initialization of variables with static storage duration is described in [basic.start] and [stmt.dcl].
end note
]
A declaration of a block-scope variable with external or internal linkage that has an initializer is ill-formed.
To zero-initialize an object or reference of type T means:
  • if T is a scalar type ([basic.types]), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T;104
  • if T is a (possibly cv-qualified) non-union class type, each non-static data member, each non-virtual base class subobject, and, if the object is not a base class subobject, each virtual base class subobject is zero-initialized and padding is initialized to zero bits;
  • if T is a (possibly cv-qualified) union type, the object's first non-static named data member is zero-initialized and padding is initialized to zero bits;
  • if T is an array type, each element is zero-initialized;
  • if T is a reference type, no initialization is performed.
To default-initialize an object of type T means:
  • If T is a (possibly cv-qualified) class type (Clause [class]), constructors are considered.
    The applicable constructors are enumerated ([over.match.ctor]), and the best one for the initializer () is chosen through overload resolution ([over.match]).
    The constructor thus selected is called, with an empty argument list, to initialize the object.
  • If T is an array type, each element is default-initialized.
  • Otherwise, no initialization is performed.
A class type T is const-default-constructible if default-initialization of T would invoke a user-provided constructor of T (not inherited from a base class) or if
  • each direct non-variant non-static data member M of T has a default member initializer or, if M is of class type X (or array thereof), X is const-default-constructible,
  • if T is a union with at least one non-static data member, exactly one variant member has a default member initializer,
  • if T is not a union, for each anonymous union member with at least one non-static data member (if any), exactly one non-static data member has a default member initializer, and
  • each potentially constructed base class of T is const-default-constructible.
If a program calls for the default-initialization of an object of a const-qualified type T, T shall be a const-default-constructible class type or array thereof.
To value-initialize an object of type T means:
  • if T is a (possibly cv-qualified) class type (Clause [class]) with either no default constructor ([class.ctor]) or a default constructor that is user-provided or deleted, then the object is default-initialized;
  • if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;
  • if T is an array type, then each element is value-initialized;
  • otherwise, the object is zero-initialized.
A program that calls for default-initialization or value-initialization of an entity of reference type is ill-formed.
[Note
:
Every object of static storage duration is zero-initialized at program startup before any other initialization takes place.
In some cases, additional initialization is done later.
end note
]
An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.
[Note
:
Since () is not permitted by the syntax for initializer,
X a();
is not the declaration of an object of class X, but the declaration of a function taking no argument and returning an X.
The form () is permitted in certain other initialization contexts ([expr.new], [expr.type.conv], [class.base.init]).
end note
]
If no initializer is specified for an object, the object is default-initialized.
When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced ([expr.ass]).
[Note
:
Objects with static or thread storage duration are zero-initialized, see [basic.start.static].
end note
]
If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases:
  • If an indeterminate value of unsigned narrow character type ([basic.fundamental]) or std​::​byte type ([cstddef.syn]) is produced by the evaluation of: then the result of the operation is an indeterminate value.
  • If an indeterminate value of unsigned narrow character type or std​::​byte type is produced by the evaluation of the right operand of a simple assignment operator ([expr.ass]) whose first operand is an lvalue of unsigned narrow character type or std​::​byte type, an indeterminate value replaces the value of the object referred to by the left operand.
  • If an indeterminate value of unsigned narrow character type is produced by the evaluation of the initialization expression when initializing an object of unsigned narrow character type, that object is initialized to an indeterminate value.
  • If an indeterminate value of unsigned narrow character type or std​::​byte type is produced by the evaluation of the initialization expression when initializing an object of std​::​byte type, that object is initialized to an indeterminate value.
[Example
:
  int f(bool b) {
    unsigned char c;
    unsigned char d = c;        // OK, d has an indeterminate value
    int e = d;                  // undefined behavior
    return b ? d : 0;           // undefined behavior if b is true
  }
end example
]
An initializer for a static member is in the scope of the member's class.
[Example
:
int a;

struct X {
  static int a;
  static int b;
};

int X::a = 1;
int X::b = a;                   // X​::​b = X​::​a
end example
]
If the entity being initialized does not have class type, the expression-list in a parenthesized initializer shall be a single expression.
The initialization that occurs in the = form of a brace-or-equal-initializer or condition ([stmt.select]), as well as in argument passing, function return, throwing an exception ([except.throw]), handling an exception ([except.handle]), and aggregate member initialization ([dcl.init.aggr]), is called copy-initialization.
[Note
:
Copy-initialization may invoke a move ([class.copy]).
end note
]
The initialization that occurs in the forms
T x(a);
T x{a};
as well as in new expressions ([expr.new]), static_­cast expressions ([expr.static.cast]), functional notation type conversions ([expr.type.conv]), mem-initializers, and the braced-init-list form of a condition is called direct-initialization.
The semantics of initializers are as follows.
The destination type is the type of the object or reference being initialized and the source type is the type of the initializer expression.
If the initializer is not a single (possibly parenthesized) expression, the source type is not defined.
  • If the initializer is a (non-parenthesized) braced-init-list or is = braced-init-list, the object or reference is list-initialized ([dcl.init.list]).
  • If the destination type is a reference type, see [dcl.init.ref].
  • If the destination type is an array of characters, an array of char16_­t, an array of char32_­t, or an array of wchar_­t, and the initializer is a string literal, see [dcl.init.string].
  • If the initializer is (), the object is value-initialized.
  • Otherwise, if the destination type is an array, the program is ill-formed.
  • If the destination type is a (possibly cv-qualified) class type:
    • If the initializer expression is a prvalue and the cv-unqualified version of the source type is the same class as the class of the destination, the initializer expression is used to initialize the destination object.
      [Example
      :
      T x = T(T(T())); calls the T default constructor to initialize x.
      end example
      ]
    • Otherwise, if the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered.
      The applicable constructors are enumerated ([over.match.ctor]), and the best one is chosen through overload resolution ([over.match]).
      The constructor so selected is called to initialize the object, with the initializer expression or expression-list as its argument(s).
      If no constructor applies, or the overload resolution is ambiguous, the initialization is ill-formed.
    • Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in [over.match.copy], and the best one is chosen through overload resolution ([over.match]).
      If the conversion cannot be done or is ambiguous, the initialization is ill-formed.
      The function selected is called with the initializer expression as its argument; if the function is a constructor, the call is a prvalue of the cv-unqualified version of the destination type whose result object is initialized by the constructor.
      The call is used to direct-initialize, according to the rules above, the object that is the destination of the copy-initialization.
  • Otherwise, if the source type is a (possibly cv-qualified) class type, conversion functions are considered.
    The applicable conversion functions are enumerated ([over.match.conv]), and the best one is chosen through overload resolution ([over.match]).
    The user-defined conversion so selected is called to convert the initializer expression into the object being initialized.
    If the conversion cannot be done or is ambiguous, the initialization is ill-formed.
  • Otherwise, the initial value of the object being initialized is the (possibly converted) value of the initializer expression.
    Standard conversions (Clause [conv]) will be used, if necessary, to convert the initializer expression to the cv-unqualified version of the destination type; no user-defined conversions are considered.
    If the conversion cannot be done, the initialization is ill-formed.
    When initializing a bit-field with a value that it cannot represent, the resulting value of the bit-field is implementation-defined.
    [Note
    :
    An expression of type “cv1 T” can initialize an object of type “cv2 T” independently of the cv-qualifiers cv1 and cv2.
    int a;
    const int b = a;
    int c = b;
    end note
    ]
An initializer-clause followed by an ellipsis is a pack expansion ([temp.variadic]).
If the initializer is a parenthesized expression-list, the expressions are evaluated in the order specified for function calls ([expr.call]).
An object whose initialization has completed is deemed to be constructed, even if no constructor of the object's class is invoked for the initialization.
[Note
:
Such an object might have been value-initialized or initialized by aggregate initialization ([dcl.init.aggr]) or by an inherited constructor ([class.inhctor.init]).
end note
]
A declaration that specifies the initialization of a variable, whether from an explicit initializer or by default-initialization, is called the initializing declaration of that variable.
[Note
:
In most cases this is the defining declaration ([basic.def]) of the variable, but the initializing declaration of a non-inline static data member ([class.static.data]) might be the declaration within the class definition and not the definition at namespace scope.
end note
]
As specified in [conv.ptr], converting an integer literal whose value is 0 to a pointer type results in a null pointer value.

11.6.1 Aggregates [dcl.init.aggr]

An aggregate is an array or a class (Clause [class]) with
[Note
:
Aggregate initialization does not allow accessing protected and private base class' members or constructors.
end note
]
The elements of an aggregate are:
  • for an array, the array elements in increasing subscript order, or
  • for a class, the direct base classes in declaration order, followed by the direct non-static data members ([class.mem]) that are not members of an anonymous union, in declaration order.
When an aggregate is initialized by an initializer list as specified in [dcl.init.list], the elements of the initializer list are taken as initializers for the elements of the aggregate, in order.
Each element is copy-initialized from the corresponding initializer-clause.
If the initializer-clause is an expression and a narrowing conversion ([dcl.init.list]) is required to convert the expression, the program is ill-formed.
[Note
:
If an initializer-clause is itself an initializer list, the element is list-initialized, which will result in a recursive application of the rules in this section if the element is an aggregate.
end note
]
[Example
:
struct A {
  int x;
  struct B {
    int i;
    int j;
  } b;
} a = { 1, { 2, 3 } };
initializes a.x with 1, a.b.i with 2, a.b.j with 3.
struct base1 { int b1, b2 = 42; };
struct base2 {
  base2() {
    b3 = 42;
  }
  int b3;
};
struct derived : base1, base2 {
  int d;
};

derived d1{{1, 2}, {}, 4};
derived d2{{}, {}, 4};
initializes d1.b1 with 1, d1.b2 with 2, d1.b3 with 42, d1.d with 4, and d2.b1 with 0, d2.b2 with 42, d2.b3 with 42, d2.d with 4.
end example
]
An aggregate that is a class can also be initialized with a single expression not enclosed in braces, as described in [dcl.init].
An array of unknown bound initialized with a brace-enclosed initializer-list containing n initializer-clauses, where n shall be greater than zero, is defined as having n elements ([dcl.array]).
[Example
:
int x[] = { 1, 3, 5 };
declares and initializes x as a one-dimensional array that has three elements since no size was specified and there are three initializers.
end example
]
An empty initializer list {} shall not be used as the initializer-clause for an array of unknown bound.105
[Note
:
A default member initializer does not determine the bound for a member array of unknown bound.
Since the default member initializer is ignored if a suitable mem-initializer is present ([class.base.init]), the default member initializer is not considered to initialize the array of unknown bound.
[Example
:
struct S {
  int y[] = { 0 };          // error: non-static data member of incomplete type
};
end example
]
end note
]
[Note
:
Static data members and unnamed bit-fields are not considered elements of the aggregate.
[Example
:
struct A {
  int i;
  static int s;
  int j;
  int :17;
  int k;
} a = { 1, 2, 3 };
Here, the second initializer 2 initializes a.j and not the static data member A​::​s, and the third initializer 3 initializes a.k and not the unnamed bit-field before it.
end example
]
end note
]
An initializer-list is ill-formed if the number of initializer-clauses exceeds the number of elements to initialize.
[Example
:
char cv[4] = { 'a', 's', 'd', 'f', 0 };     // error
is ill-formed.
end example
]
If there are fewer initializer-clauses in the list than there are elements in a non-union aggregate, then each element not explicitly initialized is initialized as follows:
  • If the element has a default member initializer ([class.mem]), the element is initialized from that initializer.
  • Otherwise, if the element is not a reference, the element is copy-initialized from an empty initializer list ([dcl.init.list]).
  • Otherwise, the program is ill-formed.
If the aggregate is a union and the initializer list is empty, then
  • if any variant member has a default member initializer, that member is initialized from its default member initializer;
  • otherwise, the first member of the union (if any) is copy-initialized from an empty initializer list.
[Example
:
struct S { int a; const char* b; int c; int d = b[a]; };
S ss = { 1, "asdf" };
initializes ss.a with 1, ss.b with "asdf", ss.c with the value of an expression of the form int{} (that is, 0), and ss.d with the value of ss.b[ss.a] (that is, 's'), and in
struct X { int i, j, k = 42; };
X a[] = { 1, 2, 3, 4, 5, 6 };
X b[2] = { { 1, 2, 3 }, { 4, 5, 6 } };
a and b have the same value
end example
]
If a reference member is initialized from its default member initializer and a potentially-evaluated subexpression thereof is an aggregate initialization that would use that default member initializer, the program is ill-formed.
[Example
:
  struct A;
  extern A a;
  struct A {
    const A& a1 { A{a,a} };     // OK
    const A& a2 { A{} };        // error
  };
  A a{a,a};                     // OK
end example
]
If an aggregate class C contains a subaggregate element e with no elements, the initializer-clause for e shall not be omitted from an initializer-list for an object of type C unless the initializer-clauses for all elements of C following e are also omitted.
[Example
:
struct S { } s;
struct A {
  S s1;
  int i1;
  S s2;
  int i2;
  S s3;
  int i3;
} a = {
  { },              // Required initialization
  0,
  s,                // Required initialization
  0
};                  // Initialization not required for A​::​s3 because A​::​i3 is also not initialized
end example
]
When initializing a multi-dimensional array, the initializer-clauses initialize the elements with the last (rightmost) index of the array varying the fastest ([dcl.array]).
[Example
:
int x[2][2] = { 3, 1, 4, 2 };
initializes x[0][0] to 3, x[0][1] to 1, x[1][0] to 4, and x[1][1] to 2.
On the other hand,
float y[4][3] = {
  { 1 }, { 2 }, { 3 }, { 4 }
};
initializes the first column of y (regarded as a two-dimensional array) and leaves the rest zero.
end example
]
Braces can be elided in an initializer-list as follows.
If the initializer-list begins with a left brace, then the succeeding comma-separated list of initializer-clauses initializes the elements of a subaggregate; it is erroneous for there to be more initializer-clauses than elements.
If, however, the initializer-list for a subaggregate does not begin with a left brace, then only enough initializer-clauses from the list are taken to initialize the elements of the subaggregate; any remaining initializer-clauses are left to initialize the next element of the aggregate of which the current subaggregate is an element.
[Example
:
float y[4][3] = {
  { 1, 3, 5 },
  { 2, 4, 6 },
  { 3, 5, 7 },
};
is a completely-braced initialization: 1, 3, and 5 initialize the first row of the array y[0], namely y[0][0], y[0][1], and y[0][2].
Likewise the next two lines initialize y[1] and y[2].
The initializer ends early and therefore y[3]s elements are initialized as if explicitly initialized with an expression of the form float(), that is, are initialized with 0.0.
In the following example, braces in the initializer-list are elided; however the initializer-list has the same effect as the completely-braced initializer-list of the above example,
float y[4][3] = {
  1, 3, 5, 2, 4, 6, 3, 5, 7
};
The initializer for y begins with a left brace, but the one for y[0] does not, therefore three elements from the list are used.
Likewise the next three are taken successively for y[1] and y[2].
end example
]
All implicit type conversions (Clause [conv]) are considered when initializing the element with an assignment-expression.
If the assignment-expression can initialize an element, the element is initialized.
Otherwise, if the element is itself a subaggregate, brace elision is assumed and the assignment-expression is considered for the initialization of the first element of the subaggregate.
[Note
:
As specified above, brace elision cannot apply to subaggregates with no elements; an initializer-clause for the entire subobject is required.
end note
]
[Example
:
struct A {
  int i;
  operator int();
};
struct B {
  A a1, a2;
  int z;
};
A a;
B b = { 4, a, a };
Braces are elided around the initializer-clause for b.a1.i.
b.a1.i is initialized with 4, b.a2 is initialized with a, b.z is initialized with whatever a.operator int() returns.
end example
]
[Note
:
An aggregate array or an aggregate class may contain elements of a class type with a user-provided constructor ([class.ctor]).
Initialization of these aggregate objects is described in [class.expl.init].
end note
]
[Note
:
Whether the initialization of aggregates with static storage duration is static or dynamic is specified in [basic.start.static], [basic.start.dynamic], and [stmt.dcl].
end note
]
When a union is initialized with a brace-enclosed initializer, the braces shall only contain an initializer-clause for the first non-static data member of the union.
[Example
:
union u { int a; const char* b; };
u a = { 1 };
u b = a;
u c = 1;                        // error
u d = { 0, "asdf" };            // error
u e = { "asdf" };               // error
end example
]
[Note
:
As described above, the braces around the initializer-clause for a union member can be omitted if the union is a member of another aggregate.
end note
]
The syntax provides for empty initializer-lists, but nonetheless C++ does not have zero length arrays.

11.6.2 Character arrays [dcl.init.string]

An array of narrow character type ([basic.fundamental]), char16_­t array, char32_­t array, or wchar_­t array can be initialized by a narrow string literal, char16_­t string literal, char32_­t string literal, or wide string literal, respectively, or by an appropriately-typed string literal enclosed in braces ([lex.string]).
Successive characters of the value of the string literal initialize the elements of the array.
[Example
:
char msg[] = "Syntax error on line %s\n";
shows a character array whose members are initialized with a string-literal.
Note that because '\n' is a single character and because a trailing '\0' is appended, sizeof(msg) is 25.
end example
]
There shall not be more initializers than there are array elements.
[Example
:
char cv[4] = "asdf";            // error
is ill-formed since there is no space for the implied trailing '\0'.
end example
]
If there are fewer initializers than there are array elements, each element not explicitly initialized shall be zero-initialized ([dcl.init]).

11.6.3 References [dcl.init.ref]

A variable whose declared type is “reference to type T” ([dcl.ref]) shall be initialized.
[Example
:
int g(int) noexcept;
void f() {
  int i;
  int& r = i;                   // r refers to i
  r = 1;                        // the value of i becomes 1
  int* p = &r;                  // p points to i
  int& rr = r;                  // rr refers to what r refers to, that is, to i
  int (&rg)(int) = g;           // rg refers to the function g
  rg(i);                        // calls function g
  int a[3];
  int (&ra)[3] = a;             // ra refers to the array a
  ra[1] = i;                    // modifies a[1]
}
end example
]
A reference cannot be changed to refer to another object after initialization.
[Note
:
Assignment to a reference assigns to the object referred to by the reference ([expr.ass]).
end note
]
Argument passing ([expr.call]) and function value return ([stmt.return]) are initializations.
The initializer can be omitted for a reference only in a parameter declaration ([dcl.fct]), in the declaration of a function return type, in the declaration of a class member within its class definition ([class.mem]), and where the extern specifier is explicitly used.
[Example
:
int& r1;                        // error: initializer missing
extern int& r2;                 // OK
end example
]
Given types “cv1 T1” and “cv2 T2”, “cv1 T1” is reference-related to “cv2 T2” if T1 is the same type as T2, or T1 is a base class of T2.
cv1 T1” is reference-compatible with “cv2 T2” if
  • T1 is reference-related to T2, or
  • T2 is “noexcept function” and T1 is “function”, where the function types are otherwise the same,
and cv1 is the same cv-qualification as, or greater cv-qualification than, cv2.
In all cases where the reference-related or reference-compatible relationship of two types is used to establish the validity of a reference binding, and T1 is a base class of T2, a program that necessitates such a binding is ill-formed if T1 is an inaccessible (Clause [class.access]) or ambiguous ([class.member.lookup]) base class of T2.
A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:
  • If the reference is an lvalue reference and the initializer expression
    • is an lvalue (but is not a bit-field), and “cv1 T1” is reference-compatible with “cv2 T2”, or
    • has a class type (i.e., T2 is a class type), where T1 is not reference-related to T2, and can be converted to an lvalue of type “cv3 T3”, where “cv1 T1” is reference-compatible with “cv3 T3106 (this conversion is selected by enumerating the applicable conversion functions ([over.match.ref]) and choosing the best one through overload resolution ([over.match])),
    then the reference is bound to the initializer expression lvalue in the first case and to the lvalue result of the conversion in the second case (or, in either case, to the appropriate base class subobject of the object).
    [Note
    :
    The usual lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions are not needed, and therefore are suppressed, when such direct bindings to lvalues are done.
    end note
    ]
    [Example
    :
    double d = 2.0;
    double& rd = d;                 // rd refers to d
    const double& rcd = d;          // rcd refers to d
    
    struct A { };
    struct B : A { operator int&(); } b;
    A& ra = b;                      // ra refers to A subobject in b
    const A& rca = b;               // rca refers to A subobject in b
    int& ir = B();                  // ir refers to the result of B​::​operator int&
    
    end example
    ]
  • Otherwise, the reference shall be an lvalue reference to a non-volatile const type (i.e., cv1 shall be const), or the reference shall be an rvalue reference.
    [Example
    :
    double& rd2 = 2.0;              // error: not an lvalue and reference not const
    int  i = 2;
    double& rd3 = i;                // error: type mismatch and reference not const
    
    end example
    ]
    • If the initializer expression
      • is an rvalue (but not a bit-field) or function lvalue and “cv1 T1” is reference-compatible with “cv2 T2”, or
      • has a class type (i.e., T2 is a class type), where T1 is not reference-related to T2, and can be converted to an rvalue or function lvalue of type “cv3 T3”, where “cv1 T1” is reference-compatible with “cv3 T3” (see [over.match.ref]),
      then the value of the initializer expression in the first case and the result of the conversion in the second case is called the converted initializer.
      If the converted initializer is a prvalue, its type T4 is adjusted to type “cv1 T4” ([conv.qual]) and the temporary materialization conversion ([conv.rval]) is applied.
      In any case, the reference is bound to the resulting glvalue (or to an appropriate base class subobject).
      [Example
      :
      struct A { };
      struct B : A { } b;
      extern B f();
      const A& rca2 = f();                // bound to the A subobject of the B rvalue.
      A&& rra = f();                      // same as above
      struct X {
        operator B();
        operator int&();
      } x;
      const A& r = x;                     // bound to the A subobject of the result of the conversion
      int i2 = 42;
      int&& rri = static_cast<int&&>(i2); // bound directly to i2
      B&& rrb = x;                        // bound directly to the result of operator B
      
      end example
      ]
    • Otherwise:
      • If T1 or T2 is a class type and T1 is not reference-related to T2, user-defined conversions are considered using the rules for copy-initialization of an object of type “cv1 T1” by user-defined conversion ([dcl.init], [over.match.copy], [over.match.conv]); the program is ill-formed if the corresponding non-reference copy-initialization would be ill-formed.
        The result of the call to the conversion function, as described for the non-reference copy-initialization, is then used to direct-initialize the reference.
        For this direct-initialization, user-defined conversions are not considered.
      • Otherwise, the initializer expression is implicitly converted to a prvalue of type “cv1 T1.
        The temporary materialization conversion is applied and the reference is bound to the result.
      If T1 is reference-related to T2:
      • cv1 shall be the same cv-qualification as, or greater cv-qualification than, cv2; and
      • if the reference is an rvalue reference, the initializer expression shall not be an lvalue.
      [Example
      :
      struct Banana { };
      struct Enigma { operator const Banana(); };
      struct Alaska { operator Banana&(); };
      void enigmatic() {
        typedef const Banana ConstBanana;
        Banana &&banana1 = ConstBanana(); // ill-formed
        Banana &&banana2 = Enigma();      // ill-formed
        Banana &&banana3 = Alaska();      // ill-formed
      }
      
      const double& rcd2 = 2;         // rcd2 refers to temporary with value 2.0
      double&& rrd = 2;               // rrd refers to temporary with value 2.0
      const volatile int cvi = 1;
      const int& r2 = cvi;            // error: cv-qualifier dropped
      struct A { operator volatile int&(); } a;
      const int& r3 = a;              // error: cv-qualifier dropped
                                      // from result of conversion function
      double d2 = 1.0;
      double&& rrd2 = d2;             // error: initializer is lvalue of related type
      struct X { operator int&(); };
      int&& rri2 = X();               // error: result of conversion function is lvalue of related type
      int i3 = 2;
      double&& rrd3 = i3;             // rrd3 refers to temporary with value 2.0
      
      end example
      ]
In all cases except the last (i.e., implicitly converting the initializer expression to the underlying type of the reference), the reference is said to bind directly to the initializer expression.
[Note
:
[class.temporary] describes the lifetime of temporaries bound to references.
end note
]
This requires a conversion function ([class.conv.fct]) returning a reference type.

11.6.4 List-initialization [dcl.init.list]

List-initialization is initialization of an object or reference from a braced-init-list.
Such an initializer is called an initializer list, and the comma-separated initializer-clauses of the list are called the elements of the initializer list.
An initializer list may be empty.
List-initialization can occur in direct-initialization or copy-initialization contexts; list-initialization in a direct-initialization context is called direct-list-initialization and list-initialization in a copy-initialization context is called copy-list-initialization.
[Note
:
List-initialization can be used
[Example
:
int a = {1};
std::complex<double> z{1,2};
new std::vector<std::string>{"once", "upon", "a", "time"};  // 4 string elements
f( {"Nicholas","Annemarie"} );  // pass list of two elements
return { "Norah" };             // return list of one element
int* e {};                      // initialization to zero / null pointer
x = double{1};                  // explicitly construct a double
std::map<std::string,int> anim = { {"bear",4}, {"cassowary",2}, {"tiger",7} };
end example
]
end note
]
A constructor is an initializer-list constructor if its first parameter is of type std​::​initializer_­list<E> or reference to possibly cv-qualified std​::​initializer_­list<E> for some type E, and either there are no other parameters or else all other parameters have default arguments ([dcl.fct.default]).
[Note
:
Initializer-list constructors are favored over other constructors in list-initialization ([over.match.list]).
Passing an initializer list as the argument to the constructor template template<class T> C(T) of a class C does not create an initializer-list constructor, because an initializer list argument causes the corresponding parameter to be a non-deduced context ([temp.deduct.call]).
end note
]
The template std​::​initializer_­list is not predefined; if the header <initializer_­list> is not included prior to a use of std​::​initializer_­list — even an implicit use in which the type is not named ([dcl.spec.auto]) — the program is ill-formed.
List-initialization of an object or reference of type T is defined as follows:
  • If T is an aggregate class and the initializer list has a single element of type cv U, where U is T or a class derived from T, the object is initialized from that element (by copy-initialization for copy-list-initialization, or by direct-initialization for direct-list-initialization).
  • Otherwise, if T is a character array and the initializer list has a single element that is an appropriately-typed string literal ([dcl.init.string]), initialization is performed as described in that section.
  • Otherwise, if T is an aggregate, aggregate initialization is performed ([dcl.init.aggr]).
    [Example
    :
    double ad[] = { 1, 2.0 };           // OK
    int ai[] = { 1, 2.0 };              // error: narrowing
    
    struct S2 {
      int m1;
      double m2, m3;
    };
    S2 s21 = { 1, 2, 3.0 };             // OK
    S2 s22 { 1.0, 2, 3 };               // error: narrowing
    S2 s23 { };                         // OK: default to 0,0,0
    
    end example
    ]
  • Otherwise, if the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized.
  • Otherwise, if T is a specialization of std​::​initializer_­list<E>, the object is constructed as described below.
  • Otherwise, if T is a class type, constructors are considered.
    The applicable constructors are enumerated and the best one is chosen through overload resolution ([over.match], [over.match.list]).
    If a narrowing conversion (see below) is required to convert any of the arguments, the program is ill-formed.
    [Example
    :
    struct S {
      S(std::initializer_list<double>); // #1
      S(std::initializer_list<int>);    // #2
      S();                              // #3
      // ...
    };
    S s1 = { 1.0, 2.0, 3.0 };           // invoke #1
    S s2 = { 1, 2, 3 };                 // invoke #2
    S s3 = { };                         // invoke #3
    
    end example
    ]
    [Example
    :
    struct Map {
      Map(std::initializer_list<std::pair<std::string,int>>);
    };
    Map ship = {{"Sophie",14}, {"Surprise",28}};
    end example
    ]
    [Example
    :
    struct S {
      // no initializer-list constructors
      S(int, double, double);           // #1
      S();                              // #2
      // ...
    };
    S s1 = { 1, 2, 3.0 };               // OK: invoke #1
    S s2 { 1.0, 2, 3 };                 // error: narrowing
    S s3 { };                           // OK: invoke #2
    
    end example
    ]
  • Otherwise, if T is an enumeration with a fixed underlying type ([dcl.enum]), the initializer-list has a single element v, and the initialization is direct-list-initialization, the object is initialized with the value T(v) ([expr.type.conv]); if a narrowing conversion is required to convert v to the underlying type of T, the program is ill-formed.
    [Example
    :
    enum byte : unsigned char { };
    byte b { 42 };                      // OK
    byte c = { 42 };                    // error
    byte d = byte{ 42 };                // OK; same value as b
    byte e { -1 };                      // error
    
    struct A { byte b; };
    A a1 = { { 42 } };                  // error
    A a2 = { byte{ 42 } };              // OK
    
    void f(byte);
    f({ 42 });                          // error
    
    enum class Handle : uint32_t { Invalid = 0 };
    Handle h { 42 };                    // OK
    
    end example
    ]
  • Otherwise, if the initializer list has a single element of type E and either T is not a reference type or its referenced type is reference-related to E, the object or reference is initialized from that element (by copy-initialization for copy-list-initialization, or by direct-initialization for direct-list-initialization); if a narrowing conversion (see below) is required to convert the element to T, the program is ill-formed.
    [Example
    :
    int x1 {2};                         // OK
    int x2 {2.0};                       // error: narrowing
    
    end example
    ]
  • Otherwise, if T is a reference type, a prvalue of the type referenced by T is generated.
    The prvalue initializes its result object by copy-list-initialization or direct-list-initialization, depending on the kind of initialization for the reference.
    The prvalue is then used to direct-initialize the reference.
    [Note
    :
    As usual, the binding will fail and the program is ill-formed if the reference type is an lvalue reference to a non-const type.
    end note
    ]
    [Example
    :
    struct S {
      S(std::initializer_list<double>); // #1
      S(const std::string&);            // #2
      // ...
    };
    const S& r1 = { 1, 2, 3.0 };        // OK: invoke #1
    const S& r2 { "Spinach" };          // OK: invoke #2
    S& r3 = { 1, 2, 3 };                // error: initializer is not an lvalue
    const int& i1 = { 1 };              // OK
    const int& i2 = { 1.1 };            // error: narrowing
    const int (&iar)[2] = { 1, 2 };     // OK: iar is bound to temporary array
    
    end example
    ]
  • Otherwise, if the initializer list has no elements, the object is value-initialized.
    [Example
    :
    int** pp {};                        // initialized to null pointer
    
    end example
    ]
  • Otherwise, the program is ill-formed.
    [Example
    :
    struct A { int i; int j; };
    A a1 { 1, 2 };                      // aggregate initialization
    A a2 { 1.2 };                       // error: narrowing
    struct B {
      B(std::initializer_list<int>);
    };
    B b1 { 1, 2 };                      // creates initializer_­list<int> and calls constructor
    B b2 { 1, 2.0 };                    // error: narrowing
    struct C {
      C(int i, double j);
    };
    C c1 = { 1, 2.2 };                  // calls constructor with arguments (1, 2.2)
    C c2 = { 1.1, 2 };                  // error: narrowing
    
    int j { 1 };                        // initialize to 1
    int k { };                          // initialize to 0
    
    end example
    ]
Within the initializer-list of a braced-init-list, the initializer-clauses, including any that result from pack expansions ([temp.variadic]), are evaluated in the order in which they appear.
That is, every value computation and side effect associated with a given initializer-clause is sequenced before every value computation and side effect associated with any initializer-clause that follows it in the comma-separated list of the initializer-list.
[Note
:
This evaluation ordering holds regardless of the semantics of the initialization; for example, it applies when the elements of the initializer-list are interpreted as arguments of a constructor call, even though ordinarily there are no sequencing constraints on the arguments of a call.
end note
]
An object of type std​::​initializer_­list<E> is constructed from an initializer list as if the implementation generated and materialized ([conv.rval]) a prvalue of type “array of N const E”, where N is the number of elements in the initializer list.
Each element of that array is copy-initialized with the corresponding element of the initializer list, and the std​::​initializer_­list<E> object is constructed to refer to that array.
[Note
:
A constructor or conversion function selected for the copy shall be accessible (Clause [class.access]) in the context of the initializer list.
end note
]
If a narrowing conversion is required to initialize any of the elements, the program is ill-formed.
[Example
:
struct X {
  X(std::initializer_list<double> v);
};
X x{ 1,2,3 };
The initialization will be implemented in a way roughly equivalent to this:
const double __a[3] = {double{1}, double{2}, double{3}};
X x(std::initializer_list<double>(__a, __a+3));
assuming that the implementation can construct an initializer_­list object with a pair of pointers.
end example
]
The array has the same lifetime as any other temporary object ([class.temporary]), except that initializing an initializer_­list object from the array extends the lifetime of the array exactly like binding a reference to a temporary.
[Example
:
typedef std::complex<double> cmplx;
std::vector<cmplx> v1 = { 1, 2, 3 };

void f() {
  std::vector<cmplx> v2{ 1, 2, 3 };
  std::initializer_list<int> i3 = { 1, 2, 3 };
}

struct A {
  std::initializer_list<int> i4;
  A() : i4{ 1, 2, 3 } {}  // ill-formed, would create a dangling reference
};
For v1 and v2, the initializer_­list object is a parameter in a function call, so the array created for { 1, 2, 3 } has full-expression lifetime.
For i3, the initializer_­list object is a variable, so the array persists for the lifetime of the variable.
For i4, the initializer_­list object is initialized in the constructor's ctor-initializer as if by binding a temporary array to a reference member, so the program is ill-formed ([class.base.init]).
end example
]
[Note
:
The implementation is free to allocate the array in read-only memory if an explicit array with the same initializer could be so allocated.
end note
]
A narrowing conversion is an implicit conversion
  • from a floating-point type to an integer type, or
  • from long double to double or float, or from double to float, except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly), or
  • from an integer type or unscoped enumeration type to a floating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type, or
  • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.
[Note
:
As indicated above, such conversions are not allowed at the top level in list-initializations.
end note
]
[Example
:
int x = 999;              // x is not a constant expression
const int y = 999;
const int z = 99;
char c1 = x;              // OK, though it might narrow (in this case, it does narrow)
char c2{x};               // error: might narrow
char c3{y};               // error: narrows (assuming char is 8 bits)
char c4{z};               // OK: no narrowing needed
unsigned char uc1 = {5};  // OK: no narrowing needed
unsigned char uc2 = {-1}; // error: narrows
unsigned int ui1 = {-1};  // error: narrows
signed int si1 =
  { (unsigned int)-1 };   // error: narrows
int ii = {2.0};           // error: narrows
float f1 { x };           // error: might narrow
float f2 { 7 };           // OK: 7 can be exactly represented as a float
int f(int);
int a[] =
  { 2, f(2), f(2.0) };    // OK: the double-to-int conversion is not at the top level
end example
]

12 Classes [class]

A class is a type.
Its name becomes a class-name ([class.name]) within its scope.
An object of a class consists of a (possibly empty) sequence of members and base class objects.
[Note
:
An unnamed class thus can't be final.
end note
]
A class-name is inserted into the scope in which it is declared immediately after the class-name is seen.
The class-name is also inserted into the scope of the class itself; this is known as the injected-class-name.
For purposes of access checking, the injected-class-name is treated as if it were a public member name.
A class-specifier is commonly referred to as a class definition.
A class is considered defined after the closing brace of its class-specifier has been seen even though its member functions are in general not yet defined.
The optional attribute-specifier-seq appertains to the class; the attributes in the attribute-specifier-seq are thereafter considered attributes of the class whenever it is named.
If a class is marked with the class-virt-specifier final and it appears as a class-or-decltype in a base-clause, the program is ill-formed.
Whenever a class-key is followed by a class-head-name, the identifier final, and a colon or left brace, final is interpreted as a class-virt-specifier.
[Example
:
struct A;
struct A final {};      // OK: definition of struct A,
                        // not value-initialization of variable final

struct X {
 struct C { constexpr operator int() { return 5; } };
 struct B final : C{};  // OK: definition of nested class B,
                        // not declaration of a bit-field member final
};
end example
]
Complete objects and member subobjects of class type shall have nonzero size.107
[Note
:
Class objects can be assigned, passed as arguments to functions, and returned by functions (except objects of classes for which copying or moving has been restricted; see [class.copy]).
Other plausible operators, such as equality comparison, can be defined by the user; see [over.oper].
end note
]
A union is a class defined with the class-key union; it holds at most one data member at a time ([class.union]).
[Note
:
Aggregates of class type are described in [dcl.init.aggr].
end note
]
  • where each copy constructor, move constructor, copy assignment operator, and move assignment operator ([class.copy], [over.ass]) is either deleted or trivial,
  • that has at least one non-deleted copy constructor, move constructor, copy assignment operator, or move assignment operator, and
  • that has a trivial, non-deleted destructor ([class.dtor]).
A trivial class is a class that is trivially copyable and has one or more default constructors ([class.ctor]), all of which are either trivial or deleted and at least one of which is not deleted.
[Note
:
In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes.
end note
]
A class S is a standard-layout class if it:
  • has no non-static data members of type non-standard-layout class (or array of such types) or reference,
  • has no virtual functions ([class.virtual]) and no virtual base classes ([class.mi]),
  • has the same access control (Clause [class.access]) for all non-static data members,
  • has no non-standard-layout base classes,
  • has at most one base class subobject of any given type,
  • has all non-static data members and bit-fields in the class and its base classes first declared in the same class, and
  • has no element of the set M(S) of types (defined below) as a base class.108
M(X) is defined as follows:
  • If X is a non-union class type with no (possibly inherited (Clause [class.derived])) non-static data members, the set M(X) is empty.
  • If X is a non-union class type whose first non-static data member has type (where said member may be an anonymous union), the set M(X) consists of and the elements of .
  • If X is a union type, the set M(X) is the union of all and the set containing all , where each is the type of the ith non-static data member of X.
  • If X is an array type with element type , the set M(X) consists of and the elements of .
  • If X is a non-class, non-array type, the set M(X) is empty.
[Note
:
M(X) is the set of the types of all non-base-class subobjects that are guaranteed in a standard-layout class to be at a zero offset in X.
end note
]
[Example
:
   struct B { int i; };         // standard-layout class
   struct C : B { };            // standard-layout class
   struct D : C { };            // standard-layout class
   struct E : D { char : 4; };  // not a standard-layout class

   struct Q {};
   struct S : Q { };
   struct T : Q { };
   struct U : S, T { };         // not a standard-layout class
end example
]
A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class.
A standard-layout union is a standard-layout class defined with the class-key union.
[Note
:
Standard-layout classes are useful for communicating with code written in other programming languages.
Their layout is specified in [class.mem].
end note
]
A POD struct109 is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types).
Similarly, a POD union is a union that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types).
A POD class is a class that is either a POD struct or a POD union.
[Example
:
struct N {          // neither trivial nor standard-layout
  int i;
  int j;
  virtual ~N();
};

struct T {          // trivial but not standard-layout
  int i;
private:
  int j;
};

struct SL {         // standard-layout but not trivial
  int i;
  int j;
  ~SL();
};

struct POD {        // both trivial and standard-layout
  int i;
  int j;
};
end example
]
If a class-head-name contains a nested-name-specifier, the class-specifier shall refer to a class that was previously declared directly in the class or namespace to which the nested-name-specifier refers, or in an element of the inline namespace set ([namespace.def]) of that namespace (i.e., not merely inherited or introduced by a using-declaration), and the class-specifier shall appear in a namespace enclosing the previous declaration.
In such cases, the nested-name-specifier of the class-head-name of the definition shall not begin with a decltype-specifier.
Base class subobjects are not so constrained.
This ensures that two subobjects that have the same class type and that belong to the same most derived object are not allocated at the same address ([expr.eq]).
The acronym POD stands for “plain old data”.

12.1 Class names [class.name]

A class definition introduces a new type.
[Example
:
struct X { int a; };
struct Y { int a; };
X a1;
Y a2;
int a3;
declares three variables of three different types.
This implies that
a1 = a2;                        // error: Y assigned to X
a1 = a3;                        // error: int assigned to X
are type mismatches, and that
int f(X);
int f(Y);
declare an overloaded (Clause [over]) function f() and not simply a single function f() twice.
For the same reason,
struct S { int a; };
struct S { int a; };            // error, double definition
is ill-formed because it defines S twice.
end example
]
A class declaration introduces the class name into the scope where it is declared and hides any class, variable, function, or other declaration of that name in an enclosing scope ([basic.scope]).
If a class name is declared in a scope where a variable, function, or enumerator of the same name is also declared, then when both declarations are in scope, the class can be referred to only using an elaborated-type-specifier ([basic.lookup.elab]).
[Example
:
struct stat {
  // ...
};

stat gstat;                     // use plain stat to define variable

int stat(struct stat*);         // redeclare stat as function

void f() {
  struct stat* ps;              // struct prefix needed to name struct stat
  stat(ps);                     // call stat()
}
end example
]
A declaration consisting solely of class-key identifier; is either a redeclaration of the name in the current scope or a forward declaration of the identifier as a class name.
It introduces the class name into the current scope.
[Example
:
struct s { int a; };

void g() {
  struct s;                     // hide global struct s with a block-scope declaration
  s* p;                         // refer to local struct s
  struct s { char* p; };        // define local struct s
  struct s;                     // redeclaration, has no effect
}
end example
]
[Note
:
Such declarations allow definition of classes that refer to each other.
[Example
:
class Vector;

class Matrix {
  // ...
  friend Vector operator*(const Matrix&, const Vector&);
};

class Vector {
  // ...
  friend Vector operator*(const Matrix&, const Vector&);
};
Declaration of friends is described in [class.friend], operator functions in [over.oper].
end example
]
end note
]
[Note
:
An elaborated-type-specifier ([dcl.type.elab]) can also be used as a type-specifier as part of a declaration.
It differs from a class declaration in that if a class of the elaborated name is in scope the elaborated name will refer to it.
end note
]
[Example
:
struct s { int a; };

void g(int s) {
  struct s* p = new struct s;   // global s
  p->a = s;                     // parameter s
}
end example
]
[Note
:
The declaration of a class name takes effect immediately after the identifier is seen in the class definition or elaborated-type-specifier.
For example,
class A * A;
first specifies A to be the name of a class and then redefines it as the name of a pointer to an object of that class.
This means that the elaborated form class A must be used to refer to the class.
Such artistry with names can be confusing and is best avoided.
end note
]
A typedef-name that names a class type, or a cv-qualified version thereof, is also a class-name.
If a typedef-name that names a cv-qualified class type is used where a class-name is required, the cv-qualifiers are ignored.
A typedef-name shall not be used as the identifier in a class-head.

12.2 Class members [class.mem]

The member-specification in a class definition declares the full set of members of the class; no member can be added elsewhere.
A direct member of a class X is a member of X that was first declared within the member-specification of X, including anonymous union objects ([class.union.anon]) and direct members thereof.
Members of a class are data members, member functions ([class.mfct]), nested types, enumerators, and member templates ([temp.mem]) and specializations thereof.
[Note
:
A specialization of a static data member template is a static data member.
A specialization of a member function template is a member function.
A specialization of a member class template is a nested class.
end note
]
A member-declaration does not declare new members of the class if it is
For any other member-declaration, each declared entity that is not an unnamed bit-field ([class.bit]) is a member of the class, and each such member-declaration shall either declare at least one member name of the class or declare at least one unnamed bit-field.
A data member is a non-function member introduced by a member-declarator.
A member function is a member that is a function.
Nested types are classes ([class.name], [class.nest]) and enumerations ([dcl.enum]) declared in the class and arbitrary types declared as members by use of a typedef declaration ([dcl.typedef]) or alias-declaration.
The enumerators of an unscoped enumeration ([dcl.enum]) defined in the class are members of the class.
A data member or member function may be declared static in its member-declaration, in which case it is a static member (see [class.static]) (a static data member ([class.static.data]) or static member function ([class.static.mfct]), respectively) of the class.
Any other data member or member function is a non-static member (a non-static data member or non-static member function ([class.mfct.non-static]), respectively).
[Note
:
A non-static data member of non-reference type is a member subobject of a class object ([intro.object]).
end note
]
A member shall not be declared twice in the member-specification, except that
[Note
:
A single name can denote several member functions provided their types are sufficiently different (Clause [over]).
end note
]
A class is considered a completely-defined object type ([basic.types]) (or complete type) at the closing } of the class-specifier.
Within the class member-specification, the class is regarded as complete within function bodies, default arguments, noexcept-specifiers, and default member initializers (including such things in nested classes).
Otherwise it is regarded as incomplete within its own class member-specification.
In a member-declarator, an = immediately following the declarator is interpreted as introducing a pure-specifier if the declarator-id has function type, otherwise it is interpreted as introducing a brace-or-equal-initializer.
[Example
:
struct S {
  using T = void();
  T * p = 0;        // OK: brace-or-equal-initializer
  virtual T f = 0;  // OK: pure-specifier
};
end example
]
A brace-or-equal-initializer shall appear only in the declaration of a data member.
(For static data members, see [class.static.data]; for non-static data members, see [class.base.init] and [dcl.init.aggr]).
A brace-or-equal-initializer for a non-static data member specifies a default member initializer for the member, and shall not directly or indirectly cause the implicit definition of a defaulted default constructor for the enclosing class or the exception specification of that constructor.
A member shall not be declared with the extern storage-class-specifier.
Within a class definition, a member shall not be declared with the thread_­local storage-class-specifier unless also declared static.
The decl-specifier-seq may be omitted in constructor, destructor, and conversion function declarations only; when declaring another kind of member the decl-specifier-seq shall contain a type-specifier that is not a cv-qualifier.
The member-declarator-list can be omitted only after a class-specifier or an enum-specifier or in a friend declaration ([class.friend]).
A pure-specifier shall be used only in the declaration of a virtual function ([class.virtual]) that is not a friend declaration.
The optional attribute-specifier-seq in a member-declaration appertains to each of the entities declared by the member-declarators; it shall not appear if the optional member-declarator-list is omitted.
A virt-specifier-seq shall contain at most one of each virt-specifier.
A virt-specifier-seq shall appear only in the declaration of a virtual member function ([class.virtual]).
Non-static data members shall not have incomplete types.
In particular, a class C shall not contain a non-static member of class C, but it can contain a pointer or reference to an object of class C.
[Note
:
See [expr.prim] for restrictions on the use of non-static data members and non-static member functions.
end note
]
[Note
:
The type of a non-static member function is an ordinary function type, and the type of a non-static data member is an ordinary object type.
There are no special member function types or data member types.
end note
]
[Example
:
A simple example of a class definition is
struct tnode {
  char tword[20];
  int count;
  tnode* left;
  tnode* right;
};
which contains an array of twenty characters, an integer, and two pointers to objects of the same type.
Once this definition has been given, the declaration
tnode s, *sp;
declares s to be a tnode and sp to be a pointer to a tnode.
With these declarations, sp->count refers to the count member of the object to which sp points; s.left refers to the left subtree pointer of the object s; and s.right->tword[0] refers to the initial character of the tword member of the right subtree of s.
end example
]
Non-static data members of a (non-union) class with the same access control (Clause [class.access]) are allocated so that later members have higher addresses within a class object.
The order of allocation of non-static data members with different access control is unspecified (Clause [class.access]).
Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions ([class.virtual]) and virtual base classes ([class.mi]).
If T is the name of a class, then each of the following shall have a name different from T:
  • every static data member of class T;
  • every member function of class T
    [Note
    :
    This restriction does not apply to constructors, which do not have names ([class.ctor])
    end note
    ]
    ;
  • every member of class T that is itself a type;
  • every member template of class T;
  • every enumerator of every member of class T that is an unscoped enumerated type; and
  • every member of every anonymous union that is a member of class T.
In addition, if class T has a user-declared constructor ([class.ctor]), every non-static data member of class T shall have a name different from T.
The common initial sequence of two standard-layout struct (Clause [class]) types is the longest sequence of non-static data members and bit-fields in declaration order, starting with the first such entity in each of the structs, such that corresponding entities have layout-compatible types and either neither entity is a bit-field or both are bit-fields with the same width.
[Example
:
  struct A { int a; char b; };
  struct B { const int b1; volatile char b2; };
  struct C { int c; unsigned : 0; char b; };
  struct D { int d; char b : 4; };
  struct E { unsigned int e; char b; };
The common initial sequence of A and B comprises all members of either class.
The common initial sequence of A and C and of A and D comprises the first member in each case.
The common initial sequence of A and E is empty.
end example
]
Two standard-layout struct (Clause [class]) types are layout-compatible classes if their common initial sequence comprises all members and bit-fields of both classes ([basic.types]).
Two standard-layout unions are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in any order) have layout-compatible types ([basic.types]).
In a standard-layout union with an active member ([class.union]) of struct type T1, it is permitted to read a non-static data member m of another union member of struct type T2 provided m is part of the common initial sequence of T1 and T2; the behavior is as if the corresponding member of T1 were nominated.
[Example
:
struct T1 { int a, b; };
struct T2 { int c; double d; };
union U { T1 t1; T2 t2; };
int f() {
  U u = { { 1, 2 } };   // active member is t1
  return u.t2.c;        // OK, as if u.t1.a were nominated
}
end example
]
[Note
:
Reading a volatile object through a non-volatile glvalue has undefined behavior ([dcl.type.cv]).
end note
]
If a standard-layout class object has any non-static data members, its address is the same as the address of its first non-static data member.
Otherwise, its address is the same as the address of its first base class subobject (if any).
[Note
:
There might therefore be unnamed padding within a standard-layout struct object, but not at its beginning, as necessary to achieve appropriate alignment.
end note
]
[Note
:
The object and its first subobject are pointer-interconvertible ([basic.compound], [expr.static.cast]).
end note
]

12.2.1 Member functions [class.mfct]

A member function may be defined ([dcl.fct.def]) in its class definition, in which case it is an inline member function ([dcl.inline]), or it may be defined outside of its class definition if it has already been declared but not defined in its class definition.
A member function definition that appears outside of the class definition shall appear in a namespace scope enclosing the class definition.
Except for member function definitions that appear outside of a class definition, and except for explicit specializations of member functions of class templates and member function templates ([temp.spec]) appearing outside of the class definition, a member function shall not be redeclared.
An inline member function (whether static or non-static) may also be defined outside of its class definition provided either its declaration in the class definition or its definition outside of the class definition declares the function as inline or constexpr.
[Note
:
Member functions of a class in namespace scope have the linkage of that class.
Member functions of a local class ([class.local]) have no linkage.
end note
]
[Note
:
There can be at most one definition of a non-inline member function in a program.
There may be more than one inline member function definition in a program.
end note
]
If the definition of a member function is lexically outside its class definition, the member function name shall be qualified by its class name using the ​::​ operator.
[Note
:
A name used in a member function definition (that is, in the parameter-declaration-clause including the default arguments ([dcl.fct.default]) or in the member function body) is looked up as described in [basic.lookup].
end note
]
[Example
:
struct X {
  typedef int T;
  static T count;
  void f(T);
};
void X::f(T t = count) { }
The member function f of class X is defined in global scope; the notation X​::​f specifies that the function f is a member of class X and in the scope of class X.
In the function definition, the parameter type T refers to the typedef member T declared in class X and the default argument count refers to the static data member count declared in class X.
end example
]
[Note
:
A static local variable or local type in a member function always refers to the same entity, whether or not the member function is inline.
end note
]
Previously declared member functions may be mentioned in friend declarations.
Member functions of a local class shall be defined inline in their class definition, if they are defined at all.
[Note
:
A member function can be declared (but not defined) using a typedef for a function type.
The resulting member function has exactly the same type as it would have if the function declarator were provided explicitly, see [dcl.fct].
For example,
typedef void fv();
typedef void fvc() const;
struct S {
  fv memfunc1;      // equivalent to: void memfunc1();
  void memfunc2();
  fvc memfunc3;     // equivalent to: void memfunc3() const;
};
fv  S::* pmfv1 = &S::memfunc1;
fv  S::* pmfv2 = &S::memfunc2;
fvc S::* pmfv3 = &S::memfunc3;
Also see [temp.arg].
end note
]

12.2.2 Non-static member functions [class.mfct.non-static]

A non-static member function may be called for an object of its class type, or for an object of a class derived (Clause [class.derived]) from its class type, using the class member access syntax ([expr.ref], [over.match.call]).
A non-static member function may also be called directly using the function call syntax ([expr.call], [over.match.call]) from within the body of a member function of its class or of a class derived from its class.
If a non-static member function of a class X is called for an object that is not of type X, or of a type derived from X, the behavior is undefined.
When an id-expression ([expr.prim]) that is not part of a class member access syntax ([expr.ref]) and not used to form a pointer to member ([expr.unary.op]) is used in a member of class X in a context where this can be used ([expr.prim.this]), if name lookup ([basic.lookup]) resolves the name in the id-expression to a non-static non-type member of some class C, and if either the id-expression is potentially evaluated or C is X or a base class of X, the id-expression is transformed into a class member access expression ([expr.ref]) using (*this) ([class.this]) as the postfix-expression to the left of the . operator.
[Note
:
If C is not X or a base class of X, the class member access expression is ill-formed.
end note
]
Similarly during name lookup, when an unqualified-id ([expr.prim]) used in the definition of a member function for class X resolves to a static member, an enumerator or a nested type of class X or of a base class of X, the unqualified-id is transformed into a qualified-id ([expr.prim]) in which the nested-name-specifier names the class of the member function.
These transformations do not apply in the template definition context ([temp.dep.type]).
[Example
:
struct tnode {
  char tword[20];
  int count;
  tnode* left;
  tnode* right;
  void set(const char*, tnode* l, tnode* r);
};

void tnode::set(const char* w, tnode* l, tnode* r) {
  count = strlen(w)+1;
  if (sizeof(tword)<=count)
      perror("tnode string too long");
  strcpy(tword,w);
  left = l;
  right = r;
}

void f(tnode n1, tnode n2) {
  n1.set("abc",&n2,0);
  n2.set("def",0,0);
}
In the body of the member function tnode​::​set, the member names tword, count, left, and right refer to members of the object for which the function is called.
Thus, in the call n1.set("abc",&n2,0), tword refers to n1.tword, and in the call n2.set("def",0,0), it refers to n2.tword.
The functions strlen, perror, and strcpy are not members of the class tnode and should be declared elsewhere.110
end example
]
A non-static member function may be declared const, volatile, or const volatile.
These cv-qualifiers affect the type of the this pointer ([class.this]).
They also affect the function type ([dcl.fct]) of the member function; a member function declared const is a const member function, a member function declared volatile is a volatile member function and a member function declared const volatile is a const volatile member function.
[Example
:
struct X {
  void g() const;
  void h() const volatile;
};
X​::​g is a const member function and X​::​h is a const volatile member function.
end example
]
A non-static member function may be declared with a ref-qualifier ([dcl.fct]); see [over.match.funcs].
A non-static member function may be declared virtual ([class.virtual]) or pure virtual ([class.abstract]).
See, for example, <cstring> ([c.strings]).

12.2.2.1 The this pointer [class.this]

In the body of a non-static ([class.mfct]) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called.
The type of this in a member function of a class X is X*.
If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*.
[Note
:
Thus in a const member function, the object for which the function is called is accessed through a const access path.
end note
]
[Example
:
struct s {
  int a;
  int f() const;
  int g() { return a++; }
  int h() const { return a++; } // error
};

int s::f() const { return a; }
The a++ in the body of s​::​h is ill-formed because it tries to modify (a part of) the object for which s​::​h() is called.
This is not allowed in a const member function because this is a pointer to const; that is, *this has const type.
end example
]
Similarly, volatile semantics ([dcl.type.cv]) apply in volatile member functions when accessing the object and its non-static data members.
A cv-qualified member function can be called on an object-expression ([expr.ref]) only if the object-expression is as cv-qualified or less-cv-qualified than the member function.
[Example
:
void k(s& x, const s& y) {
  x.f();
  x.g();
  y.f();
  y.g();                        // error
}
The call y.g() is ill-formed because y is const and s​::​g() is a non-const member function, that is, s​::​g() is less-qualified than the object-expression y.
end example
]
Constructors ([class.ctor]) and destructors ([class.dtor]) shall not be declared const, volatile or const volatile.
[Note
:
However, these functions can be invoked to create and destroy objects with cv-qualified types, see [class.ctor] and [class.dtor].
end note
]

12.2.3 Static members [class.static]

A static member s of class X may be referred to using the qualified-id expression X​::​s; it is not necessary to use the class member access syntax ([expr.ref]) to refer to a static member.
A static member may be referred to using the class member access syntax, in which case the object expression is evaluated.
[Example
:
struct process {
  static void reschedule();
};
process& g();

void f() {
  process::reschedule();        // OK: no object necessary
  g().reschedule();             // g() is called
}
end example
]
A static member may be referred to directly in the scope of its class or in the scope of a class derived (Clause [class.derived]) from its class; in this case, the static member is referred to as if a qualified-id expression was used, with the nested-name-specifier of the qualified-id naming the class scope from which the static member is referenced.
[Example
:
int g();
struct X {
  static int g();
};
struct Y : X {
  static int i;
};
int Y::i = g();                 // equivalent to Y​::​g();
end example
]
If an unqualified-id ([expr.prim]) is used in the definition of a static member following the member's declarator-id, and name lookup ([basic.lookup.unqual]) finds that the unqualified-id refers to a static member, enumerator, or nested type of the member's class (or of a base class of the member's class), the unqualified-id is transformed into a qualified-id expression in which the nested-name-specifier names the class scope from which the member is referenced.
[Note
:
See [expr.prim] for restrictions on the use of non-static data members and non-static member functions.
end note
]
Static members obey the usual class member access rules (Clause [class.access]).
When used in the declaration of a class member, the static specifier shall only be used in the member declarations that appear within the member-specification of the class definition.
[Note
:
It cannot be specified in member declarations that appear in namespace scope.
end note
]

12.2.3.1 Static member functions [class.static.mfct]

[Note
:
The rules described in [class.mfct] apply to static member functions.
end note
]
[Note
:
A static member function does not have a this pointer ([class.this]).
end note
]
A static member function shall not be virtual.
There shall not be a static and a non-static member function with the same name and the same parameter types ([over.load]).
A static member function shall not be declared const, volatile, or const volatile.

12.2.3.2 Static data members [class.static.data]

A static data member is not part of the subobjects of a class.
If a static data member is declared thread_­local there is one copy of the member per thread.
If a static data member is not declared thread_­local there is one copy of the data member that is shared by all the objects of the class.
The declaration of a non-inline static data member in its class definition is not a definition and may be of an incomplete type other than cv void.
The definition for a static data member that is not defined inline in the class definition shall appear in a namespace scope enclosing the member's class definition.
In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the ​::​ operator.
The initializer expression in the definition of a static data member is in the scope of its class ([basic.scope.class]).
[Example
:
class process {
  static process* run_chain;
  static process* running;
};

process* process::running = get_main();
process* process::run_chain = running;
The static data member run_­chain of class process is defined in global scope; the notation process​::​run_­chain specifies that the member run_­chain is a member of class process and in the scope of class process.
In the static data member definition, the initializer expression refers to the static data member running of class process.
end example
]
[Note
:
Once the static data member has been defined, it exists even if no objects of its class have been created.
[Example
:
In the example above, run_­chain and running exist even if no objects of class process are created by the program.
end example
]
end note
]
If a non-volatile non-inline const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression ([expr.const]).
The member shall still be defined in a namespace scope if it is odr-used ([basic.def.odr]) in the program and the namespace scope definition shall not contain an initializer.
An inline static data member may be defined in the class definition and may specify a brace-or-equal-initializer.
If the member is declared with the constexpr specifier, it may be redeclared in namespace scope with no initializer (this usage is deprecated; see [depr.static_constexpr]).
Declarations of other static data members shall not specify a brace-or-equal-initializer.
[Note
:
There shall be exactly one definition of a static data member that is odr-used ([basic.def.odr]) in a program; no diagnostic is required.
end note
]
Unnamed classes and classes contained directly or indirectly within unnamed classes shall not contain static data members.
[Note
:
Static data members of a class in namespace scope have the linkage of that class ([basic.link]).
A local class cannot have static data members ([class.local]).
end note
]
Static data members are initialized and destroyed exactly like non-local variables ([basic.start.static], [basic.start.dynamic], [basic.start.term]).
A static data member shall not be mutable ([dcl.stc]).

12.2.4 Bit-fields [class.bit]

A member-declarator of the form
identifier attribute-specifier-seq : constant-expression
specifies a bit-field; its length is set off from the bit-field name by a colon.
The optional attribute-specifier-seq appertains to the entity being declared.
The bit-field attribute is not part of the type of the class member.
The constant-expression shall be an integral constant expression with a value greater than or equal to zero.
The value of the integral constant expression may be larger than the number of bits in the object representation ([basic.types]) of the bit-field's type; in such cases the extra bits are used as padding bits and do not participate in the value representation ([basic.types]) of the bit-field.
Allocation of bit-fields within a class object is implementation-defined.
Alignment of bit-fields is implementation-defined.
Bit-fields are packed into some addressable allocation unit.
[Note
:
Bit-fields straddle allocation units on some machines and not on others.
Bit-fields are assigned right-to-left on some machines, left-to-right on others.
end note
]
A declaration for a bit-field that omits the identifier declares an unnamed bit-field.
Unnamed bit-fields are not members and cannot be initialized.
[Note
:
An unnamed bit-field is useful for padding to conform to externally-imposed layouts.
end note
]
As a special case, an unnamed bit-field with a width of zero specifies alignment of the next bit-field at an allocation unit boundary.
Only when declaring an unnamed bit-field may the value of the constant-expression be equal to zero.
A bit-field shall not be a static member.
A bit-field shall have integral or enumeration type ([basic.fundamental]).
A bool value can successfully be stored in a bit-field of any nonzero size.
The address-of operator & shall not be applied to a bit-field, so there are no pointers to bit-fields.
A non-const reference shall not be bound to a bit-field ([dcl.init.ref]).
[Note
:
If the initializer for a reference of type const T& is an lvalue that refers to a bit-field, the reference is bound to a temporary initialized to hold the value of the bit-field; the reference is not bound to the bit-field directly.
end note
]
If the value true or false is stored into a bit-field of type bool of any size (including a one bit bit-field), the original bool value and the value of the bit-field shall compare equal.
If the value of an enumerator is stored into a bit-field of the same enumeration type and the number of bits in the bit-field is large enough to hold all the values of that enumeration type ([dcl.enum]), the original enumerator value and the value of the bit-field shall compare equal.
[Example
:
enum BOOL { FALSE=0, TRUE=1 };
struct A {
  BOOL b:1;
};
A a;
void f() {
  a.b = TRUE;
  if (a.b == TRUE)              // yields true
    { /* ... */ }
}
end example
]

12.2.5 Nested class declarations [class.nest]

A class can be declared within another class.
A class declared within another is called a nested class.
The name of a nested class is local to its enclosing class.
The nested class is in the scope of its enclosing class.
[Note
:
See [expr.prim] for restrictions on the use of non-static data members and non-static member functions.
end note
]
[Example
:
int x;
int y;

struct enclose {
  int x;
  static int s;

  struct inner {
    void f(int i) {
      int a = sizeof(x);        // OK: operand of sizeof is an unevaluated operand
      x = i;                    // error: assign to enclose​::​x
      s = i;                    // OK: assign to enclose​::​s
      ::x = i;                  // OK: assign to global x
      y = i;                    // OK: assign to global y
    }
    void g(enclose* p, int i) {
      p->x = i;                 // OK: assign to enclose​::​x
    }
  };
};

inner* p = 0;                   // error: inner not in scope
end example
]
Member functions and static data members of a nested class can be defined in a namespace scope enclosing the definition of their class.
[Example
:
struct enclose {
  struct inner {
    static int x;
    void f(int i);
  };
};

int enclose::inner::x = 1;

void enclose::inner::f(int i) { /* ... */ }
end example
]
If class X is defined in a namespace scope, a nested class Y may be declared in class X and later defined in the definition of class X or be later defined in a namespace scope enclosing the definition of class X.
[Example
:
class E {
  class I1;                     // forward declaration of nested class
  class I2;
  class I1 { };                 // definition of nested class
};
class E::I2 { };                // definition of nested class
end example
]
Like a member function, a friend function ([class.friend]) defined within a nested class is in the lexical scope of that class; it obeys the same rules for name binding as a static member function of that class ([class.static]), but it has no special access rights to members of an enclosing class.

12.2.6 Nested type names [class.nested.type]

Type names obey exactly the same scope rules as other names.
In particular, type names defined within a class definition cannot be used outside their class without qualification.
[Example
:
struct X {
  typedef int I;
  class Y { /* ... */ };
  I a;
};

I b;                            // error
Y c;                            // error
X::Y d;                         // OK
X::I e;                         // OK
end example
]

12.3 Unions [class.union]

In a union, a non-static data member is active if its name refers to an object whose lifetime has begun and has not ended ([basic.life]).
At most one of the non-static data members of an object of union type can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time.
[Note
:
One special guarantee is made in order to simplify the use of unions: If a standard-layout union contains several standard-layout structs that share a common initial sequence ([class.mem]), and if a non-static data member of an object of this standard-layout union type is active and is one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of the standard-layout struct members; see [class.mem].
end note
]
The size of a union is sufficient to contain the largest of its non-static data members.
Each non-static data member is allocated as if it were the sole member of a struct.
[Note
:
A union object and its non-static data members are pointer-interconvertible ([basic.compound], [expr.static.cast]).
As a consequence, all non-static data members of a union object have the same address.
end note
]
A union can have member functions (including constructors and destructors), but it shall not have virtual ([class.virtual]) functions.
A union shall not have base classes.
A union shall not be used as a base class.
If a union contains a non-static data member of reference type the program is ill-formed.
[Note
:
Absent default member initializers ([class.mem]), if any non-static data member of a union has a non-trivial default constructor ([class.ctor]), copy constructor ([class.copy]), move constructor ([class.copy]), copy assignment operator ([class.copy]), move assignment operator ([class.copy]), or destructor ([class.dtor]), the corresponding member function of the union must be user-provided or it will be implicitly deleted ([dcl.fct.def.delete]) for the union.
end note
]
[Example
:
Consider the following union:
union U {
  int i;
  float f;
  std::string s;
};
Since std​::​string ([string.classes]) declares non-trivial versions of all of the special member functions, U will have an implicitly deleted default constructor, copy/move constructor, copy/move assignment operator, and destructor.
To use U, some or all of these member functions must be user-provided.
end example
]
When the left operand of an assignment operator involves a member access expression ([expr.ref]) that nominates a union member, it may begin the lifetime of that union member, as described below.
For an expression E, define the set S(E) of subexpressions of E as follows:
  • If E is of the form A.B, S(E) contains the elements of S(A), and also contains A.B if B names a union member of a non-class, non-array type, or of a class type with a trivial default constructor that is not deleted, or an array of such types.
  • If E is of the form A[B] and is interpreted as a built-in array subscripting operator, S(E) is S(A) if A is of array type, S(B) if B is of array type, and empty otherwise.
  • Otherwise, S(E) is empty.
In an assignment expression of the form E1 = E2 that uses either the built-in assignment operator ([expr.ass]) or a trivial assignment operator ([class.copy]), for each element X of S(E1), if modification of X would have undefined behavior under [basic.life], an object of the type of X is implicitly created in the nominated storage; no initialization is performed and the beginning of its lifetime is sequenced after the value computation of the left and right operands and before the assignment.
[Note
:
This ends the lifetime of the previously-active member of the union, if any ([basic.life]).
end note
]
[Example
:
union A { int x; int y[4]; };
struct B { A a; };
union C { B b; int k; };
int f() {
  C c;                  // does not start lifetime of any union member
  c.b.a.y[3] = 4;       // OK: S(c.b.a.y[3]) contains c.b and c.b.a.y;
                        // creates objects to hold union members c.b and c.b.a.y
  return c.b.a.y[3];    // OK: c.b.a.y refers to newly created object (see [basic.life])
}

struct X { const int a; int b; };
union Y { X x; int k; };
void g() {
  Y y = { { 1, 2 } };   // OK, y.x is active union member ([class.mem])
  int n = y.x.a;
  y.k = 4;              // OK: ends lifetime of y.x, y.k is active member of union
  y.x.b = n;            // undefined behavior: y.x.b modified outside its lifetime,
                        // S(y.x.b) is empty because X's default constructor is deleted,
                        // so union member y.x's lifetime does not implicitly start
}
end example
]
[Note
:
In general, one must use explicit destructor calls and placement new-expression to change the active member of a union.
end note
]
[Example
:
Consider an object u of a union type U having non-static data members m of type M and n of type N.
If M has a non-trivial destructor and N has a non-trivial constructor (for instance, if they declare or inherit virtual functions), the active member of u can be safely switched from m to n using the destructor and placement new-expression as follows:
u.m.~M();
new (&u.n) N;
end example
]

12.3.1 Anonymous unions [class.union.anon]

A union of the form
union { member-specification } ;
is called an anonymous union; it defines an unnamed type and an unnamed object of that type called an anonymous union object.
Each member-declaration in the member-specification of an anonymous union shall either define a non-static data member or be a static_assert-declaration.
[Note
:
Nested types, anonymous unions, and functions cannot be declared within an anonymous union.
end note
]
The names of the members of an anonymous union shall be distinct from the names of any other entity in the scope in which the anonymous union is declared.
For the purpose of name lookup, after the anonymous union definition, the members of the anonymous union are considered to have been defined in the scope in which the anonymous union is declared.
[Example
:
void f() {
  union { int a; const char* p; };
  a = 1;
  p = "Jennifer";
}
Here a and p are used like ordinary (non-member) variables, but since they are union members they have the same address.
end example
]
Anonymous unions declared in a named namespace or in the global namespace shall be declared static.
Anonymous unions declared at block scope shall be declared with any storage class allowed for a block-scope variable, or with no storage class.
A storage class is not allowed in a declaration of an anonymous union in a class scope.
An anonymous union shall not have private or protected members (Clause [class.access]).
An anonymous union shall not have member functions.
A union for which objects, pointers, or references are declared is not an anonymous union.
[Example
:
void f() {
  union { int aa; char* p; } obj, *ptr = &obj;
  aa = 1;           // error
  ptr->aa = 1;      // OK
}
The assignment to plain aa is ill-formed since the member name is not visible outside the union, and even if it were visible, it is not associated with any particular object.
end example
]
[Note
:
Initialization of unions with no user-declared constructors is described in [dcl.init.aggr].
end note
]
A union-like class is a union or a class that has an anonymous union as a direct member.
A union-like class X has a set of variant members.
If X is a union, a non-static data member of X that is not an anonymous union is a variant member of X.
In addition, a non-static data member of an anonymous union that is a member of X is also a variant member of X.
At most one variant member of a union may have a default member initializer.
[Example
:
union U {
  int x = 0;
  union {
    int k;
  };
  union {
    int z;
    int y = 1;      // error: initialization for second variant member of U
  };
};
end example
]

12.4 Local class declarations [class.local]

A class can be declared within a function definition; such a class is called a local class.
The name of a local class is local to its enclosing scope.
The local class is in the scope of the enclosing scope, and has the same access to names outside the function as does the enclosing function.
Declarations in a local class shall not odr-use ([basic.def.odr]) a variable with automatic storage duration from an enclosing scope.
[Example
:
int x;
void f() {
  static int s;
  int x;
  const int N = 5;
  extern int q();

  struct local {
    int g() { return x; }       // error: odr-use of automatic variable x
    int h() { return s; }       // OK
    int k() { return ::x; }     // OK
    int l() { return q(); }     // OK
    int m() { return N; }       // OK: not an odr-use
    int* n() { return &N; }     // error: odr-use of automatic variable N
  };
}

local* p = 0;                   // error: local not in scope
end example
]
An enclosing function has no special access to members of the local class; it obeys the usual access rules (Clause [class.access]).
Member functions of a local class shall be defined within their class definition, if they are defined at all.
If class X is a local class a nested class Y may be declared in class X and later defined in the definition of class X or be later defined in the same scope as the definition of class X.
A class nested within a local class is a local class.
A local class shall not have static data members.

13 Derived classes [class.derived]

A class-or-decltype shall denote a class type that is not an incompletely defined class (Clause [class]).
The class denoted by the class-or-decltype of a base-specifier is called a direct base class for the class being defined.
During the lookup for a base class name, non-type names are ignored ([basic.scope.hiding]).
If the name found is not a class-name, the program is ill-formed.
A class B is a base class of a class D if it is a direct base class of D or a direct base class of one of D's base classes.
A class is an indirect base class of another if it is a base class but not a direct base class.
A class is said to be (directly or indirectly) derived from its (direct or indirect) base classes.
[Note
:
See Clause [class.access] for the meaning of access-specifier.
end note
]
Unless redeclared in the derived class, members of a base class are also considered to be members of the derived class.
Members of a base class other than constructors are said to be inherited by the derived class.
Constructors of a base class can also be inherited as described in [namespace.udecl].
Inherited members can be referred to in expressions in the same manner as other members of the derived class, unless their names are hidden or ambiguous ([class.member.lookup]).
[Note
:
The scope resolution operator ​::​ ([expr.prim]) can be used to refer to a direct or indirect base member explicitly.
This allows access to a name that has been redeclared in the derived class.
A derived class can itself serve as a base class subject to access control; see [class.access.base].
A pointer to a derived class can be implicitly converted to a pointer to an accessible unambiguous base class ([conv.ptr]).
An lvalue of a derived class type can be bound to a reference to an accessible unambiguous base class ([dcl.init.ref]).
end note
]
The base-specifier-list specifies the type of the base class subobjects contained in an object of the derived class type.
[Example
:
struct Base {
  int a, b, c;
};
struct Derived : Base {
  int b;
};
struct Derived2 : Derived {
  int c;
};
Here, an object of class Derived2 will have a subobject of class Derived which in turn will have a subobject of class Base.
end example
]
A base-specifier followed by an ellipsis is a pack expansion ([temp.variadic]).
The order in which the base class subobjects are allocated in the most derived object ([intro.object]) is unspecified.
[Note
:
A derived class and its base class subobjects can be represented by a directed acyclic graph (DAG) where an arrow means “directly derived from”.
An arrow need not have a physical representation in memory.
A DAG of subobjects is often referred to as a “subobject lattice”.
dag Base Base Derived1 Derived1 Derived1->Base Derived2 Derived2 Derived2->Derived1
Figure 2 — Directed acyclic graph
end note
]
[Note
:
Initialization of objects representing base classes can be specified in constructors; see [class.base.init].
end note
]
[Note
:
A base class subobject might have a layout ([basic.stc]) different from the layout of a most derived object of the same type.
A base class subobject might have a polymorphic behavior ([class.cdtor]) different from the polymorphic behavior of a most derived object of the same type.
A base class subobject may be of zero size (Clause [class]); however, two subobjects that have the same class type and that belong to the same most derived object must not be allocated at the same address ([expr.eq]).
end note
]

13.1 Multiple base classes [class.mi]

A class can be derived from any number of base classes.
[Note
:
The use of more than one direct base class is often called multiple inheritance.
end note
]
[Example
:
class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class D : public A, public B, public C { /* ... */ };
end example
]
[Note
:
The order of derivation is not significant except as specified by the semantics of initialization by constructor ([class.base.init]), cleanup ([class.dtor]), and storage layout ([class.mem], [class.access.spec]).
end note
]
A class shall not be specified as a direct base class of a derived class more than once.
[Note
:
A class can be an indirect base class more than once and can be a direct and an indirect base class.
There are limited things that can be done with such a class.
The non-static data members and member functions of the direct base class cannot be referred to in the scope of the derived class.
However, the static members, enumerations and types can be unambiguously referred to.
end note
]
[Example
:
class X { /* ... */ };
class Y : public X, public X { /* ... */ };             // ill-formed
class L { public: int next;  /* ... */ };
class A : public L { /* ... */ };
class B : public L { /* ... */ };
class C : public A, public B { void f(); /* ... */ };   // well-formed
class D : public A, public L { void f(); /* ... */ };   // well-formed
end example
]
A base class specifier that does not contain the keyword virtual specifies a non-virtual base class.
A base class specifier that contains the keyword virtual specifies a virtual base class.
For each distinct occurrence of a non-virtual base class in the class lattice of the most derived class, the most derived object ([intro.object]) shall contain a corresponding distinct base class subobject of that type.
For each distinct base class that is specified virtual, the most derived object shall contain a single base class subobject of that type.
[Note
:
For an object of class type C, each distinct occurrence of a (non-virtual) base class L in the class lattice of C corresponds one-to-one with a distinct L subobject within the object of type C.
Given the class C defined above, an object of class C will have two subobjects of class L as shown in Figure [fig:nonvirt].
nonvirt L1 L L2 L A A A->L1 B B B->L2 C C C->A C->B
Figure 3 — Non-virtual base
In such lattices, explicit qualification can be used to specify which subobject is meant.
The body of function C​::​f could refer to the member next of each L subobject:
void C::f() { A::next = B::next; }      // well-formed
Without the A​::​ or B​::​ qualifiers, the definition of C​::​f above would be ill-formed because of ambiguity ([class.member.lookup]).
end note
]
[Note
:
In contrast, consider the case with a virtual base class:
class V { /* ... */ };
class A : virtual public V { /* ... */ };
class B : virtual public V { /* ... */ };
class C : public A, public B { /* ... */ };
virt V V A A A->V B B B->V C C C->A C->B
Figure 4 — Virtual base
For an object c of class type C, a single subobject of type V is shared by every base class subobject of c that has a virtual base class of type V.
Given the class C defined above, an object of class C will have one subobject of class V, as shown in Figure [fig:virt].
end note
]
[Note
:
A class can have both virtual and non-virtual base classes of a given type.
class B { /* ... */ };
class X : virtual public B { /* ... */ };
class Y : virtual public B { /* ... */ };
class Z : public B { /* ... */ };
class AA : public X, public Y, public Z { /* ... */ };
For an object of class AA, all virtual occurrences of base class B in the class lattice of AA correspond to a single B subobject within the object of type AA, and every other occurrence of a (non-virtual) base class B in the class lattice of AA corresponds one-to-one with a distinct B subobject within the object of type AA.
Given the class AA defined above, class AA has two subobjects of class B: Z's B and the virtual B shared by X and Y, as shown in Figure [fig:virtnonvirt].
virtnonvirt B1 B B2 B AA AA X X AA->X Y Y AA->Y Z Z AA->Z X->B1 Y->B1 Z->B2
Figure 5 — Virtual and non-virtual base
end note
]

13.2 Member name lookup [class.member.lookup]

Member name lookup determines the meaning of a name (id-expression) in a class scope ([basic.scope.class]).
Name lookup can result in an ambiguity, in which case the program is ill-formed.
For an id-expression, name lookup begins in the class scope of this; for a qualified-id, name lookup begins in the scope of the nested-name-specifier.
Name lookup takes place before access control ([basic.lookup], Clause [class.access]).
The following steps define the result of name lookup for a member name f in a class scope C.
The lookup set for f in C, called , consists of two component sets: the declaration set, a set of members named f; and the subobject set, a set of subobjects where declarations of these members (possibly including using-declarations) were found.
In the declaration set, using-declarations are replaced by the set of designated members that are not hidden or overridden by members of the derived class ([namespace.udecl]), and type declarations (including injected-class-names) are replaced by the types they designate.
is calculated as follows:
If C contains a declaration of the name f, the declaration set contains every declaration of f declared in C that satisfies the requirements of the language construct in which the lookup occurs.
[Note
:
Looking up a name in an elaborated-type-specifier ([basic.lookup.elab]) or base-specifier (Clause [class.derived]), for instance, ignores all non-type declarations, while looking up a name in a nested-name-specifier ([basic.lookup.qual]) ignores function, variable, and enumerator declarations.
As another example, looking up a name in a using-declaration ([namespace.udecl]) includes the declaration of a class or enumeration that would ordinarily be hidden by another declaration of that name in the same scope.
end note
]
If the resulting declaration set is not empty, the subobject set contains C itself, and calculation is complete.
Otherwise (i.e., C does not contain a declaration of f or the resulting declaration set is empty), is initially empty.
If C has base classes, calculate the lookup set for f in each direct base class subobject , and merge each such lookup set in turn into .
The following steps define the result of merging lookup set into the intermediate :
  • If each of the subobject members of is a base class subobject of at least one of the subobject members of , or if is empty, is unchanged and the merge is complete.
    Conversely, if each of the subobject members of is a base class subobject of at least one of the subobject members of , or if is empty, the new is a copy of .
  • Otherwise, if the declaration sets of and differ, the merge is ambiguous: the new is a lookup set with an invalid declaration set and the union of the subobject sets.
    In subsequent merges, an invalid declaration set is considered different from any other.
  • Otherwise, the new is a lookup set with the shared set of declarations and the union of the subobject sets.
The result of name lookup for f in C is the declaration set of .
If it is an invalid set, the program is ill-formed.
[Example
:
struct A { int x; };                    // S(x,A) = { { A​::​x }, { A } }
struct B { float x; };                  // S(x,B) = { { B​::​x }, { B } }
struct C: public A, public B { };       // S(x,C) = { invalid, { A in C, B in C } }
struct D: public virtual C { };         // S(x,D) = S(x,C)
struct E: public virtual C { char x; }; // S(x,E) = { { E​::​x }, { E } }
struct F: public D, public E { };       // S(x,F) = S(x,E)
int main() {
  F f;
  f.x = 0;                              // OK, lookup finds E​::​x
}
is unambiguous because the A and B base class subobjects of D are also base class subobjects of E, so is discarded in the first merge step.
end example
]
If the name of an overloaded function is unambiguously found, overload resolution ([over.match]) also takes place before access control.
Ambiguities can often be resolved by qualifying a name with its class name.
[Example
:
struct A {
  int f();
};
struct B {
  int f();
};
struct C : A, B {
  int f() { return A::f() + B::f(); }
};
end example
]
[Note
:
A static member, a nested type or an enumerator defined in a base class T can unambiguously be found even if an object has more than one base class subobject of type T.
Two base class subobjects share the non-static member subobjects of their common virtual base classes.
end note
]
[Example
:
struct V {
  int v;
};
struct A {
  int a;
  static int   s;
  enum { e };
};
struct B : A, virtual V { };
struct C : A, virtual V { };
struct D : B, C { };

void f(D* pd) {
  pd->v++;          // OK: only one v (virtual)
  pd->s++;          // OK: only one s (static)
  int i = pd->e;    // OK: only one e (enumerator)
  pd->a++;          // error, ambiguous: two as in D
}
end example
]
[Note
:
When virtual base classes are used, a hidden declaration can be reached along a path through the subobject lattice that does not pass through the hiding declaration.
This is not an ambiguity.
The identical use with non-virtual base classes is an ambiguity; in that case there is no unique instance of the name that hides all the others.
end note
]
[Example
:
struct V { int f();  int x; };
struct W { int g();  int y; };
struct B : virtual V, W {
  int f();  int x;
  int g();  int y;
};
struct C : virtual V, W { };

struct D : B, C { void glorp(); };
virt W1 W V V W2 W B B B->W1 B->V C C C->V C->W2 D D D->B D->C
Figure 6 — Name lookup
The names declared in V and the left-hand instance of W are hidden by those in B, but the names declared in the right-hand instance of W are not hidden at all.
void D::glorp() {
  x++;              // OK: B​::​x hides V​::​x
  f();              // OK: B​::​f() hides V​::​f()
  y++;              // error: B​::​y and C's W​::​y
  g();              // error: B​::​g() and C's W​::​g()
}
end example
]
An explicit or implicit conversion from a pointer to or an expression designating an object of a derived class to a pointer or reference to one of its base classes shall unambiguously refer to a unique object representing the base class.
[Example
:
struct V { };
struct A { };
struct B : A, virtual V { };
struct C : A, virtual V { };
struct D : B, C { };

void g() {
  D d;
  B* pb = &d;
  A* pa = &d;       // error, ambiguous: C's A or B's A?
  V* pv = &d;       // OK: only one V subobject
}
end example
]
[Note
:
Even if the result of name lookup is unambiguous, use of a name found in multiple subobjects might still be ambiguous ([conv.mem], [expr.ref], [class.access.base]).
end note
]
[Example
:
struct B1 {
  void f();
  static void f(int);
  int i;
};
struct B2 {
  void f(double);
};
struct I1: B1 { };
struct I2: B1 { };

struct D: I1, I2, B2 {
  using B1::f;
  using B2::f;
  void g() {
    f();                        // Ambiguous conversion of this
    f(0);                       // Unambiguous (static)
    f(0.0);                     // Unambiguous (only one B2)
    int B1::* mpB1 = &D::i;     // Unambiguous
    int D::* mpD = &D::i;       // Ambiguous conversion
  }
};
end example
]

13.3 Virtual functions [class.virtual]

[Note
:
Virtual functions support dynamic binding and object-oriented programming.
end note
]
A class that declares or inherits a virtual function is called a polymorphic class.
If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list ([dcl.fct]), cv-qualification, and ref-qualifier (or absence of same) as Base​::​vf is declared, then Derived​::​vf is also virtual (whether or not it is so declared) and it overrides111 Base​::​vf.
For convenience we say that any virtual function overrides itself.
A virtual member function C​::​vf of a class object S is a final overrider unless the most derived class ([intro.object]) of which S is a base class subobject (if any) declares or inherits another member function that overrides vf.
In a derived class, if a virtual member function of a base class subobject has more than one final overrider the program is ill-formed.
[Example
:
struct A {
  virtual void f();
};
struct B : virtual A {
  virtual void f();
};
struct C : B , virtual A {
  using A::f;
};

void foo() {
  C c;
  c.f();              // calls B​::​f, the final overrider
  c.C::f();           // calls A​::​f because of the using-declaration
}
end example
]
[Example
:
struct A { virtual void f(); };
struct B : A { };
struct C : A { void f(); };
struct D : B, C { };  // OK: A​::​f and C​::​f are the final overriders
                      // for the B and C subobjects, respectively
end example
]
[Note
:
A virtual member function does not have to be visible to be overridden, for example,
struct B {
  virtual void f();
};
struct D : B {
  void f(int);
};
struct D2 : D {
  void f();
};
the function f(int) in class D hides the virtual function f() in its base class B; D​::​f(int) is not a virtual function.
However, f() declared in class D2 has the same name and the same parameter list as B​::​f(), and therefore is a virtual function that overrides the function B​::​f() even though B​::​f() is not visible in class D2.
end note
]
If a virtual function f in some class B is marked with the virt-specifier final and in a class D derived from B a function D​::​f overrides B​::​f, the program is ill-formed.
[Example
:
struct B {
  virtual void f() const final;
};

struct D : B {
  void f() const;     // error: D​::​f attempts to override final B​::​f
};
end example
]
If a virtual function is marked with the virt-specifier override and does not override a member function of a base class, the program is ill-formed.
[Example
:
struct B {
  virtual void f(int);
};

struct D : B {
  virtual void f(long) override;  // error: wrong signature overriding B​::​f
  virtual void f(int) override;   // OK
};
end example
]
Even though destructors are not inherited, a destructor in a derived class overrides a base class destructor declared virtual; see [class.dtor] and [class.free].
The return type of an overriding function shall be either identical to the return type of the overridden function or covariant with the classes of the functions.
If a function D​::​f overrides a function B​::​f, the return types of the functions are covariant if they satisfy the following criteria:
  • both are pointers to classes, both are lvalue references to classes, or both are rvalue references to classes112
  • the class in the return type of B​::​f is the same class as the class in the return type of D​::​f, or is an unambiguous and accessible direct or indirect base class of the class in the return type of D​::​f
  • both pointers or references have the same cv-qualification and the class type in the return type of D​::​f has the same cv-qualification as or less cv-qualification than the class type in the return type of B​::​f.
If the class type in the covariant return type of D​::​f differs from that of B​::​f, the class type in the return type of D​::​f shall be complete at the point of declaration of D​::​f or shall be the class type D.
When the overriding function is called as the final overrider of the overridden function, its result is converted to the type returned by the (statically chosen) overridden function ([expr.call]).
[Example
:
class B { };
class D : private B { friend class Derived; };
struct Base {
  virtual void vf1();
  virtual void vf2();
  virtual void vf3();
  virtual B*   vf4();
  virtual B*   vf5();
  void f();
};

struct No_good : public Base {
  D*  vf4();        // error: B (base class of D) inaccessible
};

class A;
struct Derived : public Base {
    void vf1();     // virtual and overrides Base​::​vf1()
    void vf2(int);  // not virtual, hides Base​::​vf2()
    char vf3();     // error: invalid difference in return type only
    D*   vf4();     // OK: returns pointer to derived class
    A*   vf5();     // error: returns pointer to incomplete class
    void f();
};

void g() {
  Derived d;
  Base* bp = &d;                // standard conversion:
                                // Derived* to Base*
  bp->vf1();                    // calls Derived​::​vf1()
  bp->vf2();                    // calls Base​::​vf2()
  bp->f();                      // calls Base​::​f() (not virtual)
  B*  p = bp->vf4();            // calls Derived​::​pf() and converts the
                                // result to B*
  Derived*  dp = &d;
  D*  q = dp->vf4();            // calls Derived​::​pf() and does not
                                // convert the result to B*
  dp->vf2();                    // ill-formed: argument mismatch
}
end example
]
[Note
:
The interpretation of the call of a virtual function depends on the type of the object for which it is called (the dynamic type), whereas the interpretation of a call of a non-virtual member function depends only on the type of the pointer or reference denoting that object (the static type) ([expr.call]).
end note
]
[Note
:
The virtual specifier implies membership, so a virtual function cannot be a non-member ([dcl.fct.spec]) function.
Nor can a virtual function be a static member, since a virtual function call relies on a specific object for determining which function to invoke.
A virtual function declared in one class can be declared a friend in another class.
end note
]
A virtual function declared in a class shall be defined, or declared pure ([class.abstract]) in that class, or both; no diagnostic is required ([basic.def.odr]).
[Example
:
Here are some uses of virtual functions with multiple base classes:
struct A {
  virtual void f();
};

struct B1 : A {                 // note non-virtual derivation
  void f();
};

struct B2 : A {
  void f();
};

struct D : B1, B2 {             // D has two separate A subobjects
};

void foo() {
  D   d;
//   A*  ap = &d;                  // would be ill-formed: ambiguous
  B1*  b1p = &d;
  A*   ap = b1p;
  D*   dp = &d;
  ap->f();                      // calls D​::​B1​::​f
  dp->f();                      // ill-formed: ambiguous
}
In class D above there are two occurrences of class A and hence two occurrences of the virtual member function A​::​f.
The final overrider of B1​::​A​::​f is B1​::​f and the final overrider of B2​::​A​::​f is B2​::​f.
end example
]
[Example
:
The following example shows a function that does not have a unique final overrider:
struct A {
  virtual void f();
};

struct VB1 : virtual A {        // note virtual derivation
  void f();
};

struct VB2 : virtual A {
  void f();
};

struct Error : VB1, VB2 {       // ill-formed
};

struct Okay : VB1, VB2 {
  void f();
};
Both VB1​::​f and VB2​::​f override A​::​f but there is no overrider of both of them in class Error.
This example is therefore ill-formed.
Class Okay is well formed, however, because Okay​::​f is a final overrider.
end example
]
[Example
:
The following example uses the well-formed classes from above.
struct VB1a : virtual A {       // does not declare f
};

struct Da : VB1a, VB2 {
};

void foe() {
  VB1a*  vb1ap = new Da;
  vb1ap->f();                   // calls VB2​::​f
}
end example
]
Explicit qualification with the scope operator ([expr.prim]) suppresses the virtual call mechanism.
[Example
:
class B { public: virtual void f(); };
class D : public B { public: void f(); };

void D::f() { /* ... */ B::f(); }
Here, the function call in D​::​f really does call B​::​f and not D​::​f.
end example
]
A function with a deleted definition ([dcl.fct.def]) shall not override a function that does not have a deleted definition.
Likewise, a function that does not have a deleted definition shall not override a function with a deleted definition.
A function with the same name but a different parameter list (Clause [over]) as a virtual function is not necessarily virtual and does not override.
The use of the virtual specifier in the declaration of an overriding function is legal but redundant (has empty semantics).
Access control (Clause [class.access]) is not considered in determining overriding.
Multi-level pointers to classes or references to multi-level pointers to classes are not allowed.

13.4 Abstract classes [class.abstract]

[Note
:
The abstract class mechanism supports the notion of a general concept, such as a shape, of which only more concrete variants, such as circle and square, can actually be used.
An abstract class can also be used to define an interface for which derived classes provide a variety of implementations.
end note
]
An abstract class is a class that can be used only as a base class of some other class; no objects of an abstract class can be created except as subobjects of a class derived from it.
A class is abstract if it has at least one pure virtual function.
[Note
:
Such a function might be inherited: see below.
end note
]
A virtual function is specified pure by using a pure-specifier in the function declaration in the class definition.
A pure virtual function need be defined only if called with, or as if with ([class.dtor]), the qualified-id syntax ([expr.prim]).
[Example
:
class point { /* ... */ };
class shape {                   // abstract class
  point center;
public:
  point where() { return center; }
  void move(point p) { center=p; draw(); }
  virtual void rotate(int) = 0; // pure virtual
  virtual void draw() = 0;      // pure virtual
};
end example
]
[Note
:
A function declaration cannot provide both a pure-specifier and a definition
end note
]
[Example
:
struct C {
  virtual void f() = 0 { };     // ill-formed
};
end example
]
An abstract class shall not be used as a parameter type, as a function return type, or as the type of an explicit conversion.
Pointers and references to an abstract class can be declared.
[Example
:
shape x;                        // error: object of abstract class
shape* p;                       // OK
shape f();                      // error
void g(shape);                  // error
shape& h(shape&);               // OK
end example
]
A class is abstract if it contains or inherits at least one pure virtual function for which the final overrider is pure virtual.
[Example
:
class ab_circle : public shape {
  int radius;
public:
  void rotate(int) { }
  // ab_­circle​::​draw() is a pure virtual
};
Since shape​::​draw() is a pure virtual function ab_­circle​::​draw() is a pure virtual by default.
The alternative declaration,
class circle : public shape {
  int radius;
public:
  void rotate(int) { }
  void draw();                  // a definition is required somewhere
};
would make class circle non-abstract and a definition of circle​::​draw() must be provided.
end example
]
[Note
:
An abstract class can be derived from a class that is not abstract, and a pure virtual function may override a virtual function which is not pure.
end note
]
Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call ([class.virtual]) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined.

14 Member access control [class.access]

A member of a class can be
  • private; that is, its name can be used only by members and friends of the class in which it is declared.
  • protected; that is, its name can be used only by members and friends of the class in which it is declared, by classes derived from that class, and by their friends (see [class.protected]).
  • public; that is, its name can be used anywhere without access restriction.
A member of a class can also access all the names to which the class has access.
A local class of a member function may access the same names that the member function itself may access.113
Members of a class defined with the keyword class are private by default.
Members of a class defined with the keywords struct or union are public by default.
[Example
:
class X {
  int a;            // X​::​a is private by default
};

struct S {
  int a;            // S​::​a is public by default
};
end example
]
Access control is applied uniformly to all names, whether the names are referred to from declarations or expressions.
[Note
:
Access control applies to names nominated by friend declarations ([class.friend]) and using-declarations ([namespace.udecl]).
end note
]
In the case of overloaded function names, access control is applied to the function selected by overload resolution.
[Note
:
Because access control applies to names, if access control is applied to a typedef name, only the accessibility of the typedef name itself is considered.
The accessibility of the entity referred to by the typedef is not considered.
For example,
class A {
  class B { };
public:
  typedef B BB;
};

void f() {
  A::BB x;          // OK, typedef name A​::​BB is public
  A::B y;           // access error, A​::​B is private
}
end note
]
It should be noted that it is access to members and base classes that is controlled, not their visibility.
Names of members are still visible, and implicit conversions to base classes are still considered, when those members and base classes are inaccessible.
The interpretation of a given construct is established without regard to access control.
If the interpretation established makes use of inaccessible member names or base classes, the construct is ill-formed.
All access controls in Clause [class.access] affect the ability to access a class member name from the declaration of a particular entity, including parts of the declaration preceding the name of the entity being declared and, if the entity is a class, the definitions of members of the class appearing outside the class's member-specification.
[Note
:
This access also applies to implicit references to constructors, conversion functions, and destructors.
end note
]
[Example
:
class A {
  typedef int I;    // private member
  I f();
  friend I g(I);
  static I x;
  template<int> struct Q;
  template<int> friend struct R;
protected:
    struct B { };
};

A::I A::f() { return 0; }
A::I g(A::I p = A::x);
A::I g(A::I p) { return 0; }
A::I A::x = 0;
template<A::I> struct A::Q { };
template<A::I> struct R { };

struct D: A::B, A { };
Here, all the uses of A​::​I are well-formed because A​::​f, A​::​x, and A​::​Q are members of class A and g and R are friends of class A.
This implies, for example, that access checking on the first use of A​::​I must be deferred until it is determined that this use of A​::​I is as the return type of a member of class A.
Similarly, the use of A​::​B as a base-specifier is well-formed because D is derived from A, so checking of base-specifiers must be deferred until the entire base-specifier-list has been seen.
end example
]
The names in a default argument ([dcl.fct.default]) are bound at the point of declaration, and access is checked at that point rather than at any points of use of the default argument.
Access checking for default arguments in function templates and in member functions of class templates is performed as described in [temp.inst].
The names in a default template-argument ([temp.param]) have their access checked in the context in which they appear rather than at any points of use of the default template-argument.
[Example
:
class B { };
template <class T> class C {
protected:
  typedef T TT;
};

template <class U, class V = typename U::TT>
class D : public U { };

D <C<B> >* d;       // access error, C​::​TT is protected
end example
]
Access permissions are thus transitive and cumulative to nested and local classes.

14.1 Access specifiers [class.access.spec]

Member declarations can be labeled by an access-specifier:
access-specifier : member-specification
An access-specifier specifies the access rules for members following it until the end of the class or until another access-specifier is encountered.
[Example
:
class X {
  int a;            // X​::​a is private by default: class used
public:
  int b;            // X​::​b is public
  int c;            // X​::​c is public
};
end example
]
Any number of access specifiers is allowed and no particular order is required.
[Example
:
struct S {
  int a;            // S​::​a is public by default: struct used
protected:
  int b;            // S​::​b is protected
private:
  int c;            // S​::​c is private
public:
  int d;            // S​::​d is public
};
end example
]
[Note
:
The effect of access control on the order of allocation of data members is described in [class.mem].
end note
]
When a member is redeclared within its class definition, the access specified at its redeclaration shall be the same as at its initial declaration.
[Example
:
struct S {
  class A;
  enum E : int;
private:
  class A { };        // error: cannot change access
  enum E: int { e0 }; // error: cannot change access
};
end example
]
[Note
:
In a derived class, the lookup of a base class name will find the injected-class-name instead of the name of the base class in the scope in which it was declared.
The injected-class-name might be less accessible than the name of the base class in the scope in which it was declared.
end note
]
[Example
:
class A { };
class B : private A { };
class C : public B {
  A* p;             // error: injected-class-name A is inaccessible
  ::A* q;           // OK
};
end example
]

14.2 Accessibility of base classes and base class members [class.access.base]

If a class is declared to be a base class (Clause [class.derived]) for another class using the public access specifier, the public members of the base class are accessible as public members of the derived class and protected members of the base class are accessible as protected members of the derived class.
If a class is declared to be a base class for another class using the protected access specifier, the public and protected members of the base class are accessible as protected members of the derived class.
If a class is declared to be a base class for another class using the private access specifier, the public and protected members of the base class are accessible as private members of the derived class114.
In the absence of an access-specifier for a base class, public is assumed when the derived class is defined with the class-key struct and private is assumed when the class is defined with the class-key class.
[Example
:
class B { /* ... */ };
class D1 : private B { /* ... */ };
class D2 : public B { /* ... */ };
class D3 : B { /* ... */ };             // B private by default
struct D4 : public B { /* ... */ };
struct D5 : private B { /* ... */ };
struct D6 : B { /* ... */ };            // B public by default
class D7 : protected B { /* ... */ };
struct D8 : protected B { /* ... */ };
Here B is a public base of D2, D4, and D6, a private base of D1, D3, and D5, and a protected base of D7 and D8.
end example
]
[Note
:
A member of a private base class might be inaccessible as an inherited member name, but accessible directly.
Because of the rules on pointer conversions ([conv.ptr]) and explicit casts ([expr.cast]), a conversion from a pointer to a derived class to a pointer to an inaccessible base class might be ill-formed if an implicit conversion is used, but well-formed if an explicit cast is used.
For example,
class B {
public:
  int mi;                       // non-static member
  static int si;                // static member
};
class D : private B {
};
class DD : public D {
  void f();
};

void DD::f() {
  mi = 3;                       // error: mi is private in D
  si = 3;                       // error: si is private in D
  ::B  b;
  b.mi = 3;                     // OK (b.mi is different from this->mi)
  b.si = 3;                     // OK (b.si is different from this->si)
  ::B::si = 3;                  // OK
  ::B* bp1 = this;              // error: B is a private base class
  ::B* bp2 = (::B*)this;        // OK with cast
  bp2->mi = 3;                  // OK: access through a pointer to B.
}
end note
]
A base class B of N is accessible at R, if
  • an invented public member of B would be a public member of N, or
  • R occurs in a member or friend of class N, and an invented public member of B would be a private or protected member of N, or
  • R occurs in a member or friend of a class P derived from N, and an invented public member of B would be a private or protected member of P, or
  • there exists a class S such that B is a base class of S accessible at R and S is a base class of N accessible at R.
[Example
:
class B {
public:
  int m;
};

class S: private B {
  friend class N;
};

class N: private S {
  void f() {
    B* p = this;    // OK because class S satisfies the fourth condition above: B is a base class of N
                    // accessible in f() because B is an accessible base class of S and S is an accessible
                    // base class of N.
  }
};
end example
]
If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class ([conv.ptr], [conv.mem]).
[Note
:
It follows that members and friends of a class X can implicitly convert an X* to a pointer to a private or protected immediate base class of X.
end note
]
The access to a member is affected by the class in which the member is named.
This naming class is the class in which the member name was looked up and found.
[Note
:
This class can be explicit, e.g., when a qualified-id is used, or implicit, e.g., when a class member access operator ([expr.ref]) is used (including cases where an implicit “this->” is added).
If both a class member access operator and a qualified-id are used to name the member (as in p->T​::​m), the class naming the member is the class denoted by the nested-name-specifier of the qualified-id (that is, T).
end note
]
A member m is accessible at the point R when named in class N if
  • m as a member of N is public, or
  • m as a member of N is private, and R occurs in a member or friend of class N, or
  • m as a member of N is protected, and R occurs in a member or friend of class N, or in a member of a class P derived from N, where m as a member of P is public, private, or protected, or
  • there exists a base class B of N that is accessible at R, and m is accessible at R when named in class B.
    [Example
    :
    class B;
    class A {
    private:
      int i;
      friend void f(B*);
    };
    class B : public A { };
    void f(B* p) {
      p->i = 1;         // OK: B* can be implicitly converted to A*, and f has access to i in A
    }
    end example
    ]
If a class member access operator, including an implicit “this->”, is used to access a non-static data member or non-static member function, the reference is ill-formed if the left operand (considered as a pointer in the “.” operator case) cannot be implicitly converted to a pointer to the naming class of the right operand.
[Note
:
This requirement is in addition to the requirement that the member be accessible as named.
end note
]
As specified previously in Clause [class.access], private members of a base class remain inaccessible even to derived classes unless friend declarations within the base class definition are used to grant access explicitly.

14.3 Friends [class.friend]

A friend of a class is a function or class that is given permission to use the private and protected member names from the class.
A class specifies its friends, if any, by way of friend declarations.
Such declarations give special access rights to the friends, but they do not make the nominated friends members of the befriending class.
[Example
:
The following example illustrates the differences between members and friends:
class X {
  int a;
  friend void friend_set(X*, int);
public:
  void member_set(int);
};

void friend_set(X* p, int i) { p->a = i; }
void X::member_set(int i) { a = i; }

void f() {
  X obj;
  friend_set(&obj,10);
  obj.member_set(10);
}
end example
]
Declaring a class to be a friend implies that the names of private and protected members from the class granting friendship can be accessed in the base-specifiers and member declarations of the befriended class.
[Example
:
class A {
  class B { };
  friend class X;
};

struct X : A::B {               // OK: A​::​B accessible to friend
  A::B mx;                      // OK: A​::​B accessible to member of friend
  class Y {
    A::B my;                    // OK: A​::​B accessible to nested member of friend
  };
};
end example
]
[Example
:
class X {
  enum { a=100 };
  friend class Y;
};

class Y {
  int v[X::a];                  // OK, Y is a friend of X
};

class Z {
  int v[X::a];                  // error: X​::​a is private
};
end example
]
A class shall not be defined in a friend declaration.
[Example
:
class A {
  friend class B { };           // error: cannot define class in friend declaration
};
end example
]
A friend declaration that does not declare a function shall have one of the following forms:
friend elaborated-type-specifier ;
friend simple-type-specifier ;
friend typename-specifier ;
[Note
:
A friend declaration may be the declaration in a template-declaration (Clause [temp], [temp.friend]).
end note
]
If the type specifier in a friend declaration designates a (possibly cv-qualified) class type, that class is declared as a friend; otherwise, the friend declaration is ignored.
[Example
:
class C;
typedef C Ct;

class X1 {
  friend C;                     // OK: class C is a friend
};

class X2 {
  friend Ct;                    // OK: class C is a friend
  friend D;                     // error: no type-name D in scope
  friend class D;               // OK: elaborated-type-specifier declares new class
};

template <typename T> class R {
  friend T;
};

R<C> rc;                        // class C is a friend of R<C>
R<int> Ri;                      // OK: "friend int;" is ignored
end example
]
A function first declared in a friend declaration has the linkage of the namespace of which it is a member ([basic.link]).
Otherwise, the function retains its previous linkage ([dcl.stc]).
When a friend declaration refers to an overloaded name or operator, only the function specified by the parameter types becomes a friend.
A member function of a class X can be a friend of a class Y.
[Example
:
class Y {
  friend char* X::foo(int);
  friend X::X(char);            // constructors can be friends
  friend X::~X();               // destructors can be friends
};
end example
]
A function can be defined in a friend declaration of a class if and only if the class is a non-local class ([class.local]), the function name is unqualified, and the function has namespace scope.
[Example
:
class M {
  friend void f() { }           // definition of global f, a friend of M,
                                // not the definition of a member function
};
end example
]
Such a function is implicitly an inline function ([dcl.inline]).
A friend function defined in a class is in the (lexical) scope of the class in which it is defined.
A friend function defined outside the class is not ([basic.lookup.unqual]).
No storage-class-specifier shall appear in the decl-specifier-seq of a friend declaration.
A name nominated by a friend declaration shall be accessible in the scope of the class containing the friend declaration.
The meaning of the friend declaration is the same whether the friend declaration appears in the private, protected or public ([class.mem]) portion of the class member-specification.
Friendship is neither inherited nor transitive.
[Example
:
class A {
  friend class B;
  int a;
};

class B {
  friend class C;
};

class C  {
  void f(A* p) {
    p->a++;         // error: C is not a friend of A despite being a friend of a friend
  }
};

class D : public B  {
  void f(A* p) {
    p->a++;         // error: D is not a friend of A despite being derived from a friend
  }
};
end example
]
If a friend declaration appears in a local class ([class.local]) and the name specified is an unqualified name, a prior declaration is looked up without considering scopes that are outside the innermost enclosing non-class scope.
For a friend function declaration, if there is no prior declaration, the program is ill-formed.
For a friend class declaration, if there is no prior declaration, the class that is specified belongs to the innermost enclosing non-class scope, but if it is subsequently referenced, its name is not found by name lookup until a matching declaration is provided in the innermost enclosing non-class scope.
[Example
:
class X;
void a();
void f() {
  class Y;
  extern void b();
  class A {
  friend class X;   // OK, but X is a local class, not ​::​X
  friend class Y;   // OK
  friend class Z;   // OK, introduces local class Z
  friend void a();  // error, ​::​a is not considered
  friend void b();  // OK
  friend void c();  // error
  };
  X* px;            // OK, but ​::​X is found
  Z* pz;            // error, no Z is found
}
end example
]

14.4 Protected member access [class.protected]

An additional access check beyond those described earlier in Clause [class.access] is applied when a non-static data member or non-static member function is a protected member of its naming class ([class.access.base])115 As described earlier, access to a protected member is granted because the reference occurs in a friend or member of some class C.
If the access is to form a pointer to member ([expr.unary.op]), the nested-name-specifier shall denote C or a class derived from C.
All other accesses involve a (possibly implicit) object expression ([expr.ref]).
In this case, the class of the object expression shall be C or a class derived from C.
[Example
:
class B {
protected:
  int i;
  static int j;
};

class D1 : public B {
};

class D2 : public B {
  friend void fr(B*,D1*,D2*);
  void mem(B*,D1*);
};

void fr(B* pb, D1* p1, D2* p2) {
  pb->i = 1;                    // ill-formed
  p1->i = 2;                    // ill-formed
  p2->i = 3;                    // OK (access through a D2)
  p2->B::i = 4;                 // OK (access through a D2, even though naming class is B)
  int B::* pmi_B = &B::i;       // ill-formed
  int B::* pmi_B2 = &D2::i;     // OK (type of &D2​::​i is int B​::​*)
  B::j = 5;                     // ill-formed (not a friend of naming class B)
  D2::j = 6;                    // OK (because refers to static member)
}

void D2::mem(B* pb, D1* p1) {
  pb->i = 1;                    // ill-formed
  p1->i = 2;                    // ill-formed
  i = 3;                        // OK (access through this)
  B::i = 4;                     // OK (access through this, qualification ignored)
  int B::* pmi_B = &B::i;       // ill-formed
  int B::* pmi_B2 = &D2::i;     // OK
  j = 5;                        // OK (because j refers to static member)
  B::j = 6;                     // OK (because B​::​j refers to static member)
}

void g(B* pb, D1* p1, D2* p2) {
  pb->i = 1;                    // ill-formed
  p1->i = 2;                    // ill-formed
  p2->i = 3;                    // ill-formed
}
end example
]
This additional check does not apply to other members, e.g., static data members or enumerator member constants.

14.5 Access to virtual functions [class.access.virt]

The access rules (Clause [class.access]) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it.
[Example
:
class B {
public:
  virtual int f();
};

class D : public B {
private:
  int f();
};

void f() {
  D d;
  B* pb = &d;
  D* pd = &d;

  pb->f();                      // OK: B​::​f() is public, D​::​f() is invoked
  pd->f();                      // error: D​::​f() is private
}
end example
]
Access is checked at the call point using the type of the expression used to denote the object for which the member function is called (B* in the example above).
The access of the member function in the class in which it was defined (D in the example above) is in general not known.

14.6 Multiple access [class.paths]

If a name can be reached by several paths through a multiple inheritance graph, the access is that of the path that gives most access.
[Example
:
class W { public: void f(); };
class A : private virtual W { };
class B : public virtual W { };
class C : public A, public B {
  void f() { W::f(); }          // OK
};
Since W​::​f() is available to C​::​f() along the public path through B, access is allowed.
end example
]

14.7 Nested classes [class.access.nest]

A nested class is a member and as such has the same access rights as any other member.
The members of an enclosing class have no special access to members of a nested class; the usual access rules (Clause [class.access]) shall be obeyed.
[Example
:
class E {
  int x;
  class B { };

  class I {
    B b;                        // OK: E​::​I can access E​::​B
    int y;
    void f(E* p, int i) {
      p->x = i;                 // OK: E​::​I can access E​::​x
    }
  };

  int g(I* p) {
    return p->y;                // error: I​::​y is private
  }
};
end example
]

15 Special member functions [special]

The default constructor ([class.ctor]), copy constructor and copy assignment operator ([class.copy]), move constructor and move assignment operator ([class.copy]), and destructor ([class.dtor]) are special member functions.
[Note
:
The implementation will implicitly declare these member functions for some class types when the program does not explicitly declare them.
The implementation will implicitly define them if they are odr-used ([basic.def.odr]).
end note
]
An implicitly-declared special member function is declared at the closing } of the class-specifier.
Programs shall not define implicitly-declared special member functions.
Programs may explicitly refer to implicitly-declared special member functions.
[Example
:
A program may explicitly call, take the address of, or form a pointer to member to an implicitly-declared special member function.
struct A { };                   // implicitly declared A​::​operator=
struct B : A {
  B& operator=(const B &);
};
B& B::operator=(const B& s) {
  this->A::operator=(s);        // well formed
  return *this;
}
end example
]
[Note
:
The special member functions affect the way objects of class type are created, copied, moved, and destroyed, and how values can be converted to values of other types.
Often such special member functions are called implicitly.
end note
]
Special member functions obey the usual access rules (Clause [class.access]).
[Example
:
Declaring a constructor protected ensures that only derived classes and friends can create objects using it.
end example
]
For a class, its non-static data members, its non-virtual direct base classes, and, if the class is not abstract ([class.abstract]), its virtual base classes are called its potentially constructed subobjects.

15.1 Constructors [class.ctor]

Constructors do not have names.
In a declaration of a constructor, the declarator is a function declarator ([dcl.fct]) of the form
ptr-declarator ( parameter-declaration-clause ) noexcept-specifier attribute-specifier-seq
where the ptr-declarator consists solely of an id-expression, an optional attribute-specifier-seq, and optional surrounding parentheses, and the id-expression has one of the following forms:
The class-name shall not be a typedef-name.
In a constructor declaration, each decl-specifier in the optional decl-specifier-seq shall be friend, inline, explicit, or constexpr.
[Example
:
struct S {
  S();              // declares the constructor
};

S::S() { }          // defines the constructor
end example
]
A constructor is used to initialize objects of its class type.
Because constructors do not have names, they are never found during name lookup; however an explicit type conversion using the functional notation ([expr.type.conv]) will cause a constructor to be called to initialize an object.
[Note
:
For initialization of objects of class type see [class.init].
end note
]
A constructor can be invoked for a const, volatile or const volatile object.
const and volatile semantics ([dcl.type.cv]) are not applied on an object under construction.
They come into effect when the constructor for the most derived object ([intro.object]) ends.
A default constructor for a class X is a constructor of class X for which each parameter that is not a function parameter pack has a default argument (including the case of a constructor with no parameters).
If there is no user-declared constructor for class X, a non-explicit constructor having no parameters is implicitly declared as defaulted ([dcl.fct.def]).
An implicitly-declared default constructor is an inline public member of its class.
A defaulted default constructor for class X is defined as deleted if:
  • X is a union that has a variant member with a non-trivial default constructor and no variant member of X has a default member initializer,
  • X is a non-union class that has a variant member M with a non-trivial default constructor and no variant member of the anonymous union containing M has a default member initializer,
  • any non-static data member with no default member initializer ([class.mem]) is of reference type,
  • any non-variant non-static data member of const-qualified type (or array thereof) with no brace-or-equal-initializer does not have a user-provided default constructor,
  • X is a union and all of its variant members are of const-qualified type (or array thereof),
  • X is a non-union class and all members of any anonymous union member are of const-qualified type (or array thereof),
  • any potentially constructed subobject, except for a non-static data member with a brace-or-equal-initializer, has class type M (or array thereof) and either M has no default constructor or overload resolution ([over.match]) as applied to find M's corresponding constructor results in an ambiguity or in a function that is deleted or inaccessible from the defaulted default constructor, or
  • any potentially constructed subobject has a type with a destructor that is deleted or inaccessible from the defaulted default constructor.
A default constructor is trivial if it is not user-provided and if:
  • its class has no virtual functions ([class.virtual]) and no virtual base classes ([class.mi]), and
  • no non-static data member of its class has a default member initializer ([class.mem]), and
  • all the direct base classes of its class have trivial default constructors, and
  • for all the non-static data members of its class that are of class type (or array thereof), each such class has a trivial default constructor.
Otherwise, the default constructor is non-trivial.
A default constructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used ([basic.def.odr]) to create an object of its class type ([intro.object]) or when it is explicitly defaulted after its first declaration.
The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with no ctor-initializer and an empty compound-statement.
If that user-written default constructor would be ill-formed, the program is ill-formed.
If that user-written default constructor would satisfy the requirements of a constexpr constructor ([dcl.constexpr]), the implicitly-defined default constructor is constexpr.
Before the defaulted default constructor for a class is implicitly defined, all the non-user-provided default constructors for its base classes and its non-static data members shall have been implicitly defined.
[Note
:
An implicitly-declared default constructor has an exception specification ([except.spec]).
An explicitly-defaulted definition might have an implicit exception specification, see [dcl.fct.def].
end note
]
Default constructors are called implicitly to create class objects of static, thread, or automatic storage duration ([basic.stc.static], [basic.stc.thread], [basic.stc.auto]) defined without an initializer ([dcl.init]), are called to create class objects of dynamic storage duration ([basic.stc.dynamic]) created by a new-expression in which the new-initializer is omitted ([expr.new]), or are called when the explicit type conversion syntax ([expr.type.conv]) is used.
A program is ill-formed if the default constructor for an object is implicitly used and the constructor is not accessible (Clause [class.access]).
[Note
:
[class.base.init] describes the order in which constructors for base classes and non-static data members are called and describes how arguments can be specified for the calls to these constructors.
end note
]
A return statement in the body of a constructor shall not specify a return value.
The address of a constructor shall not be taken.
A functional notation type conversion ([expr.type.conv]) can be used to create new objects of its type.
[Note
:
The syntax looks like an explicit call of the constructor.
end note
]
[Example
:
complex zz = complex(1,2.3);
cprint( complex(7.8,1.2) );
end example
]
An object created in this way is unnamed.
[Note
:
[class.temporary] describes the lifetime of temporary objects.
end note
]
[Note
:
Explicit constructor calls do not yield lvalues, see [basic.lval].
end note
]
[Note
:
Some language constructs have special semantics when used during construction; see [class.base.init] and [class.cdtor].
end note
]
During the construction of an object, if the value of the object or any of its subobjects is accessed through a glvalue that is not obtained, directly or indirectly, from the constructor's this pointer, the value of the object or subobject thus obtained is unspecified.
[Example
:
struct C;
void no_opt(C*);

struct C {
  int c;
  C() : c(0) { no_opt(this); }
};

const C cobj;

void no_opt(C* cptr) {
  int i = cobj.c * 100;         // value of cobj.c is unspecified
  cptr->c = 1;
  cout << cobj.c * 100          // value of cobj.c is unspecified
       << '\n';
}

extern struct D d;
struct D {
  D(int a) : a(a), b(d.a) {}
  int a, b;
};
D d = D(1);                     // value of d.b is unspecified
end example
]

15.2 Temporary objects [class.temporary]

Temporary objects are created
  • when a prvalue is materialized so that it can be used as a glvalue ([conv.rval]),
  • when needed by the implementation to pass or return an object of trivially-copyable type (see below), and
  • when throwing an exception ([except.throw]).
    [Note
    :
    The lifetime of exception objects is described in [except.throw].
    end note
    ]
Even when the creation of the temporary object is unevaluated (Clause [expr]), all the semantic restrictions shall be respected as if the temporary object had been created and later destroyed.
[Note
:
This includes accessibility (Clause [class.access]) and whether it is deleted, for the constructor selected and for the destructor.
However, in the special case of the operand of a decltype-specifier ([expr.call]), no temporary is introduced, so the foregoing does not apply to such a prvalue.
end note
]
The materialization of a temporary object is generally delayed as long as possible in order to avoid creating unnecessary temporary objects.
[Note
:
Temporary objects are materialized:
end note
]
[Example
:
Consider the following code:
class X {
public:
  X(int);
  X(const X&);
  X& operator=(const X&);
  ~X();
};

class Y {
public:
  Y(int);
  Y(Y&&);
  ~Y();
};

X f(X);
Y g(Y);

void h() {
  X a(1);
  X b = f(X(2));
  Y c = g(Y(3));
  a = f(a);
}
X(2) is constructed in the space used to hold f()'s argument and Y(3) is constructed in the space used to hold g()'s argument.
Likewise, f()'s result is constructed directly in b and g()'s result is constructed directly in c.
On the other hand, the expression a = f(a) requires a temporary for the result of f(a), which is materialized so that the reference parameter of A​::​operator=(const A&) can bind to it.
end example
]
When an object of class type X is passed to or returned from a function, if each copy constructor, move constructor, and destructor of X is either trivial or deleted, and X has at least one non-deleted copy or move constructor, implementations are permitted to create a temporary object to hold the function parameter or result object.
The temporary object is constructed from the function argument or return value, respectively, and the function's parameter or return object is initialized as if by using the non-deleted trivial constructor to copy the temporary (even if that constructor is inaccessible or would not be selected by overload resolution to perform a copy or move of the object).
[Note
:
This latitude is granted to allow objects of class type to be passed to or returned from functions in registers.
end note
]
When an implementation introduces a temporary object of a class that has a non-trivial constructor ([class.ctor], [class.copy]), it shall ensure that a constructor is called for the temporary object.
Similarly, the destructor shall be called for a temporary with a non-trivial destructor ([class.dtor]).
Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created.
This is true even if that evaluation ends in throwing an exception.
The value computations and side effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression.
There are three contexts in which temporaries are destroyed at a different point than the end of the full-expression.
The first context is when a default constructor is called to initialize an element of an array with no corresponding initializer ([dcl.init]).
The second context is when a copy constructor is called to copy an element of an array while the entire array is copied ([expr.prim.lambda.capture], [class.copy]).
In either case, if the constructor has one or more default arguments, the destruction of every temporary created in a default argument is sequenced before the construction of the next array element, if any.
The third context is when a reference is bound to a temporary.116
The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:
  • A temporary object bound to a reference parameter in a function call ([expr.call]) persists until the completion of the full-expression containing the call.
  • The lifetime of a temporary bound to the returned value in a function return statement ([stmt.return]) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.
  • A temporary bound to a reference in a new-initializer persists until the completion of the full-expression containing the new-initializer.
    [Example
    :
    struct S { int mi; const std::pair<int,int>& mp; };
    S a { 1, {2,3} };
    S* p = new S{ 1, {2,3} };   // Creates dangling reference
    
    end example
    ]
    [Note
    :
    This may introduce a dangling reference, and implementations are encouraged to issue a warning in such a case.
    end note
    ]
The destruction of a temporary whose lifetime is not extended by being bound to a reference is sequenced before the destruction of every temporary which is constructed earlier in the same full-expression.
If the lifetime of two or more temporaries to which references are bound ends at the same point, these temporaries are destroyed at that point in the reverse order of the completion of their construction.
In addition, the destruction of temporaries bound to references shall take into account the ordering of destruction of objects with static, thread, or automatic storage duration ([basic.stc.static], [basic.stc.thread], [basic.stc.auto]); that is, if obj1 is an object with the same storage duration as the temporary and created before the temporary is created the temporary shall be destroyed before obj1 is destroyed; if obj2 is an object with the same storage duration as the temporary and created after the temporary is created the temporary shall be destroyed after obj2 is destroyed.
[Example
:
struct S {
  S();
  S(int);
  friend S operator+(const S&, const S&);
  ~S();
};
S obj1;
const S& cr = S(16)+S(23);
S obj2;
the expression S(16) + S(23) creates three temporaries: a first temporary T1 to hold the result of the expression S(16), a second temporary T2 to hold the result of the expression S(23), and a third temporary T3 to hold the result of the addition of these two expressions.
The temporary T3 is then bound to the reference cr.
It is unspecified whether T1 or T2 is created first.
On an implementation where T1 is created before T2, T2 shall be destroyed before T1.
The temporaries T1 and T2 are bound to the reference parameters of operator+; these temporaries are destroyed at the end of the full-expression containing the call to operator+.
The temporary T3 bound to the reference cr is destroyed at the end of cr's lifetime, that is, at the end of the program.
In addition, the order in which T3 is destroyed takes into account the destruction order of other objects with static storage duration.
That is, because obj1 is constructed before T3, and T3 is constructed before obj2, obj2 shall be destroyed before T3, and T3 shall be destroyed before obj1.
end example
]
The same rules apply to initialization of an initializer_­list object ([dcl.init.list]) with its underlying temporary array.

15.3 Conversions [class.conv]

Type conversions of class objects can be specified by constructors and by conversion functions.
These conversions are called user-defined conversions and are used for implicit type conversions (Clause [conv]), for initialization ([dcl.init]), and for explicit type conversions ([expr.cast], [expr.static.cast]).
User-defined conversions are applied only where they are unambiguous ([class.member.lookup], [class.conv.fct]).
Conversions obey the access control rules (Clause [class.access]).
Access control is applied after ambiguity resolution ([basic.lookup]).
[Note
:
See [over.match] for a discussion of the use of conversions in function calls as well as examples below.
end note
]
At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value.
[Example
:
struct X {
  operator int();
};

struct Y {
  operator X();
};

Y a;
int b = a;          // error, a.operator X().operator int() not tried
int c = X(a);       // OK: a.operator X().operator int()
end example
]
User-defined conversions are used implicitly only if they are unambiguous.
A conversion function in a derived class does not hide a conversion function in a base class unless the two functions convert to the same type.
Function overload resolution ([over.match.best]) selects the best conversion function to perform the conversion.
[Example
:
struct X {
  operator int();
};

struct Y : X {
    operator char();
};

void f(Y& a) {
  if (a) {          // ill-formed: X​::​operator int() or Y​::​operator char()
  }
}
end example
]

15.3.1 Conversion by constructor [class.conv.ctor]

A constructor declared without the function-specifier explicit specifies a conversion from the types of its parameters (if any) to the type of its class.
Such a constructor is called a converting constructor.
[Example
:
struct X {
    X(int);
    X(const char*, int =0);
    X(int, int);
};

void f(X arg) {
  X a = 1;          // a = X(1)
  X b = "Jessie";   // b = X("Jessie",0)
  a = 2;            // a = X(2)
  f(3);             // f(X(3))
  f({1, 2});        // f(X(1,2))
}
end example
]
[Note
:
An explicit constructor constructs objects just like non-explicit constructors, but does so only where the direct-initialization syntax ([dcl.init]) or where casts ([expr.static.cast], [expr.cast]) are explicitly used; see also [over.match.copy].
A default constructor may be an explicit constructor; such a constructor will be used to perform default-initialization or value-initialization ([dcl.init]).
[Example
:
struct Z {
  explicit Z();
  explicit Z(int);
  explicit Z(int, int);
};

Z a;                            // OK: default-initialization performed
Z b{};                          // OK: direct initialization syntax used
Z c = {};                       // error: copy-list-initialization
Z a1 = 1;                       // error: no implicit conversion
Z a3 = Z(1);                    // OK: direct initialization syntax used
Z a2(1);                        // OK: direct initialization syntax used
Z* p = new Z(1);                // OK: direct initialization syntax used
Z a4 = (Z)1;                    // OK: explicit cast used
Z a5 = static_cast<Z>(1);       // OK: explicit cast used
Z a6 = { 3, 4 };                // error: no implicit conversion
end example
]
end note
]
A non-explicit copy/move constructor ([class.copy]) is a converting constructor.
[Note
:
An implicitly-declared copy/move constructor is not an explicit constructor; it may be called for implicit type conversions.
end note
]

15.3.2 Conversion functions [class.conv.fct]

A member function of a class X having no parameters with a name of the form
Such functions are called conversion functions.
A decl-specifier in the decl-specifier-seq of a conversion function (if any) shall be neither a defining-type-specifier nor static.
The type of the conversion function ([dcl.fct]) is “function taking no parameter returning conversion-type-id.
A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void.117
[Example
:
struct X {
  operator int();
  operator auto() -> short;     // error: trailing return type
};

void f(X a) {
  int i = int(a);
  i = (int)a;
  i = a;
}
In all three cases the value assigned will be converted by X​::​operator int().
end example
]
A conversion function may be explicit ([dcl.fct.spec]), in which case it is only considered as a user-defined conversion for direct-initialization ([dcl.init]).
Otherwise, user-defined conversions are not restricted to use in assignments and initializations.
[Example
:
class Y { };
struct Z {
  explicit operator Y() const;
};

void h(Z z) {
  Y y1(z);          // OK: direct-initialization
  Y y2 = z;         // ill-formed: copy-initialization
  Y y3 = (Y)z;      // OK: cast notation
}

void g(X a, X b) {
  int i = (a) ? 1+a : 0;
  int j = (a&&b) ? a+b : i;
  if (a) {
  }
}
end example
]
The conversion-type-id shall not represent a function type nor an array type.
The conversion-type-id in a conversion-function-id is the longest sequence of tokens that could possibly form a conversion-type-id.
[Note
:
This prevents ambiguities between the declarator operator * and its expression counterparts.
[Example
:
&ac.operator int*i; // syntax error:
                    // parsed as: &(ac.operator int *)i
                    // not as: &(ac.operator int)*i
The * is the pointer declarator and not the multiplication operator.
end example
]
This rule also prevents ambiguities for attributes.
[Example
:
operator int [[noreturn]] ();   // error: noreturn attribute applied to a type
end example
]
end note
]
Conversion functions are inherited.
Conversion functions can be virtual.
A conversion function template shall not have a deduced return type ([dcl.spec.auto]).
[Example
:
struct S {
  operator auto() const { return 10; }      // OK
  template<class T>
  operator auto() const { return 1.2; }     // error: conversion function template
};
end example
]
These conversions are considered as standard conversions for the purposes of overload resolution ([over.best.ics], [over.ics.ref]) and therefore initialization ([dcl.init]) and explicit casts ([expr.static.cast]).
A conversion to void does not invoke any conversion function ([expr.static.cast]).
Even though never directly called to perform a conversion, such conversion functions can be declared and can potentially be reached through a call to a virtual conversion function in a base class.

15.4 Destructors [class.dtor]

In a declaration of a destructor, the declarator is a function declarator ([dcl.fct]) of the form
ptr-declarator ( parameter-declaration-clause ) noexcept-specifier attribute-specifier-seq
where the ptr-declarator consists solely of an id-expression, an optional attribute-specifier-seq, and optional surrounding parentheses, and the id-expression has one of the following forms:
The class-name shall not be a typedef-name.
A destructor shall take no arguments ([dcl.fct]).
Each decl-specifier of the decl-specifier-seq of a destructor declaration (if any) shall be friend, inline, or virtual.
A destructor is used to destroy objects of its class type.
The address of a destructor shall not be taken.
A destructor can be invoked for a const, volatile or const volatile object.
const and volatile semantics ([dcl.type.cv]) are not applied on an object under destruction.
They stop being in effect when the destructor for the most derived object ([intro.object]) starts.
[Note
:
A declaration of a destructor that does not have a noexcept-specifier has the same exception specification as if had been implicitly declared ([except.spec]).
end note
]
If a class has no user-declared destructor, a destructor is implicitly declared as defaulted ([dcl.fct.def]).
An implicitly-declared destructor is an inline public member of its class.
A defaulted destructor for a class X is defined as deleted if:
  • X is a union-like class that has a variant member with a non-trivial destructor,
  • any potentially constructed subobject has class type M (or array thereof) and M has a deleted destructor or a destructor that is inaccessible from the defaulted destructor,
  • or, for a virtual destructor, lookup of the non-array deallocation function results in an ambiguity or in a function that is deleted or inaccessible from the defaulted destructor.
A destructor is trivial if it is not user-provided and if:
  • the destructor is not virtual,
  • all of the direct base classes of its class have trivial destructors, and
  • for all of the non-static data members of its class that are of class type (or array thereof), each such class has a trivial destructor.
Otherwise, the destructor is non-trivial.
A destructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used ([basic.def.odr]) or when it is explicitly defaulted after its first declaration.
Before the defaulted destructor for a class is implicitly defined, all the non-user-provided destructors for its base classes and its non-static data members shall have been implicitly defined.
After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X's direct non-variant non-static data members, the destructors for X's non-virtual direct base classes and, if X is the type of the most derived class ([class.base.init]), its destructor calls the destructors for X's virtual base classes.
All destructors are called as if they were referenced with a qualified name, that is, ignoring any possible virtual overriding destructors in more derived classes.
Bases and members are destroyed in the reverse order of the completion of their constructor (see [class.base.init]).
A return statement ([stmt.return]) in a destructor might not directly return to the caller; before transferring control to the caller, the destructors for the members and bases are called.
Destructors for elements of an array are called in reverse order of their construction (see [class.init]).
A destructor can be declared virtual ([class.virtual]) or pure virtual ([class.abstract]); if any objects of that class or any derived class are created in the program, the destructor shall be defined.
If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly-declared) is virtual.
[Note
:
Some language constructs have special semantics when used during destruction; see [class.cdtor].
end note
]
A destructor is invoked implicitly
In each case, the context of the invocation is the context of the construction of the object.
A destructor is also invoked implicitly through use of a delete-expression for a constructed object allocated by a new-expression; the context of the invocation is the delete-expression.
[Note
:
An array of class type contains several subobjects for each of which the destructor is invoked.
end note
]
A destructor can also be invoked explicitly.
A destructor is potentially invoked if it is invoked or as specified in [expr.new], [class.base.init], and [except.throw].
A program is ill-formed if a destructor that is potentially invoked is deleted or not accessible from the context of the invocation.
At the point of definition of a virtual destructor (including an implicit definition ([class.copy])), the non-array deallocation function is determined as if for the expression delete this appearing in a non-virtual destructor of the destructor's class (see [expr.delete]).
If the lookup fails or if the deallocation function has a deleted definition ([dcl.fct.def]), the program is ill-formed.
[Note
:
This assures that a deallocation function corresponding to the dynamic type of an object is available for the delete-expression ([class.free]).
end note
]
In an explicit destructor call, the destructor is specified by a ~ followed by a type-name or decltype-specifier that denotes the destructor's class type.
The invocation of a destructor is subject to the usual rules for member functions ([class.mfct]); that is, if the object is not of the destructor's class type and not of a class derived from the destructor's class type (including when the destructor is invoked via a null pointer value), the program has undefined behavior.
[Note
:
Invoking delete on a null pointer does not call the destructor; see [expr.delete].
end note
]
[Example
:
struct B {
  virtual ~B() { }
};
struct D : B {
  ~D() { }
};

D D_object;
typedef B B_alias;
B* B_ptr = &D_object;

void f() {
  D_object.B::~B();             // calls B's destructor
  B_ptr->~B();                  // calls D's destructor
  B_ptr->~B_alias();            // calls D's destructor
  B_ptr->B_alias::~B();         // calls B's destructor
  B_ptr->B_alias::~B_alias();   // calls B's destructor
}
end example
]
[Note
:
An explicit destructor call must always be written using a member access operator ([expr.ref]) or a qualified-id ([expr.prim]); in particular, the unary-expression ~X() in a member function is not an explicit destructor call ([expr.unary.op]).
end note
]
[Note
:
Explicit calls of destructors are rarely needed.
One use of such calls is for objects placed at specific addresses using a placement new-expression.
Such use of explicit placement and destruction of objects can be necessary to cope with dedicated hardware resources and for writing memory management facilities.
For example,
void* operator new(std::size_t, void* p) { return p; }
struct X {
  X(int);
  ~X();
};
void f(X* p);

void g() {                      // rare, specialized use:
  char* buf = new char[sizeof(X)];
  X* p = new(buf) X(222);       // use buf[] and initialize
  f(p);
  p->X::~X();                   // cleanup
}
end note
]
Once a destructor is invoked for an object, the object no longer exists; the behavior is undefined if the destructor is invoked for an object whose lifetime has ended ([basic.life]).
[Example
:
If the destructor for an automatic object is explicitly invoked, and the block is subsequently left in a manner that would ordinarily invoke implicit destruction of the object, the behavior is undefined.
end example
]
[Note
:
The notation for explicit call of a destructor can be used for any scalar type name ([expr.pseudo]).
Allowing this makes it possible to write code without having to know if a destructor exists for a given type.
For example:
typedef int I;
I* p;
p->I::~I();
end note
]

15.5 Free store [class.free]

Any allocation function for a class T is a static member (even if not explicitly declared static).
[Example
:
class Arena;
struct B {
  void* operator new(std::size_t, Arena*);
};
struct D1 : B {
};

Arena*  ap;
void foo(int i) {
  new (ap) D1;      // calls B​::​operator new(std​::​size_­t, Arena*)
  new D1[i];        // calls ​::​operator new[](std​::​size_­t)
  new D1;           // ill-formed: ​::​operator new(std​::​size_­t) hidden
}
end example
]
When an object is deleted with a delete-expression, a deallocation function (operator delete() for non-array objects or operator delete[]() for arrays) is (implicitly) called to reclaim the storage occupied by the object ([basic.stc.dynamic.deallocation]).
Class-specific deallocation function lookup is a part of general deallocation function lookup ([expr.delete]) and occurs as follows.
If the delete-expression is used to deallocate a class object whose static type has a virtual destructor, the deallocation function is the one selected at the point of definition of the dynamic type's virtual destructor ([class.dtor]).118
Otherwise, if the delete-expression is used to deallocate an object of class T or array thereof, the static and dynamic types of the object shall be identical and the deallocation function's name is looked up in the scope of T.
If this lookup fails to find the name, general deallocation function lookup ([expr.delete]) continues.
If the result of the lookup is ambiguous or inaccessible, or if the lookup selects a placement deallocation function, the program is ill-formed.
Any deallocation function for a class X is a static member (even if not explicitly declared static).
[Example
:
class X {
  void operator delete(void*);
  void operator delete[](void*, std::size_t);
};

class Y {
  void operator delete(void*, std::size_t);
  void operator delete[](void*);
};
end example
]
Since member allocation and deallocation functions are static they cannot be virtual.
[Note
:
However, when the cast-expression of a delete-expression refers to an object of class type, because the deallocation function actually called is looked up in the scope of the class that is the dynamic type of the object, if the destructor is virtual, the effect is the same.
For example,
struct B {
  virtual ~B();
  void operator delete(void*, std::size_t);
};

struct D : B {
  void operator delete(void*);
};

void f() {
  B* bp = new D;
  delete bp;        // 1: uses D​::​operator delete(void*)
}
Here, storage for the non-array object of class D is deallocated by D​::​operator delete(), due to the virtual destructor.
end note
]
[Note
:
Virtual destructors have no effect on the deallocation function actually called when the cast-expression of a delete-expression refers to an array of objects of class type.
For example,
struct B {
  virtual ~B();
  void operator delete[](void*, std::size_t);
};

struct D : B {
  void operator delete[](void*, std::size_t);
};

void f(int i) {
  D* dp = new D[i];
  delete [] dp;     // uses D​::​operator delete[](void*, std​::​size_­t)
  B* bp = new D[i];
  delete[] bp;      // undefined behavior
}
end note
]
Access to the deallocation function is checked statically.
Hence, even though a different one might actually be executed, the statically visible deallocation function is required to be accessible.
[Example
:
For the call on line “// 1” above, if B​::​operator delete() had been private, the delete expression would have been ill-formed.
end example
]
[Note
:
If a deallocation function has no explicit noexcept-specifier, it has a non-throwing exception specification ([except.spec]).
end note
]
A similar provision is not needed for the array version of operator delete because [expr.delete] requires that in this situation, the static type of the object to be deleted be the same as its dynamic type.

15.6 Initialization [class.init]

When no initializer is specified for an object of (possibly cv-qualified) class type (or array thereof), or the initializer has the form (), the object is initialized as specified in [dcl.init].
An object of class type (or array thereof) can be explicitly initialized; see [class.expl.init] and [class.base.init].
When an array of class objects is initialized (either explicitly or implicitly) and the elements are initialized by constructor, the constructor shall be called for each element of the array, following the subscript order; see [dcl.array].
[Note
:
Destructors for the array elements are called in reverse order of their construction.
end note
]

15.6.1 Explicit initialization [class.expl.init]

An object of class type can be initialized with a parenthesized expression-list, where the expression-list is construed as an argument list for a constructor that is called to initialize the object.
Alternatively, a single assignment-expression can be specified as an initializer using the = form of initialization.
Either direct-initialization semantics or copy-initialization semantics apply; see [dcl.init].
[Example
:
struct complex {
  complex();
  complex(double);
  complex(double,double);
};

complex sqrt(complex,complex);

complex a(1);                   // initialize by a call of complex(double)
complex b = a;                  // initialize by a copy of a
complex c = complex(1,2);       // construct complex(1,2) using complex(double,double),
                                // copy/move it into c
complex d = sqrt(b,c);          // call sqrt(complex,complex) and copy/move the result into d
complex e;                      // initialize by a call of complex()
complex f = 3;                  // construct complex(3) using complex(double), copy/move it into f
complex g = { 1, 2 };           // initialize by a call of complex(double, double)
end example
]
[Note
:
Overloading of the assignment operator ([over.ass]) has no effect on initialization.
end note
]
An object of class type can also be initialized by a braced-init-list.
List-initialization semantics apply; see [dcl.init] and [dcl.init.list].
[Example
:
complex v[6] = { 1, complex(1,2), complex(), 2 };
Here, complex​::​complex(double) is called for the initialization of v[0] and v[3], complex​::​complex(​double, double) is called for the initialization of v[1], complex​::​complex() is called for the initialization v[2], v[4], and v[5].
For another example,
struct X {
  int i;
  float f;
  complex c;
} x = { 99, 88.8, 77.7 };
Here, x.i is initialized with 99, x.f is initialized with 88.
8, and complex​::​complex(double) is called for the initialization of x.c.
end example
]
[Note
:
Braces can be elided in the initializer-list for any aggregate, even if the aggregate has members of a class type with user-defined type conversions; see [dcl.init.aggr].
end note
]
[Note
:
If T is a class type with no default constructor, any declaration of an object of type T (or array thereof) is ill-formed if no initializer is explicitly specified (see [class.init] and [dcl.init]).
end note
]
[Note
:
The order in which objects with static or thread storage duration are initialized is described in [basic.start.dynamic] and [stmt.dcl].
end note
]

15.6.2 Initializing bases and members [class.base.init]

In the definition of a constructor for a class, initializers for direct and virtual base class subobjects and non-static data members can be specified by a ctor-initializer, which has the form
In a mem-initializer-id an initial unqualified identifier is looked up in the scope of the constructor's class and, if not found in that scope, it is looked up in the scope containing the constructor's definition.
[Note
:
If the constructor's class contains a member with the same name as a direct or virtual base class of the class, a mem-initializer-id naming the member or base class and composed of a single identifier refers to the class member.
A mem-initializer-id for the hidden base class may be specified using a qualified name.
end note
]
Unless the mem-initializer-id names the constructor's class, a non-static data member of the constructor's class, or a direct or virtual base of that class, the mem-initializer is ill-formed.
A mem-initializer-list can initialize a base class using any class-or-decltype that denotes that base class type.
[Example
:
struct A { A(); };
typedef A global_A;
struct B { };
struct C: public A, public B { C(); };
C::C(): global_A() { }          // mem-initializer for base A
end example
]
If a mem-initializer-id is ambiguous because it designates both a direct non-virtual base class and an inherited virtual base class, the mem-initializer is ill-formed.
[Example
:
struct A { A(); };
struct B: public virtual A { };
struct C: public A, public B { C(); };
C::C(): A() { }                 // ill-formed: which A?
end example
]
A ctor-initializer may initialize a variant member of the constructor's class.
If a ctor-initializer specifies more than one mem-initializer for the same member or for the same base class, the ctor-initializer is ill-formed.
A mem-initializer-list can delegate to another constructor of the constructor's class using any class-or-decltype that denotes the constructor's class itself.
If a mem-initializer-id designates the constructor's class, it shall be the only mem-initializer; the constructor is a delegating constructor, and the constructor selected by the mem-initializer is the target constructor.
The target constructor is selected by overload resolution.
Once the target constructor returns, the body of the delegating constructor is executed.
If a constructor delegates to itself directly or indirectly, the program is ill-formed, no diagnostic required.
[Example
:
struct C {
  C( int ) { }                  // #1: non-delegating constructor
  C(): C(42) { }                // #2: delegates to #1
  C( char c ) : C(42.0) { }     // #3: ill-formed due to recursion with #4
  C( double d ) : C('a') { }    // #4: ill-formed due to recursion with #3
};
end example
]
The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of [dcl.init] for direct-initialization.
[Example
:
struct B1 { B1(int); /* ... */ };
struct B2 { B2(int); /* ... */ };
struct D : B1, B2 {
  D(int);
  B1 b;
  const int c;
};

D::D(int a) : B2(a+1), B1(a+2), c(a+3), b(a+4) { /* ... */ }
D d(10);
end example
]
[Note
:
The initialization performed by each mem-initializer constitutes a full-expression ([intro.execution]).
Any expression in a mem-initializer is evaluated as part of the full-expression that performs the initialization.
end note
]
A mem-initializer where the mem-initializer-id denotes a virtual base class is ignored during execution of a constructor of any class that is not the most derived class.
A temporary expression bound to a reference member in a mem-initializer is ill-formed.
[Example
:
struct A {
  A() : v(42) { }   // error
  const int& v;
};
end example
]
In a non-delegating constructor, if a given potentially constructed subobject is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer), then
  • if the entity is a non-static data member that has a default member initializer ([class.mem]) and either
    the entity is initialized from its default member initializer as specified in [dcl.init];
  • otherwise, if the entity is an anonymous union or a variant member ([class.union.anon]), no initialization is performed;
  • otherwise, the entity is default-initialized ([dcl.init]).
[Note
:
An abstract class ([class.abstract]) is never a most derived class, thus its constructors never initialize virtual base classes, therefore the corresponding mem-initializers may be omitted.
end note
]
An attempt to initialize more than one non-static data member of a union renders the program ill-formed.
[Note
:
After the call to a constructor for class X for an object with automatic or dynamic storage duration has completed, if the constructor was not invoked as part of value-initialization and a member of X is neither initialized nor given a value during execution of the compound-statement of the body of the constructor, the member has an indeterminate value.
end note
]
[Example
:
struct A {
  A();
};

struct B {
  B(int);
};

struct C {
  C() { }               // initializes members as follows:
  A a;                  // OK: calls A​::​A()
  const B b;            // error: B has no default constructor
  int i;                // OK: i has indeterminate value
  int j = 5;            // OK: j has the value 5
};
end example
]
If a given non-static data member has both a default member initializer and a mem-initializer, the initialization specified by the mem-initializer is performed, and the non-static data member's default member initializer is ignored.
[Example
:
Given
struct A {
  int i = /* some integer expression with side effects */ ;
  A(int arg) : i(arg) { }
  // ...
};
the A(int) constructor will simply initialize i to the value of arg, and the side effects in i's default member initializer will not take place.
end example
]
A temporary expression bound to a reference member from a default member initializer is ill-formed.
[Example
:
struct A {
  A() = default;        // OK
  A(int v) : v(v) { }   // OK
  const int& v = 42;    // OK
};
A a1;                   // error: ill-formed binding of temporary to reference
A a2(1);                // OK, unfortunately
end example
]
In a non-delegating constructor, the destructor for each potentially constructed subobject of class type is potentially invoked ([class.dtor]).
[Note
:
This provision ensures that destructors can be called for fully-constructed subobjects in case an exception is thrown ([except.ctor]).
end note
]
In a non-delegating constructor, initialization proceeds in the following order:
  • First, and only for the constructor of the most derived class ([intro.object]), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
  • Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
  • Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
  • Finally, the compound-statement of the constructor body is executed.
[Note
:
The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization.
end note
]
[Example
:
struct V {
  V();
  V(int);
};

struct A : virtual V {
  A();
  A(int);
};

struct B : virtual V {
  B();
  B(int);
};

struct C : A, B, virtual V {
  C();
  C(int);
};

A::A(int i) : V(i) { /* ... */ }
B::B(int i) { /* ... */ }
C::C(int i) { /* ... */ }

V v(1);             // use V(int)
A a(2);             // use V(int)
B b(3);             // use V()
C c(4);             // use V()
end example
]
Names in the expression-list or braced-init-list of a mem-initializer are evaluated in the scope of the constructor for which the mem-initializer is specified.
[Example
:
class X {
  int a;
  int b;
  int i;
  int j;
public:
  const int& r;
  X(int i): r(a), b(i), i(i), j(this->i) { }
};
initializes X​::​r to refer to X​::​a, initializes X​::​b with the value of the constructor parameter i, initializes X​::​i with the value of the constructor parameter i, and initializes X​::​j with the value of X​::​i; this takes place each time an object of class X is created.
end example
]
[Note
:
Because the mem-initializer are evaluated in the scope of the constructor, the this pointer can be used in the expression-list of a mem-initializer to refer to the object being initialized.
end note
]
Member functions (including virtual member functions, [class.virtual]) can be called for an object under construction.
Similarly, an object under construction can be the operand of the typeid operator ([expr.typeid]) or of a dynamic_­cast ([expr.dynamic.cast]).
However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed, the program has undefined behavior.
[Example
:
class A {
public:
  A(int);
};

class B : public A {
  int j;
public:
  int f();
  B() : A(f()),     // undefined: calls member function but base A not yet initialized
  j(f()) { }        // well-defined: bases are all initialized
};

class C {
public:
  C(int);
};

class D : public B, C {
  int i;
public:
  D() : C(f()),     // undefined: calls member function but base C not yet initialized
  i(f()) { }        // well-defined: bases are all initialized
};
end example
]
[Note
:
[class.cdtor] describes the result of virtual function calls, typeid and dynamic_­casts during construction for the well-defined cases; that is, describes the polymorphic behavior of an object under construction.
end note
]
A mem-initializer followed by an ellipsis is a pack expansion ([temp.variadic]) that initializes the base classes specified by a pack expansion in the base-specifier-list for the class.
[Example
:
template<class... Mixins>
class X : public Mixins... {
public:
  X(const Mixins&... mixins) : Mixins(mixins)... { }
};
end example
]

15.6.3 Initialization by inherited constructor [class.inhctor.init]

When a constructor for type B is invoked to initialize an object of a different type D (that is, when the constructor was inherited ([namespace.udecl])), initialization proceeds as if a defaulted default constructor were used to initialize the D object and each base class subobject from which the constructor was inherited, except that the B subobject is initialized by the invocation of the inherited constructor.
The complete initialization is considered to be a single function call; in particular, the initialization of the inherited constructor's parameters is sequenced before the initialization of any part of the D object.
[Example
:
struct B1 {
  B1(int, ...) { }
};

struct B2 {
  B2(double) { }
};

int get();

struct D1 : B1 {
  using B1::B1;     // inherits B1(int, ...)
  int x;
  int y = get();
};

void test() {
  D1 d(2, 3, 4);    // OK: B1 is initialized by calling B1(2, 3, 4),
                    // then d.x is default-initialized (no initialization is performed),
                    // then d.y is initialized by calling get()
  D1 e;             // error: D1 has a deleted default constructor
}

struct D2 : B2 {
  using B2::B2;
  B1 b;
};

D2 f(1.0);          // error: B1 has a deleted default constructor

struct W { W(int); };
struct X : virtual W { using W::W; X() = delete; };
struct Y : X { using X::X; };
struct Z : Y, virtual W { using Y::Y; };
Z z(0);             // OK: initialization of Y does not invoke default constructor of X

template<class T> struct Log : T {
  using T::T;       // inherits all constructors from class T
  ~Log() { std::clog << "Destroying wrapper" << std::endl; }
};
Class template Log wraps any class and forwards all of its constructors, while writing a message to the standard log whenever an object of class Log is destroyed.
end example
]
If the constructor was inherited from multiple base class subobjects of type B, the program is ill-formed.
[Example
:
struct A { A(int); };
struct B : A { using A::A; };

struct C1 : B { using B::B; };
struct C2 : B { using B::B; };

struct D1 : C1, C2 {
  using C1::C1;
  using C2::C2;
};

struct V1 : virtual B { using B::B; };
struct V2 : virtual B { using B::B; };

struct D2 : V1, V2 {
  using V1::V1;
  using V2::V2;
};

D1 d1(0);           // ill-formed: ambiguous
D2 d2(0);           // OK: initializes virtual B base class, which initializes the A base class
                    // then initializes the V1 and V2 base classes as if by a defaulted default constructor

struct M { M(); M(int); };
struct N : M { using M::M; };
struct O : M {};
struct P : N, O { using N::N; using O::O; };
P p(0);             // OK: use M(0) to initialize N's base class,
                    // use M() to initialize O's base class
end example
]
When an object is initialized by an inherited constructor, initialization of the object is complete when the initialization of all subobjects is complete.

15.7 Construction and destruction [class.cdtor]

For an object with a non-trivial constructor, referring to any non-static member or base class of the object before the constructor begins execution results in undefined behavior.
For an object with a non-trivial destructor, referring to any non-static member or base class of the object after the destructor finishes execution results in undefined behavior.
[Example
:
struct X { int i; };
struct Y : X { Y(); };                  // non-trivial
struct A { int a; };
struct B : public A { int j; Y y; };    // non-trivial

extern B bobj;
B* pb = &bobj;                          // OK
int* p1 = &bobj.a;                      // undefined, refers to base class member
int* p2 = &bobj.y.i;                    // undefined, refers to member's member

A* pa = &bobj;                          // undefined, upcast to a base class type
B bobj;                                 // definition of bobj

extern X xobj;
int* p3 = &xobj.i;                      // OK, X is a trivial class
X xobj;
For another example,
struct W { int j; };
struct X : public virtual W { };
struct Y {
  int* p;
  X x;
  Y() : p(&x.j) {   // undefined, x is not yet constructed
    }
};
end example
]
To explicitly or implicitly convert a pointer (a glvalue) referring to an object of class X to a pointer (reference) to a direct or indirect base class B of X, the construction of X and the construction of all of its direct or indirect bases that directly or indirectly derive from B shall have started and the destruction of these classes shall not have completed, otherwise the conversion results in undefined behavior.
To form a pointer to (or access the value of) a direct non-static member of an object obj, the construction of obj shall have started and its destruction shall not have completed, otherwise the computation of the pointer value (or accessing the member value) results in undefined behavior.
[Example
:
struct A { };
struct B : virtual A { };
struct C : B { };
struct D : virtual A { D(A*); };
struct X { X(A*); };

struct E : C, D, X {
  E() : D(this),    // undefined: upcast from E* to A* might use path E*  D*  A*
                    // but D is not constructed

                    // “D((C*)this)” would be defined: E*  C* is defined because E() has started,
                    // and C*  A* is defined because C is fully constructed

  X(this) {}        // defined: upon construction of X, C/B/D/A sublattice is fully constructed
};
end example
]
Member functions, including virtual functions ([class.virtual]), can be called during construction or destruction ([class.base.init]).
When a virtual function is called directly or indirectly from a constructor or from a destructor, including during the construction or destruction of the class's non-static data members, and the object to which the call applies is the object (call it x) under construction or destruction, the function called is the final overrider in the constructor's or destructor's class and not one overriding it in a more-derived class.
If the virtual function call uses an explicit class member access ([expr.ref]) and the object expression refers to the complete object of x or one of that object's base class subobjects but not x or one of its base class subobjects, the behavior is undefined.
[Example
:
struct V {
  virtual void f();
  virtual void g();
};

struct A : virtual V {
  virtual void f();
};

struct B : virtual V {
  virtual void g();
  B(V*, A*);
};

struct D : A, B {
  virtual void f();
  virtual void g();
  D() : B((A*)this, this) { }
};

B::B(V* v, A* a) {
  f();              // calls V​::​f, not A​::​f
  g();              // calls B​::​g, not D​::​g
  v->g();           // v is base of B, the call is well-defined, calls B​::​g
  a->f();           // undefined behavior, a's type not a base of B
}
end example
]
The typeid operator ([expr.typeid]) can be used during construction or destruction ([class.base.init]).
When typeid is used in a constructor (including the mem-initializer or default member initializer ([class.mem]) for a non-static data member) or in a destructor, or used in a function called (directly or indirectly) from a constructor or destructor, if the operand of typeid refers to the object under construction or destruction, typeid yields the std​::​type_­info object representing the constructor or destructor's class.
If the operand of typeid refers to the object under construction or destruction and the static type of the operand is neither the constructor or destructor's class nor one of its bases, the behavior is undefined.
dynamic_­casts ([expr.dynamic.cast]) can be used during construction or destruction ([class.base.init]).
When a dynamic_­cast is used in a constructor (including the mem-initializer or default member initializer for a non-static data member) or in a destructor, or used in a function called (directly or indirectly) from a constructor or destructor, if the operand of the dynamic_­cast refers to the object under construction or destruction, this object is considered to be a most derived object that has the type of the constructor or destructor's class.
If the operand of the dynamic_­cast refers to the object under construction or destruction and the static type of the operand is not a pointer to or object of the constructor or destructor's own class or one of its bases, the dynamic_­cast results in undefined behavior.
[Example
:
struct V {
  virtual void f();
};

struct A : virtual V { };

struct B : virtual V {
  B(V*, A*);
};

struct D : A, B {
  D() : B((A*)this, this) { }
};

B::B(V* v, A* a) {
  typeid(*this);                // type_­info for B
  typeid(*v);                   // well-defined: *v has type V, a base of B yields type_­info for B
  typeid(*a);                   // undefined behavior: type A not a base of B
  dynamic_cast<B*>(v);          // well-defined: v of type V*, V base of B results in B*
  dynamic_cast<B*>(a);          // undefined behavior, a has type A*, A not a base of B
}
end example
]

15.8 Copying and moving class objects [class.copy]

A class object can be copied or moved in two ways: by initialization ([class.ctor], [dcl.init]), including for function argument passing ([expr.call]) and for function value return ([stmt.return]); and by assignment ([expr.ass]).
Conceptually, these two operations are implemented by a copy/move constructor ([class.ctor]) and copy/move assignment operator ([over.ass]).
A program is ill-formed if the copy/move constructor or the copy/move assignment operator for an object is implicitly odr-used and the special member function is not accessible (Clause [class.access]).
[Note
:
Copying/moving one object into another using the copy/move constructor or the copy/move assignment operator does not change the layout or size of either object.
end note
]

15.8.1 Copy/move constructors [class.copy.ctor]

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments ([dcl.fct.default]).
[Example
:
X​::​X(const X&) and X​::​X(X&,int=1) are copy constructors.
struct X {
  X(int);
  X(const X&, int = 1);
};
X a(1);             // calls X(int);
X b(a, 0);          // calls X(const X&, int);
X c = b;            // calls X(const X&, int);
end example
]
A non-template constructor for class X is a move constructor if its first parameter is of type X&&, const X&&, volatile X&&, or const volatile X&&, and either there are no other parameters or else all other parameters have default arguments ([dcl.fct.default]).
[Example
:
Y​::​Y(Y&&) is a move constructor.
struct Y {
  Y(const Y&);
  Y(Y&&);
};
extern Y f(int);
Y d(f(1));          // calls Y(Y&&)
Y e = d;            // calls Y(const Y&)
end example
]
[Note
:
All forms of copy/move constructor may be declared for a class.
[Example
:
struct X {
  X(const X&);
  X(X&);            // OK
  X(X&&);
  X(const X&&);     // OK, but possibly not sensible
};
end example
]
end note
]
[Note
:
If a class X only has a copy constructor with a parameter of type X&, an initializer of type const X or volatile X cannot initialize an object of type (possibly cv-qualified) X.
[Example
:
struct X {
  X();              // default constructor
  X(X&);            // copy constructor with a non-const parameter
};
const X cx;
X x = cx;           // error: X​::​X(X&) cannot copy cx into x
end example
]
end note
]
A declaration of a constructor for a class X is ill-formed if its first parameter is of type (optionally cv-qualified) X and either there are no other parameters or else all other parameters have default arguments.
A member function template is never instantiated to produce such a constructor signature.
[Example
:
struct S {
  template<typename T> S(T);
  S();
};

S g;

void h() {
  S a(g);           // does not instantiate the member template to produce S​::​S<S>(S);
                    // uses the implicitly declared copy constructor
}
end example
]
If the class definition does not explicitly declare a copy constructor, a non-explicit one is declared implicitly.
If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted ([dcl.fct.def]).
The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor.
The implicitly-declared copy constructor for a class X will have the form
X::X(const X&)
if each potentially constructed subobject of a class type M (or array thereof) has a copy constructor whose first parameter is of type const M& or const volatile M&.119
Otherwise, the implicitly-declared copy constructor will have the form
X::X(X&)
If the definition of a class X does not explicitly declare a move constructor, a non-explicit one will be implicitly declared as defaulted if and only if
  • X does not have a user-declared copy constructor,
  • X does not have a user-declared copy assignment operator,
  • X does not have a user-declared move assignment operator, and
  • X does not have a user-declared destructor.
[Note
:
When the move constructor is not implicitly declared or explicitly supplied, expressions that otherwise would have invoked the move constructor may instead invoke a copy constructor.
end note
]
The implicitly-declared move constructor for class X will have the form
X::X(X&&)
An implicitly-declared copy/move constructor is an inline public member of its class.
A defaulted copy/​move constructor for a class X is defined as deleted ([dcl.fct.def.delete]) if X has:
  • a variant member with a non-trivial corresponding constructor and X is a union-like class,
  • a potentially constructed subobject type M (or array thereof) that cannot be copied/moved because overload resolution ([over.match]), as applied to find M's corresponding constructor, results in an ambiguity or a function that is deleted or inaccessible from the defaulted constructor,
  • any potentially constructed subobject of a type with a destructor that is deleted or inaccessible from the defaulted constructor, or,
  • for the copy constructor, a non-static data member of rvalue reference type.
A defaulted move constructor that is defined as deleted is ignored by overload resolution ([over.match], [over.over]).
[Note
:
A deleted move constructor would otherwise interfere with initialization from an rvalue which can use the copy constructor instead.
end note
]
A copy/move constructor for class X is trivial if it is not user-provided and if:
  • class X has no virtual functions ([class.virtual]) and no virtual base classes ([class.mi]), and
  • the constructor selected to copy/move each direct base class subobject is trivial, and
  • for each non-static data member of X that is of class type (or array thereof), the constructor selected to copy/move that member is trivial;
otherwise the copy/move constructor is non-trivial.
A copy/move constructor that is defaulted and not defined as deleted is implicitly defined if it is odr-used ([basic.def.odr]) or when it is explicitly defaulted after its first declaration.
[Note
:
The copy/move constructor is implicitly defined even if the implementation elided its odr-use ([basic.def.odr], [class.temporary]).
end note
]
If the implicitly-defined constructor would satisfy the requirements of a constexpr constructor ([dcl.constexpr]), the implicitly-defined constructor is constexpr.
Before the defaulted copy/move constructor for a class is implicitly defined, all non-user-provided copy/move constructors for its potentially constructed subobjects shall have been implicitly defined.
[Note
:
An implicitly-declared copy/move constructor has an implied exception specification ([except.spec]).
end note
]
The implicitly-defined copy/move constructor for a non-union class X performs a memberwise copy/move of its bases and members.
[Note
:
Default member initializers of non-static data members are ignored.
See also the example in [class.base.init].
end note
]
The order of initialization is the same as the order of initialization of bases and members in a user-defined constructor (see [class.base.init]).
Let x be either the parameter of the constructor or, for the move constructor, an xvalue referring to the parameter.
Each base or non-static data member is copied/moved in the manner appropriate to its type:
  • if the member is an array, each element is direct-initialized with the corresponding subobject of x;
  • if a member m has rvalue reference type T&&, it is direct-initialized with static_­cast<T&&>(x.m);
  • otherwise, the base or member is direct-initialized with the corresponding base or member of x.
Virtual base class subobjects shall be initialized only once by the implicitly-defined copy/move constructor (see [class.base.init]).
The implicitly-defined copy/move constructor for a union X copies the object representation ([basic.types]) of X.
This implies that the reference parameter of the implicitly-declared copy constructor cannot bind to a volatile lvalue; see [diff.special].

15.8.2 Copy/move assignment operator [class.copy.assign]

A user-declared copy assignment operator X​::​operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatile X&.120
[Note
:
An overloaded assignment operator must be declared to have only one parameter; see [over.ass].
end note
]
[Note
:
More than one form of copy assignment operator may be declared for a class.
end note
]
[Note
:
If a class X only has a copy assignment operator with a parameter of type X&, an expression of type const X cannot be assigned to an object of type X.
[Example
:
struct X {
  X();
  X& operator=(X&);
};
const X cx;
X x;
void f() {
  x = cx;           // error: X​::​operator=(X&) cannot assign cx into x
}
end example
]
end note
]
If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly.
If the class definition declares a move constructor or move assignment operator, the implicitly declared copy assignment operator is defined as deleted; otherwise, it is defined as defaulted ([dcl.fct.def]).
The latter case is deprecated if the class has a user-declared copy constructor or a user-declared destructor.
The implicitly-declared copy assignment operator for a class X will have the form
X& X::operator=(const X&)
if
  • each direct base class B of X has a copy assignment operator whose parameter is of type const B&, const volatile B& or B, and
  • for all the non-static data members of X that are of a class type M (or array thereof), each such class type has a copy assignment operator whose parameter is of type const M&, const volatile M& or M.121
Otherwise, the implicitly-declared copy assignment operator will have the form
X& X::operator=(X&)
A user-declared move assignment operator X​::​operator= is a non-static non-template member function of class X with exactly one parameter of type X&&, const X&&, volatile X&&, or const volatile X&&.
[Note
:
An overloaded assignment operator must be declared to have only one parameter; see [over.ass].
end note
]
[Note
:
More than one form of move assignment operator may be declared for a class.
end note
]
If the definition of a class X does not explicitly declare a move assignment operator, one will be implicitly declared as defaulted if and only if
  • X does not have a user-declared copy constructor,
  • X does not have a user-declared move constructor,
  • X does not have a user-declared copy assignment operator, and
  • X does not have a user-declared destructor.
[Example
:
The class definition
struct S {
  int a;
  S& operator=(const S&) = default;
};
will not have a default move assignment operator implicitly declared because the copy assignment operator has been user-declared.
The move assignment operator may be explicitly defaulted.
struct S {
  int a;
  S& operator=(const S&) = default;
  S& operator=(S&&) = default;
};
end example
]
The implicitly-declared move assignment operator for a class X will have the form
X& X::operator=(X&&);
The implicitly-declared copy/move assignment operator for class X has the return type X&; it returns the object for which the assignment operator is invoked, that is, the object assigned to.
An implicitly-declared copy/move assignment operator is an inline public member of its class.
A defaulted copy/move assignment operator for class X is defined as deleted if X has:
  • a variant member with a non-trivial corresponding assignment operator and X is a union-like class, or
  • a non-static data member of const non-class type (or array thereof), or
  • a non-static data member of reference type, or
  • a direct non-static data member of class type M (or array thereof) or a direct base class M that cannot be copied/moved because overload resolution ([over.match]), as applied to find M's corresponding assignment operator, results in an ambiguity or a function that is deleted or inaccessible from the defaulted assignment operator.
A defaulted move assignment operator that is defined as deleted is ignored by overload resolution ([over.match], [over.over]).
Because a copy/move assignment operator is implicitly declared for a class if not declared by the user, a base class copy/move assignment operator is always hidden by the corresponding assignment operator of a derived class ([over.ass]).
A using-declaration that brings in from a base class an assignment operator with a parameter type that could be that of a copy/move assignment operator for the derived class is not considered an explicit declaration of such an operator and does not suppress the implicit declaration of the derived class operator; the operator introduced by the using-declaration is hidden by the implicitly-declared operator in the derived class.
A copy/move assignment operator for class X is trivial if it is not user-provided and if:
  • class X has no virtual functions ([class.virtual]) and no virtual base classes ([class.mi]), and
  • the assignment operator selected to copy/move each direct base class subobject is trivial, and
  • for each non-static data member of X that is of class type (or array thereof), the assignment operator selected to copy/move that member is trivial;
otherwise the copy/move assignment operator is non-trivial.
A copy/move assignment operator for a class X that is defaulted and not defined as deleted is implicitly defined when it is odr-used ([basic.def.odr]) (e.g., when it is selected by overload resolution to assign to an object of its class type) or when it is explicitly defaulted after its first declaration. The implicitly-defined copy/move assignment operator is constexpr if
  • X is a literal type, and
  • the assignment operator selected to copy/move each direct base class subobject is a constexpr function, and
  • for each non-static data member of X that is of class type (or array thereof), the assignment operator selected to copy/move that member is a constexpr function.
Before the defaulted copy/move assignment operator for a class is implicitly defined, all non-user-provided copy/move assignment operators for its direct base classes and its non-static data members shall have been implicitly defined.
[Note
:
An implicitly-declared copy/move assignment operator has an implied exception specification ([except.spec]).
end note
]
The implicitly-defined copy/move assignment operator for a non-union class X performs memberwise copy/move assignment of its subobjects.
The direct base classes of X are assigned first, in the order of their declaration in the base-specifier-list, and then the immediate non-static data members of X are assigned, in the order in which they were declared in the class definition.
Let x be either the parameter of the function or, for the move operator, an xvalue referring to the parameter.
Each subobject is assigned in the manner appropriate to its type:
  • if the subobject is of class type, as if by a call to operator= with the subobject as the object expression and the corresponding subobject of x as a single function argument (as if by explicit qualification; that is, ignoring any possible virtual overriding functions in more derived classes);
  • if the subobject is an array, each element is assigned, in the manner appropriate to the element type;
  • if the subobject is of scalar type, the built-in assignment operator is used.
It is unspecified whether subobjects representing virtual base classes are assigned more than once by the implicitly-defined copy/move assignment operator.
[Example
:
struct V { };
struct A : virtual V { };
struct B : virtual V { };
struct C : B, A { };
It is unspecified whether the virtual base class subobject V is assigned twice by the implicitly-defined copy/move assignment operator for C.
end example
]
The implicitly-defined copy assignment operator for a union X copies the object representation ([basic.types]) of X.
Because a template assignment operator or an assignment operator taking an rvalue reference parameter is never a copy assignment operator, the presence of such an assignment operator does not suppress the implicit declaration of a copy assignment operator.
Such assignment operators participate in overload resolution with other assignment operators, including copy assignment operators, and, if selected, will be used to assign an object.
This implies that the reference parameter of the implicitly-declared copy assignment operator cannot bind to a volatile lvalue; see [diff.special].

15.8.3 Copy/move elision [class.copy.elision]

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects.
In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object.
If the first parameter of the selected constructor is an rvalue reference to the object's type, the destruction of that object occurs when the target would have been destroyed; otherwise, the destruction occurs at the later of the times when the two objects would have been destroyed without the optimization.122
This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):
  • in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function parameter or a variable introduced by the exception-declaration of a handler ([except.handle])) with the same type (ignoring cv-qualification) as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function call's return object
  • in a throw-expression, when the operand is the name of a non-volatile automatic object (other than a function or catch-clause parameter) whose scope does not extend beyond the end of the innermost enclosing try-block (if there is one), the copy/move operation from the operand to the exception object ([except.throw]) can be omitted by constructing the automatic object directly into the exception object
  • when the exception-declaration of an exception handler (Clause [except]) declares an object of the same type (except for cv-qualification) as the exception object ([except.throw]), the copy operation can be omitted by treating the exception-declaration as an alias for the exception object if the meaning of the program will be unchanged except for the execution of constructors and destructors for the object declared by the exception-declaration.
    [Note
    :
    There cannot be a move from the exception object because it is always an lvalue.
    end note
    ]
Copy elision is required where an expression is evaluated in a context requiring a constant expression ([expr.const]) and in constant initialization ([basic.start.static]).
[Note
:
Copy elision might not be performed if the same expression is evaluated in another context.
end note
]
[Example
:
class Thing {
public:
  Thing();
  ~Thing();
  Thing(const Thing&);
};

Thing f() {
  Thing t;
  return t;
}

Thing t2 = f();

struct A {
  void *p;
  constexpr A(): p(this) {}
};

constexpr A g() {
  A a;
  return a;
}

constexpr A a;          // well-formed, a.p points to a
constexpr A b = g();    // well-formed, b.p points to b

void g() {
  A c = g();            // well-formed, c.p may point to c or to an ephemeral temporary
}
Here the criteria for elision can eliminate the copying of the local automatic object t into the result object for the function call f(), which is the global object t2.
Effectively, the construction of the local object t can be viewed as directly initializing the global object t2, and that object's destruction will occur at program exit.
Adding a move constructor to Thing has the same effect, but it is the move construction from the local automatic object to t2 that is elided.
end example
]
In the following copy-initialization contexts, a move operation might be used instead of a copy operation: overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.
If the first overload resolution fails or was not performed, or if the type of the first parameter of the selected constructor is not an rvalue reference to the object's type (possibly cv-qualified), overload resolution is performed again, considering the object as an lvalue.
[Note
:
This two-stage overload resolution must be performed regardless of whether copy elision will occur.
It determines the constructor to be called if elision is not performed, and the selected constructor must be accessible even if the call is elided.
end note
]
[Example
:
class Thing {
public:
  Thing();
  ~Thing();
  Thing(Thing&&);
private:
  Thing(const Thing&);
};

Thing f(bool b) {
  Thing t;
  if (b)
    throw t;            // OK: Thing(Thing&&) used (or elided) to throw t
  return t;             // OK: Thing(Thing&&) used (or elided) to return t
}

Thing t2 = f(false);    // OK: no extra copy/move performed, t2 constructed by call to f

struct Weird {
  Weird();
  Weird(Weird&);
};

Weird g() {
  Weird w;
  return w;             // OK: first overload resolution fails, second overload resolution selects Weird(Weird&)
}
end example
]
Because only one object is destroyed instead of two, and one copy/move constructor is not executed, there is still one object destroyed for each one constructed.

16 Overloading [over]

When two or more different declarations are specified for a single name in the same scope, that name is said to be overloaded.
By extension, two declarations in the same scope that declare the same name but with different types are called overloaded declarations.
Only function and function template declarations can be overloaded; variable and type declarations cannot be overloaded.
When an overloaded function name is used in a call, which overloaded function declaration is being referenced is determined by comparing the types of the arguments at the point of use with the types of the parameters in the overloaded declarations that are visible at the point of use.
This function selection process is called overload resolution and is defined in [over.match].
[Example
:
double abs(double);
int abs(int);

abs(1);             // calls abs(int);
abs(1.0);           // calls abs(double);
end example
]

16.1 Overloadable declarations [over.load]

Not all function declarations can be overloaded.
Those that cannot be overloaded are specified here.
A program is ill-formed if it contains two such non-overloadable declarations in the same scope.
[Note
:
This restriction applies to explicit declarations in a scope, and between such declarations and declarations made through a using-declaration ([namespace.udecl]).
It does not apply to sets of functions fabricated as a result of name lookup (e.g., because of using-directives) or overload resolution (e.g., for operator functions).
end note
]
Certain function declarations cannot be overloaded:
  • Function declarations that differ only in the return type, the exception specification ([except.spec]), or both cannot be overloaded.
  • Member function declarations with the same name and the same parameter-type-list ([dcl.fct]) cannot be overloaded if any of them is a static member function declaration ([class.static]).
    Likewise, member function template declarations with the same name, the same parameter-type-list, and the same template parameter lists cannot be overloaded if any of them is a static member function template declaration.
    The types of the implicit object parameters constructed for the member functions for the purpose of overload resolution ([over.match.funcs]) are not considered when comparing parameter-type-lists for enforcement of this rule.
    In contrast, if there is no static member function declaration among a set of member function declarations with the same name and the same parameter-type-list, then these member function declarations can be overloaded if they differ in the type of their implicit object parameter.
    [Example
    :
    The following illustrates this distinction:
    class X {
      static void f();
      void f();                     // ill-formed
      void f() const;               // ill-formed
      void f() const volatile;      // ill-formed
      void g();
      void g() const;               // OK: no static g
      void g() const volatile;      // OK: no static g
    };
    end example
    ]
  • Member function declarations with the same name and the same parameter-type-list ([dcl.fct]) as well as member function template declarations with the same name, the same parameter-type-list, and the same template parameter lists cannot be overloaded if any of them, but not all, have a ref-qualifier ([dcl.fct]).
    [Example
    :
    class Y {
      void h() &;
      void h() const &;             // OK
      void h() &&;                  // OK, all declarations have a ref-qualifier
      void i() &;
      void i() const;               // ill-formed, prior declaration of i
                                    // has a ref-qualifier
    };
    end example
    ]
[Note
:
As specified in [dcl.fct], function declarations that have equivalent parameter declarations declare the same function and therefore cannot be overloaded:
  • Parameter declarations that differ only in the use of equivalent typedef “types” are equivalent.
    A typedef is not a separate type, but only a synonym for another type ([dcl.typedef]).
    [Example
    :
    typedef int Int;
    
    void f(int i);
    void f(Int i);                  // OK: redeclaration of f(int)
    void f(int i) { /* ... */ }
    void f(Int i) { /* ... */ }     // error: redefinition of f(int)
    
    end example
    ]
    Enumerations, on the other hand, are distinct types and can be used to distinguish overloaded function declarations.
    [Example
    :
    enum E { a };
    
    void f(int i) { /* ... */ }
    void f(E i)   { /* ... */ }
    end example
    ]
  • Parameter declarations that differ only in a pointer * versus an array [] are equivalent.
    That is, the array declaration is adjusted to become a pointer declaration ([dcl.fct]).
    Only the second and subsequent array dimensions are significant in parameter types ([dcl.array]).
    [Example
    :
    int f(char*);
    int f(char[]);                  // same as f(char*);
    int f(char[7]);                 // same as f(char*);
    int f(char[9]);                 // same as f(char*);
    
    int g(char(*)[10]);
    int g(char[5][10]);             // same as g(char(*)[10]);
    int g(char[7][10]);             // same as g(char(*)[10]);
    int g(char(*)[20]);             // different from g(char(*)[10]);
    
    end example
    ]
  • Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent.
    That is, the function type is adjusted to become a pointer to function type ([dcl.fct]).
    [Example
    :
    void h(int());
    void h(int (*)());              // redeclaration of h(int())
    void h(int x()) { }             // definition of h(int())
    void h(int (*x)()) { }          // ill-formed: redefinition of h(int())
    
    end example
    ]
  • Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent.
    That is, the const and volatile type-specifiers for each parameter type are ignored when determining which function is being declared, defined, or called.
    [Example
    :
    typedef const int cInt;
    
    int f (int);
    int f (const int);              // redeclaration of f(int)
    int f (int) { /* ... */ }       // definition of f(int)
    int f (cInt) { /* ... */ }      // error: redefinition of f(int)
    
    end example
    ]
    Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations.123
    In particular, for any type T, “pointer to T”, “pointer to const T”, and “pointer to volatile T” are considered distinct parameter types, as are “reference to T”, “reference to const T”, and “reference to volatile T.
  • Two parameter declarations that differ only in their default arguments are equivalent.
    [Example
    :
    Consider the following:
    void f (int i, int j);
    void f (int i, int j = 99);     // OK: redeclaration of f(int, int)
    void f (int i = 88, int j);     // OK: redeclaration of f(int, int)
    void f ();                      // OK: overloaded declaration of f
    
    void prog () {
        f (1, 2);                   // OK: call f(int, int)
        f (1);                      // OK: call f(int, int)
        f ();                       // Error: f(int, int) or f()?
    }
    end example
    ]
end note
]
When a parameter type includes a function type, such as in the case of a parameter type that is a pointer to function, the const and volatile type-specifiers at the outermost level of the parameter type specifications for the inner function type are also ignored.

16.2 Declaration matching [over.dcl]

Two function declarations of the same name refer to the same function if they are in the same scope and have equivalent parameter declarations ([over.load]).
A function member of a derived class is not in the same scope as a function member of the same name in a base class.
[Example
:
struct B {
  int f(int);
};

struct D : B {
  int f(const char*);
};
Here D​::​f(const char*) hides B​::​f(int) rather than overloading it.
void h(D* pd) {
  pd->f(1);                     // error:
                                // D​::​f(const char*) hides B​::​f(int)
  pd->B::f(1);                  // OK
  pd->f("Ben");                 // OK, calls D​::​f
}
end example
]
A locally declared function is not in the same scope as a function in a containing scope.
[Example
:
void f(const char*);
void g() {
  extern void f(int);
  f("asdf");                    // error: f(int) hides f(const char*)
                                // so there is no f(const char*) in this scope
}

void caller () {
  extern void callee(int, int);
  {
    extern void callee(int);    // hides callee(int, int)
    callee(88, 99);             // error: only callee(int) in scope
  }
}
end example
]
Different versions of an overloaded member function can be given different access rules.
[Example
:
class buffer {
private:
    char* p;
    int size;
protected:
    buffer(int s, char* store) { size = s; p = store; }
public:
    buffer(int s) { p = new char[size = s]; }
};
end example
]

16.3 Overload resolution [over.match]

Overload resolution is a mechanism for selecting the best function to call given a list of expressions that are to be the arguments of the call and a set of candidate functions that can be called based on the context of the call.
The selection criteria for the best function are the number of arguments, how well the arguments match the parameter-type-list of the candidate function, how well (for non-static member functions) the object matches the implicit object parameter, and certain other properties of the candidate function.
[Note
:
The function selected by overload resolution is not guaranteed to be appropriate for the context.
Other restrictions, such as the accessibility of the function, can make its use in the calling context ill-formed.
end note
]
Overload resolution selects the function to call in seven distinct contexts within the language:
  • invocation of a function named in the function call syntax ([over.call.func]);
  • invocation of a function call operator, a pointer-to-function conversion function, a reference-to-pointer-to-function conversion function, or a reference-to-function conversion function on a class object named in the function call syntax ([over.call.object]);
  • invocation of the operator referenced in an expression ([over.match.oper]);
  • invocation of a constructor for default- or direct-initialization ([dcl.init]) of a class object ([over.match.ctor]);
  • invocation of a user-defined conversion for copy-initialization ([dcl.init]) of a class object ([over.match.copy]);
  • invocation of a conversion function for initialization of an object of a non-class type from an expression of class type ([over.match.conv]); and
  • invocation of a conversion function for conversion to a glvalue or class prvalue to which a reference ([dcl.init.ref]) will be directly bound ([over.match.ref]).
Each of these contexts defines the set of candidate functions and the list of arguments in its own unique way.
But, once the candidate functions and argument lists have been identified, the selection of the best function is the same in all cases:
  • First, a subset of the candidate functions (those that have the proper number of arguments and meet certain other conditions) is selected to form a set of viable functions ([over.match.viable]).
  • Then the best viable function is selected based on the implicit conversion sequences ([over.best.ics]) needed to match each argument to the corresponding parameter of each viable function.
If a best viable function exists and is unique, overload resolution succeeds and produces it as the result.
Otherwise overload resolution fails and the invocation is ill-formed.
When overload resolution succeeds, and the best viable function is not accessible (Clause [class.access]) in the context in which it is used, the program is ill-formed.

16.3.1 Candidate functions and argument lists [over.match.funcs]

The subclauses of [over.match.funcs] describe the set of candidate functions and the argument list submitted to overload resolution in each of the seven contexts in which overload resolution is used.
The source transformations and constructions defined in these subclauses are only for the purpose of describing the overload resolution process.
An implementation is not required to use such transformations and constructions.
The set of candidate functions can contain both member and non-member functions to be resolved against the same argument list.
So that argument and parameter lists are comparable within this heterogeneous set, a member function is considered to have an extra parameter, called the implicit object parameter, which represents the object for which the member function has been called.
For the purposes of overload resolution, both static and non-static member functions have an implicit object parameter, but constructors do not.
Similarly, when appropriate, the context can construct an argument list that contains an implied object argument to denote the object to be operated on.
Since arguments and parameters are associated by position within their respective lists, the convention is that the implicit object parameter, if present, is always the first parameter and the implied object argument, if present, is always the first argument.
For non-static member functions, the type of the implicit object parameter is
where X is the class of which the function is a member and cv is the cv-qualification on the member function declaration.
[Example
:
For a const member function of class X, the extra parameter is assumed to have type “reference to const X.
end example
]
For conversion functions, the function is considered to be a member of the class of the implied object argument for the purpose of defining the type of the implicit object parameter.
For non-conversion functions introduced by a using-declaration into a derived class, the function is considered to be a member of the derived class for the purpose of defining the type of the implicit object parameter.
For static member functions, the implicit object parameter is considered to match any object (since if the function is selected, the object is discarded).
[Note
:
No actual type is established for the implicit object parameter of a static member function, and no attempt will be made to determine a conversion sequence for that parameter ([over.match.best]).
end note
]
During overload resolution, the implied object argument is indistinguishable from other arguments.
The implicit object parameter, however, retains its identity since no user-defined conversions can be applied to achieve a type match with it.
For non-static member functions declared without a ref-qualifier, an additional rule applies:
  • even if the implicit object parameter is not const-qualified, an rvalue can be bound to the parameter as long as in all other respects the argument can be converted to the type of the implicit object parameter.
    [Note
    :
    The fact that such an argument is an rvalue does not affect the ranking of implicit conversion sequences ([over.ics.rank]).
    end note
    ]
Because other than in list-initialization only one user-defined conversion is allowed in an implicit conversion sequence, special rules apply when selecting the best user-defined conversion ([over.match.best], [over.best.ics]).
[Example
:
class T {
public:
  T();
};

class C : T {
public:
  C(int);
};
T a = 1;            // ill-formed: T(C(1)) not tried
end example
]
In each case where a candidate is a function template, candidate function template specializations are generated using template argument deduction ([temp.over], [temp.deduct]).
Those candidates are then handled as candidate functions in the usual way.124
A given name can refer to one or more function templates and also to a set of overloaded non-template functions.
In such a case, the candidate functions generated from each function template are combined with the set of non-template candidate functions.
A defaulted move constructor or assignment operator ([class.copy]) that is defined as deleted is excluded from the set of candidate functions in all contexts.
The process of argument deduction fully determines the parameter types of the function template specializations, i.e., the parameters of function template specializations contain no template parameter types. Therefore, except where specified otherwise, function template specializations and non-template functions ([dcl.fct]) are treated equivalently for the remainder of overload resolution.

16.3.1.1 Function call syntax [over.match.call]

In a function call ([expr.call])
postfix-expression ( expression-list )
if the postfix-expression denotes a set of overloaded functions and/or function templates, overload resolution is applied as specified in [over.call.func].
If the postfix-expression denotes an object of class type, overload resolution is applied as specified in [over.call.object].
If the postfix-expression denotes the address of a set of overloaded functions and/or function templates, overload resolution is applied using that set as described above.
If the function selected by overload resolution is a non-static member function, the program is ill-formed.
[Note
:
The resolution of the address of an overload set in other contexts is described in [over.over].
end note
]

16.3.1.1.1 Call to named function [over.call.func]

Of interest in [over.call.func] are only those function calls in which the postfix-expression ultimately contains a name that denotes one or more functions that might be called.
Such a postfix-expression, perhaps nested arbitrarily deep in parentheses, has one of the following forms:
postfix-expression:
	postfix-expression . id-expression
	postfix-expression -> id-expression
	primary-expression
These represent two syntactic subcategories of function calls: qualified function calls and unqualified function calls.
In qualified function calls, the name to be resolved is an id-expression and is preceded by an -> or . operator.
Since the construct A->B is generally equivalent to (*A).B, the rest of Clause [over] assumes, without loss of generality, that all member function calls have been normalized to the form that uses an object and the . operator.
Furthermore, Clause [over] assumes that the postfix-expression that is the left operand of the . operator has type “cv T” where T denotes a class125.
Under this assumption, the id-expression in the call is looked up as a member function of T following the rules for looking up names in classes ([class.member.lookup]).
The function declarations found by that lookup constitute the set of candidate functions.
The argument list is the expression-list in the call augmented by the addition of the left operand of the . operator in the normalized member function call as the implied object argument ([over.match.funcs]).
In unqualified function calls, the name is not qualified by an -> or . operator and has the more general form of a primary-expression.
The name is looked up in the context of the function call following the normal rules for name lookup in function calls ([basic.lookup]).
The function declarations found by that lookup constitute the set of candidate functions.
Because of the rules for name lookup, the set of candidate functions consists (1) entirely of non-member functions or (2) entirely of member functions of some class T.
In case (1), the argument list is the same as the expression-list in the call.
In case (2), the argument list is the expression-list in the call augmented by the addition of an implied object argument as in a qualified function call.
If the keyword this ([class.this]) is in scope and refers to class T, or a derived class of T, then the implied object argument is (*this).
If the keyword this is not in scope or refers to another class, then a contrived object of type T becomes the implied object argument126.
If the argument list is augmented by a contrived object and overload resolution selects one of the non-static member functions of T, the call is ill-formed.
Note that cv-qualifiers on the type of objects are significant in overload resolution for both glvalue and class prvalue objects.
An implied object argument must be contrived to correspond to the implicit object parameter attributed to member functions during overload resolution.
It is not used in the call to the selected function.
Since the member functions all have the same implicit object parameter, the contrived object will not be the cause to select or reject a function.

16.3.1.1.2 Call to object of class type [over.call.object]

If the primary-expression E in the function call syntax evaluates to a class object of type “cv T”, then the set of candidate functions includes at least the function call operators of T.
The function call operators of T are obtained by ordinary lookup of the name operator() in the context of (E).operator().
In addition, for each non-explicit conversion function declared in T of the form
operator conversion-type-id () cv-qualifier ref-qualifier noexcept-specifier attribute-specifier-seq ;
where cv-qualifier is the same cv-qualification as, or a greater cv-qualification than, cv, and where conversion-type-id denotes the type “pointer to function of () returning R”, or the type “reference to pointer to function of () returning R”, or the type “reference to function of () returning R”, a surrogate call function with the unique name call-function and having the form
R call-function ( conversion-type-id  F, P a, , P a) { return F (a, , a); }
is also considered as a candidate function.
Similarly, surrogate call functions are added to the set of candidate functions for each non-explicit conversion function declared in a base class of T provided the function is not hidden within T by another intervening declaration127.
If such a surrogate call function is selected by overload resolution, the corresponding conversion function will be called to convert E to the appropriate function pointer or reference, and the function will then be invoked with the arguments of the call.
If the conversion function cannot be called (e.g., because of an ambiguity), the program is ill-formed.
The argument list submitted to overload resolution consists of the argument expressions present in the function call syntax preceded by the implied object argument (E).
[Note
:
When comparing the call against the function call operators, the implied object argument is compared against the implicit object parameter of the function call operator.
When comparing the call against a surrogate call function, the implied object argument is compared against the first parameter of the surrogate call function.
The conversion function from which the surrogate call function was derived will be used in the conversion sequence for that parameter since it converts the implied object argument to the appropriate function pointer or reference required by that first parameter.
end note
]
[Example
:
int f1(int);
int f2(float);
typedef int (*fp1)(int);
typedef int (*fp2)(float);
struct A {
  operator fp1() { return f1; }
  operator fp2() { return f2; }
} a;
int i = a(1);                   // calls f1 via pointer returned from conversion function
end example
]
Note that this construction can yield candidate call functions that cannot be differentiated one from the other by overload resolution because they have identical declarations or differ only in their return type.
The call will be ambiguous if overload resolution cannot select a match to the call that is uniquely better than such undifferentiable functions.

16.3.1.2 Operators in expressions [over.match.oper]

If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause [expr].
[Note
:
Because ., .*, and ​::​ cannot be overloaded, these operators are always built-in operators interpreted according to Clause [expr].
?: cannot be overloaded, but the rules in this subclause are used to determine the conversions to be applied to the second and third operands when they have class or enumeration type ([expr.cond]).
end note
]
[Example
:
struct String {
  String (const String&);
  String (const char*);
  operator const char* ();
};
String operator + (const String&, const String&);

void f() {
 const char* p= "one" + "two";  // ill-formed because neither operand has class or enumeration type
 int I = 1 + 1;                 // always evaluates to 2 even if class or enumeration types exist
                                // that would perform the operation.
}
end example
]
If either operand has a type that is a class or an enumeration, a user-defined operator function might be declared that implements this operator or a user-defined conversion can be necessary to convert the operand to a type that is appropriate for a built-in operator.
In this case, overload resolution is used to determine which operator function or built-in operator is to be invoked to implement the operator.
Therefore, the operator notation is first transformed to the equivalent function-call notation as summarized in Table 12 (where @ denotes one of the operators covered in the specified subclause).
However, the operands are sequenced in the order prescribed for the built-in operator (Clause [expr]).
Table 12 — Relationship between operator and function call notation
Subclause
Expression
As member function
As non-member function
@a
(a).operator@ ()
operator@(a)
a@b
(a).operator@ (b)
operator@(a, b)
a=b
(a).operator= (b)
a[b]
(a).operator[](b)
a->
(a).operator->()
a@
(a).operator@ (0)
operator@(a, 0)
For a unary operator @ with an operand of a type whose cv-unqualified version is T1, and for a binary operator @ with a left operand of a type whose cv-unqualified version is T1 and a right operand of a type whose cv-unqualified version is T2, three sets of candidate functions, designated member candidates, non-member candidates and built-in candidates, are constructed as follows:
  • If T1 is a complete class type or a class currently being defined, the set of member candidates is the result of the qualified lookup of T1​::​operator@ ([over.call.func]); otherwise, the set of member candidates is empty.
  • The set of non-member candidates is the result of the unqualified lookup of operator@ in the context of the expression according to the usual rules for name lookup in unqualified function calls ([basic.lookup.argdep]) except that all member functions are ignored.
    However, if no operand has a class type, only those non-member functions in the lookup set that have a first parameter of type T1 or “reference to cv T1”, when T1 is an enumeration type, or (if there is a right operand) a second parameter of type T2 or “reference to cv T2”, when T2 is an enumeration type, are candidate functions.
  • For the operator ,, the unary operator &, or the operator ->, the built-in candidates set is empty.
    For all other operators, the built-in candidates include all of the candidate operator functions defined in [over.built] that, compared to the given operator,
    • have the same operator name, and
    • accept the same number of operands, and
    • accept operand types to which the given operand or operands can be converted according to [over.best.ics], and
    • do not have the same parameter-type-list as any non-member candidate that is not a function template specialization.
For the built-in assignment operators, conversions of the left operand are restricted as follows:
  • no temporaries are introduced to hold the left operand, and
  • no user-defined conversions are applied to the left operand to achieve a type match with the left-most parameter of a built-in candidate.
For all other operators, no such restrictions apply.
The set of candidate functions for overload resolution is the union of the member candidates, the non-member candidates, and the built-in candidates.
The argument list contains all of the operands of the operator.
The best function from the set of candidate functions is selected according to [over.match.viable] and [over.match.best].128
[Example
:
struct A {
  operator int();
};
A operator+(const A&, const A&);
void m() {
  A a, b;
  a + b;                        // operator+(a, b) chosen over int(a) + int(b)
}
end example
]
If a built-in candidate is selected by overload resolution, the operands of class type are converted to the types of the corresponding parameters of the selected operation function, except that the second standard conversion sequence of a user-defined conversion sequence ([over.ics.user]) is not applied.
Then the operator is treated as the corresponding built-in operator and interpreted according to Clause [expr].
[Example
:
struct X {
  operator double();
};

struct Y {
  operator int*();
};

int *a = Y() + 100.0;           // error: pointer arithmetic requires integral operand
int *b = Y() + X();             // error: pointer arithmetic requires integral operand
end example
]
The second operand of operator -> is ignored in selecting an operator-> function, and is not an argument when the operator-> function is called.
When operator-> returns, the operator -> is applied to the value returned, with the original second operand.129
If the operator is the operator ,, the unary operator &, or the operator ->, and there are no viable functions, then the operator is assumed to be the built-in operator and interpreted according to Clause [expr].
[Note
:
The lookup rules for operators in expressions are different than the lookup rules for operator function names in a function call, as shown in the following example:
struct A { };
void operator + (A, A);

struct B {
  void operator + (B);
  void f ();
};

A a;

void B::f() {
  operator+ (a,a);              // error: global operator hidden by member
  a + a;                        // OK: calls global operator+
}
end note
]
If the set of candidate functions is empty, overload resolution is unsuccessful.
If the value returned by the operator-> function has class type, this may result in selecting and calling another operator-> function.
The process repeats until an operator-> function returns a value of non-class type.

16.3.1.3 Initialization by constructor [over.match.ctor]

When objects of class type are direct-initialized ([dcl.init]), copy-initialized from an expression of the same or a derived class type ([dcl.init]), or default-initialized ([dcl.init]), overload resolution selects the constructor.
For direct-initialization or default-initialization that is not in the context of copy-initialization, the candidate functions are all the constructors of the class of the object being initialized.
For copy-initialization, the candidate functions are all the converting constructors ([class.conv.ctor]) of that class.
The argument list is the expression-list or assignment-expression of the initializer.

16.3.1.4 Copy-initialization of class by user-defined conversion [over.match.copy]

Under the conditions specified in [dcl.init], as part of a copy-initialization of an object of class type, a user-defined conversion can be invoked to convert an initializer expression to the type of the object being initialized.
Overload resolution is used to select the user-defined conversion to be invoked.
[Note
:
The conversion performed for indirect binding to a reference to a possibly cv-qualified class type is determined in terms of a corresponding non-reference copy-initialization.
end note
]
Assuming that “cv1 T” is the type of the object being initialized, with T a class type, the candidate functions are selected as follows:
  • The converting constructors ([class.conv.ctor]) of T are candidate functions.
  • When the type of the initializer expression is a class type “cv S”, the non-explicit conversion functions of S and its base classes are considered.
    When initializing a temporary to be bound to the first parameter of a constructor where the parameter is of type “reference to possibly cv-qualified T” and the constructor is called with a single argument in the context of direct-initialization of an object of type “cv2 T”, explicit conversion functions are also considered.
    Those that are not hidden within S and yield a type whose cv-unqualified version is the same type as T or is a derived class thereof are candidate functions.
    Conversion functions that return “reference to X” return lvalues or xvalues, depending on the type of reference, of type X and are therefore considered to yield X for this process of selecting candidate functions.
In both cases, the argument list has one argument, which is the initializer expression.
[Note
:
This argument will be compared against the first parameter of the constructors and against the implicit object parameter of the conversion functions.
end note
]

16.3.1.5 Initialization by conversion function [over.match.conv]

Under the conditions specified in [dcl.init], as part of an initialization of an object of non-class type, a conversion function can be invoked to convert an initializer expression of class type to the type of the object being initialized.
Overload resolution is used to select the conversion function to be invoked.
Assuming that “cv1 T” is the type of the object being initialized, and “cv S” is the type of the initializer expression, with S a class type, the candidate functions are selected as follows:
  • The conversion functions of S and its base classes are considered.
    Those non-explicit conversion functions that are not hidden within S and yield type T or a type that can be converted to type T via a standard conversion sequence ([over.ics.scs]) are candidate functions.
    For direct-initialization, those explicit conversion functions that are not hidden within S and yield type T or a type that can be converted to type T with a qualification conversion ([conv.qual]) are also candidate functions.
    Conversion functions that return a cv-qualified type are considered to yield the cv-unqualified version of that type for this process of selecting candidate functions.
    Conversion functions that return “reference to cv2 X” return lvalues or xvalues, depending on the type of reference, of type “cv2 X” and are therefore considered to yield X for this process of selecting candidate functions.
The argument list has one argument, which is the initializer expression.
[Note
:
This argument will be compared against the implicit object parameter of the conversion functions.
end note
]

16.3.1.6 Initialization by conversion function for direct reference binding [over.match.ref]

Under the conditions specified in [dcl.init.ref], a reference can be bound directly to a glvalue or class prvalue that is the result of applying a conversion function to an initializer expression.
Overload resolution is used to select the conversion function to be invoked.
Assuming that “reference to cv1 T” is the type of the reference being initialized, and “cv S” is the type of the initializer expression, with S a class type, the candidate functions are selected as follows:
  • The conversion functions of S and its base classes are considered.
    Those non-explicit conversion functions that are not hidden within S and yield type “lvalue reference to cv2 T2” (when initializing an lvalue reference or an rvalue reference to function) or “cv2 T2” or “rvalue reference to cv2 T2” (when initializing an rvalue reference or an lvalue reference to function), where “cv1 T” is reference-compatible ([dcl.init.ref]) with “cv2 T2”, are candidate functions.
    For direct-initialization, those explicit conversion functions that are not hidden within S and yield type “lvalue reference to cv2 T2” or “cv2 T2” or “rvalue reference to cv2 T2”, respectively, where T2 is the same type as T or can be converted to type T with a qualification conversion ([conv.qual]), are also candidate functions.
The argument list has one argument, which is the initializer expression.
[Note
:
This argument will be compared against the implicit object parameter of the conversion functions.
end note
]

16.3.1.7 Initialization by list-initialization [over.match.list]

When objects of non-aggregate class type T are list-initialized such that [dcl.init.list] specifies that overload resolution is performed according to the rules in this section, overload resolution selects the constructor in two phases:
  • Initially, the candidate functions are the initializer-list constructors ([dcl.init.list]) of the class T and the argument list consists of the initializer list as a single argument.
  • If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list.
If the initializer list has no elements and T has a default constructor, the first phase is omitted.
In copy-list-initialization, if an explicit constructor is chosen, the initialization is ill-formed.
[Note
:
This differs from other situations ([over.match.ctor], [over.match.copy]), where only converting constructors are considered for copy-initialization.
This restriction only applies if this initialization is part of the final result of overload resolution.
end note
]

16.3.1.8 Class template argument deduction [over.match.class.deduct]

A set of functions and function templates is formed comprising:
  • For each constructor of the primary class template designated by the template-name, if the template is defined, a function template with the following properties:
    • The template parameters are the template parameters of the class template followed by the template parameters (including default template arguments) of the constructor, if any.
    • The types of the function parameters are those of the constructor.
    • The return type is the class template specialization designated by the template-name and template arguments corresponding to the template parameters obtained from the class template.
  • If the primary class template C is not defined or does not declare any constructors, an additional function template derived as above from a hypothetical constructor C().
  • An additional function template derived as above from a hypothetical constructor C(C), called the copy deduction candidate.
  • For each deduction-guide, a function or function template with the following properties:
Initialization and overload resolution are performed as described in [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list] (as appropriate for the type of initialization performed) for an object of a hypothetical class type, where the selected functions and function templates are considered to be the constructors of that class type for the purpose of forming an overload set, and the initializer is provided by the context in which class template argument deduction was performed.
Each such notional constructor is considered to be explicit if the function or function template was generated from a constructor or deduction-guide that was declared explicit.
All such notional constructors are considered to be public members of the hypothetical class type.
[Example
:
template <class T> struct A {
  explicit A(const T&, ...) noexcept;  // #1
  A(T&&, ...);                         // #2
};

int i;
A a1 = { i, i };    // error: explicit constructor #1 selected in copy-list-initialization during deduction,
                    // cannot deduce from non-forwarding rvalue reference in #2

A a2{i, i};         // OK, #1 deduces to A<int> and also initializes
A a3{0, i};         // OK, #2 deduces to A<int> and also initializes
A a4 = {0, i};      // OK, #2 deduces to A<int> and also initializes

template <class T> A(const T&, const T&) -> A<T&>;  // #3
template <class T> explicit A(T&&, T&&) -> A<T>;    // #4

A a5 = {0, 1};      // error: explicit deduction guide #4 selected in copy-list-initialization during deduction
A a6{0,1};          // OK, #4 deduces to A<int> and #2 initializes
A a7 = {0, i};      // error: #3 deduces to A<int&>, #1 and #2 declare same constructor
A a8{0,i};          // error: #3 deduces to A<int&>, #1 and #2 declare same constructor

template <class T> struct B {
  template <class U> using TA = T;
  template <class U> B(U, TA<U>);
};

B b{(int*)0, (char*)0};         // OK, deduces B<char*>
end example
]

16.3.2 Viable functions [over.match.viable]

From the set of candidate functions constructed for a given context ([over.match.funcs]), a set of viable functions is chosen, from which the best function will be selected by comparing argument conversion sequences for the best fit ([over.match.best]).
The selection of viable functions considers relationships between arguments and function parameters other than the ranking of conversion sequences.
First, to be a viable function, a candidate function shall have enough parameters to agree in number with the arguments in the list.
  • If there are m arguments in the list, all candidate functions having exactly m parameters are viable.
  • A candidate function having fewer than m parameters is viable only if it has an ellipsis in its parameter list ([dcl.fct]).
    For the purposes of overload resolution, any argument for which there is no corresponding parameter is considered to “match the ellipsis” ([over.ics.ellipsis]) .
  • A candidate function having more than m parameters is viable only if the (m+1)-st parameter has a default argument ([dcl.fct.default]).130
    For the purposes of overload resolution, the parameter list is truncated on the right, so that there are exactly m parameters.
Second, for F to be a viable function, there shall exist for each argument an implicit conversion sequence ([over.best.ics]) that converts that argument to the corresponding parameter of F.
If the parameter has reference type, the implicit conversion sequence includes the operation of binding the reference, and the fact that an lvalue reference to non-const cannot be bound to an rvalue and that an rvalue reference cannot be bound to an lvalue can affect the viability of the function (see [over.ics.ref]).
According to [dcl.fct.default], parameters following the (m+1)-st parameter must also have default arguments.

16.3.3 Best viable function [over.match.best]

Define ICSi(F) as follows:
  • If F is a static member function, ICS1(F) is defined such that ICS1(F) is neither better nor worse than ICS1(G) for any function G, and, symmetrically, ICS1(G) is neither better nor worse than ICS1(F);131 otherwise,
  • let ICSi(F) denote the implicit conversion sequence that converts the i-th argument in the list to the type of the i-th parameter of viable function F.
    [over.best.ics] defines the implicit conversion sequences and [over.ics.rank] defines what it means for one implicit conversion sequence to be a better conversion sequence or worse conversion sequence than another.
Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then
  • for some argument j, ICSj(F1) is a better conversion sequence than ICSj(F2), or, if not that,
  • the context is an initialization by user-defined conversion (see [dcl.init], [over.match.conv], and [over.match.ref]) and the standard conversion sequence from the return type of F1 to the destination type (i.e., the type of the entity being initialized) is a better conversion sequence than the standard conversion sequence from the return type of F2 to the destination type
    [Example
    :
    struct A {
      A();
      operator int();
      operator double();
    } a;
    int i = a;          // a.operator int() followed by no conversion is better than
                        // a.operator double() followed by a conversion to int
    float x = a;        // ambiguous: both possibilities require conversions,
                        // and neither is better than the other
    
    end example
    ]
    or, if not that,
  • the context is an initialization by conversion function for direct reference binding ([over.match.ref]) of a reference to function type, the return type of F1 is the same kind of reference (i.e. lvalue or rvalue) as the reference being initialized, and the return type of F2 is not
    [Example
    :
    template <class T> struct A {
      operator T&();    // #1
      operator T&&();   // #2
    };
    typedef int Fn();
    A<Fn> a;
    Fn& lf = a;         // calls #1
    Fn&& rf = a;        // calls #2
    
    end example
    ]
    or, if not that,
  • F1 is not a function template specialization and F2 is a function template specialization, or, if not that,
  • F1 and F2 are function template specializations, and the function template for F1 is more specialized than the template for F2 according to the partial ordering rules described in [temp.func.order], or, if not that,
  • F1 is generated from a deduction-guide ([over.match.class.deduct]) and F2 is not, or, if not that,
  • F1 is the copy deduction candidate ([over.match.class.deduct]) and F2 is not, or, if not that,
  • F1 is generated from a non-template constructor and F2 is generated from a constructor template.
    [Example
    :
    template <class T> struct A {
      using value_type = T;
      A(value_type);    // #1
      A(const A&);      // #2
      A(T, T, int);     // #3
      template<class U>
        A(int, T, U);   // #4
      // #5 is the copy deduction candidate, A(A)
    };
    
    A x(1, 2, 3);       // uses #3, generated from a non-template constructor
    
    template <class T>
    A(T) -> A<T>;       // #6, less specialized than #5
    
    A a(42);            // uses #6 to deduce A<int> and #1 to initialize
    A b = a;            // uses #5 to deduce A<int> and #2 to initialize
    
    template <class T>
    A(A<T>) -> A<A<T>>; // #7, as specialized as #5
    
    A b2 = a;           // uses #7 to deduce A<A<int>> and #1 to initialize
    
    end example
    ]
If there is exactly one viable function that is a better function than all other viable functions, then it is the one selected by overload resolution; otherwise the call is ill-formed.132
[Example
:
void Fcn(const int*,  short);
void Fcn(int*, int);

int i;
short s = 0;

void f() {
  Fcn(&i, s);       // is ambiguous because &i  int* is better than &i  const int*
                    // but s  short is also better than s  int

  Fcn(&i, 1L);      // calls Fcn(int*, int), because &i  int* is better than &i  const int*
                    // and 1L  short and 1L  int are indistinguishable

  Fcn(&i, 'c');     // calls Fcn(int*, int), because &i  int* is better than &i  const int*
                    // and c  int is better than c  short
}
end example
]
If the best viable function resolves to a function for which multiple declarations were found, and if at least two of these declarations — or the declarations they refer to in the case of using-declarations — specify a default argument that made the function viable, the program is ill-formed.
[Example
:
namespace A {
  extern "C" void f(int = 5);
}
namespace B {
  extern "C" void f(int = 5);
}

using A::f;
using B::f;

void use() {
  f(3);             // OK, default argument was not used for viability
  f();              // Error: found default argument twice
}
end example
]
If a function is a static member function, this definition means that the first argument, the implied object argument, has no effect in the determination of whether the function is better or worse than any other function.
The algorithm for selecting the best viable function is linear in the number of viable functions.
Run a simple tournament to find a function W that is not worse than any opponent it faced.
Although another function F that W did not face might be at least as good as W, F cannot be the best function because at some point in the tournament F encountered another function G such that F was not better than G.
Hence, W is either the best function or there is no best function.
So, make a second pass over the viable functions to verify that W is better than all other functions.

16.3.3.1 Implicit conversion sequences [over.best.ics]

An implicit conversion sequence is a sequence of conversions used to convert an argument in a function call to the type of the corresponding parameter of the function being called.
The sequence of conversions is an implicit conversion as defined in Clause [conv], which means it is governed by the rules for initialization of an object or reference by a single expression ([dcl.init], [dcl.init.ref]).
Implicit conversion sequences are concerned only with the type, cv-qualification, and value category of the argument and how these are converted to match the corresponding properties of the parameter.
Other properties, such as the lifetime, storage class, alignment, accessibility of the argument, whether the argument is a bit-field, and whether a function is deleted ([dcl.fct.def.delete]), are ignored.
So, although an implicit conversion sequence can be defined for a given argument-parameter pair, the conversion from the argument to the parameter might still be ill-formed in the final analysis.
However, if the target is
  • the first parameter of a constructor or
  • the implicit object parameter of a user-defined conversion function
and the constructor or user-defined conversion function is a candidate by user-defined conversion sequences are not considered.
[Note
:
These rules prevent more than one user-defined conversion from being applied during overload resolution, thereby avoiding infinite recursion.
end note
]
[Example
:
  struct Y { Y(int); };
  struct A { operator int(); };
  Y y1 = A();       // error: A​::​operator int() is not a candidate

  struct X { };
  struct B { operator X(); };
  B b;
  X x({b});         // error: B​::​operator X() is not a candidate
end example
]
For the case where the parameter type is a reference, see [over.ics.ref].
When the parameter type is not a reference, the implicit conversion sequence models a copy-initialization of the parameter from the argument expression.
The implicit conversion sequence is the one required to convert the argument expression to a prvalue of the type of the parameter.
[Note
:
When the parameter has a class type, this is a conceptual conversion defined for the purposes of Clause [over]; the actual initialization is defined in terms of constructors and is not a conversion.
end note
]
Any difference in top-level cv-qualification is subsumed by the initialization itself and does not constitute a conversion.
[Example
:
A parameter of type A can be initialized from an argument of type const A.
The implicit conversion sequence for that case is the identity sequence; it contains no “conversion” from const A to A.
end example
]
When the parameter has a class type and the argument expression has the same type, the implicit conversion sequence is an identity conversion.
When the parameter has a class type and the argument expression has a derived class type, the implicit conversion sequence is a derived-to-base Conversion from the derived class to the base class.
[Note
:
There is no such standard conversion; this derived-to-base Conversion exists only in the description of implicit conversion sequences.
end note
]
A derived-to-base Conversion has Conversion rank ([over.ics.scs]).
In all contexts, when converting to the implicit object parameter or when converting to the left operand of an assignment operation only standard conversion sequences are allowed.
If no conversions are required to match an argument to a parameter type, the implicit conversion sequence is the standard conversion sequence consisting of the identity conversion ([over.ics.scs]).
If no sequence of conversions can be found to convert an argument to a parameter type, an implicit conversion sequence cannot be formed.
If several different sequences of conversions exist that each convert the argument to the parameter type, the implicit conversion sequence associated with the parameter is defined to be the unique conversion sequence designated the ambiguous conversion sequence.
For the purpose of ranking implicit conversion sequences as described in [over.ics.rank], the ambiguous conversion sequence is treated as a user-defined conversion sequence that is indistinguishable from any other user-defined conversion sequence.
[Note
:
This rule prevents a function from becoming non-viable because of an ambiguous conversion sequence for one of its parameters.
[Example
:
class B;
class A { A (B&);};
class B { operator A (); };
class C { C (B&); };
void f(A) { }
void f(C) { }
B b;
f(b);               // ill-formed: ambiguous because there is a conversion b  C (via constructor)
                    // and an (ambiguous) conversion b  A (via constructor or conversion function)
void f(B) { }
f(b);               // OK, unambiguous
end example
]
end note
]
If a function that uses the ambiguous conversion sequence is selected as the best viable function, the call will be ill-formed because the conversion of one of the arguments in the call is ambiguous.
The three forms of implicit conversion sequences mentioned above are defined in the following subclauses.

16.3.3.1.1 Standard conversion sequences [over.ics.scs]

Table 13 summarizes the conversions defined in Clause [conv] and partitions them into four disjoint categories: Lvalue Transformation, Qualification Adjustment, Promotion, and Conversion.
[Note
:
These categories are orthogonal with respect to value category, cv-qualification, and data representation: the Lvalue Transformations do not change the cv-qualification or data representation of the type; the Qualification Adjustments do not change the value category or data representation of the type; and the Promotions and Conversions do not change the value category or cv-qualification of the type.
end note
]
[Note
:
As described in Clause [conv], a standard conversion sequence is either the Identity conversion by itself (that is, no conversion) or consists of one to three conversions from the other four categories.
If there are two or more conversions in the sequence, the conversions are applied in the canonical order: Lvalue Transformation, Promotion or Conversion, Qualification Adjustment.
end note
]
Each conversion in Table 13 also has an associated rank (Exact Match, Promotion, or Conversion).
These are used to rank standard conversion sequences ([over.ics.rank]).
The rank of a conversion sequence is determined by considering the rank of each conversion in the sequence and the rank of any reference binding ([over.ics.ref]).
If any of those has Conversion rank, the sequence has Conversion rank; otherwise, if any of those has Promotion rank, the sequence has Promotion rank; otherwise, the sequence has Exact Match rank.
Table 13 — Conversions
Conversion
Category
Rank
Subclause
No conversions required
Identity
Lvalue-to-rvalue conversion
Array-to-pointer conversion
Lvalue Transformation
Function-to-pointer conversion
Exact Match
Qualification conversions
Function pointer conversion
Qualification Adjustment
Integral promotions
Floating-point promotion
Promotion
Promotion
Integral conversions
Floating-point conversions
Floating-integral conversions
Pointer conversions
Conversion
Conversion
Pointer to member conversions
Boolean conversions

16.3.3.1.2 User-defined conversion sequences [over.ics.user]

A user-defined conversion sequence consists of an initial standard conversion sequence followed by a user-defined conversion ([class.conv]) followed by a second standard conversion sequence.
If the user-defined conversion is specified by a constructor ([class.conv.ctor]), the initial standard conversion sequence converts the source type to the type required by the argument of the constructor.
If the user-defined conversion is specified by a conversion function ([class.conv.fct]), the initial standard conversion sequence converts the source type to the implicit object parameter of the conversion function.
The second standard conversion sequence converts the result of the user-defined conversion to the target type for the sequence.
Since an implicit conversion sequence is an initialization, the special rules for initialization by user-defined conversion apply when selecting the best user-defined conversion for a user-defined conversion sequence (see [over.match.best] and [over.best.ics]).
If the user-defined conversion is specified by a specialization of a conversion function template, the second standard conversion sequence shall have exact match rank.
A conversion of an expression of class type to the same class type is given Exact Match rank, and a conversion of an expression of class type to a base class of that type is given Conversion rank, in spite of the fact that a constructor (i.e., a user-defined conversion function) is called for those cases.

16.3.3.1.3 Ellipsis conversion sequences [over.ics.ellipsis]

An ellipsis conversion sequence occurs when an argument in a function call is matched with the ellipsis parameter specification of the function called (see [expr.call]).

16.3.3.1.4 Reference binding [over.ics.ref]

When a parameter of reference type binds directly ([dcl.init.ref]) to an argument expression, the implicit conversion sequence is the identity conversion, unless the argument expression has a type that is a derived class of the parameter type, in which case the implicit conversion sequence is a derived-to-base Conversion ([over.best.ics]).
[Example
:
struct A {};
struct B : public A {} b;
int f(A&);
int f(B&);
int i = f(b);       // calls f(B&), an exact match, rather than f(A&), a conversion
end example
]
If the parameter binds directly to the result of applying a conversion function to the argument expression, the implicit conversion sequence is a user-defined conversion sequence ([over.ics.user]), with the second standard conversion sequence either an identity conversion or, if the conversion function returns an entity of a type that is a derived class of the parameter type, a derived-to-base Conversion.
When a parameter of reference type is not bound directly to an argument expression, the conversion sequence is the one required to convert the argument expression to the referenced type according to [over.best.ics].
Conceptually, this conversion sequence corresponds to copy-initializing a temporary of the referenced type with the argument expression.
Any difference in top-level cv-qualification is subsumed by the initialization itself and does not constitute a conversion.
Except for an implicit object parameter, for which see [over.match.funcs], a standard conversion sequence cannot be formed if it requires binding an lvalue reference other than a reference to a non-volatile const type to an rvalue or binding an rvalue reference to an lvalue other than a function lvalue.
[Note
:
This means, for example, that a candidate function cannot be a viable function if it has a non-const lvalue reference parameter (other than the implicit object parameter) and the corresponding argument would require a temporary to be created to initialize the lvalue reference (see [dcl.init.ref]).
end note
]
Other restrictions on binding a reference to a particular argument that are not based on the types of the reference and the argument do not affect the formation of a standard conversion sequence, however.
[Example
:
A function with an “lvalue reference to int” parameter can be a viable candidate even if the corresponding argument is an int bit-field.
The formation of implicit conversion sequences treats the int bit-field as an int lvalue and finds an exact match with the parameter.
If the function is selected by overload resolution, the call will nonetheless be ill-formed because of the prohibition on binding a non-const lvalue reference to a bit-field ([dcl.init.ref]).
end example
]

16.3.3.1.5 List-initialization sequence [over.ics.list]

When an argument is an initializer list ([dcl.init.list]), it is not an expression and special rules apply for converting it to a parameter type.
If the parameter type is an aggregate class X and the initializer list has a single element of type cv U, where U is X or a class derived from X, the implicit conversion sequence is the one required to convert the element to the parameter type.
Otherwise, if the parameter type is a character array133 and the initializer list has a single element that is an appropriately-typed string literal ([dcl.init.string]), the implicit conversion sequence is the identity conversion.
Otherwise, if the parameter type is std​::​initializer_­list<X> and all the elements of the initializer list can be implicitly converted to X, the implicit conversion sequence is the worst conversion necessary to convert an element of the list to X, or if the initializer list has no elements, the identity conversion.
This conversion can be a user-defined conversion even in the context of a call to an initializer-list constructor.
[Example
:
void f(std::initializer_list<int>);
f( {} );                // OK: f(initializer_­list<int>) identity conversion
f( {1,2,3} );           // OK: f(initializer_­list<int>) identity conversion
f( {'a','b'} );         // OK: f(initializer_­list<int>) integral promotion
f( {1.0} );             // error: narrowing

struct A {
  A(std::initializer_list<double>);             // #1
  A(std::initializer_list<complex<double>>);    // #2
  A(std::initializer_list<std::string>);        // #3
};
A a{ 1.0,2.0 };         // OK, uses #1

void g(A);
g({ "foo", "bar" });    // OK, uses #3

typedef int IA[3];
void h(const IA&);
h({ 1, 2, 3 });         // OK: identity conversion
end example
]
Otherwise, if the parameter type is “array of N X”, if there exists an implicit conversion sequence for each element of the array from the corresponding element of the initializer list (or from {} if there is no such element), the implicit conversion sequence is the worst such implicit conversion sequence.
Otherwise, if the parameter is a non-aggregate class X and overload resolution per [over.match.list] chooses a single best constructor C of X to perform the initialization of an object of type X from the argument initializer list:
  • If C is not an initializer-list constructor and the initializer list has a single element of type cv U, where U is X or a class derived from X, the implicit conversion sequence has Exact Match rank if U is X, or Conversion rank if U is derived from X.
  • Otherwise, the implicit conversion sequence is a user-defined conversion sequence with the second standard conversion sequence an identity conversion.
If multiple constructors are viable but none is better than the others, the implicit conversion sequence is the ambiguous conversion sequence.
User-defined conversions are allowed for conversion of the initializer list elements to the constructor parameter types except as noted in [over.best.ics].
[Example
:
struct A {
  A(std::initializer_list<int>);
};
void f(A);
f( {'a', 'b'} );        // OK: f(A(std​::​initializer_­list<int>)) user-defined conversion

struct B {
  B(int, double);
};
void g(B);
g( {'a', 'b'} );        // OK: g(B(int, double)) user-defined conversion
g( {1.0, 1.0} );        // error: narrowing

void f(B);
f( {'a', 'b'} );        // error: ambiguous f(A) or f(B)

struct C {
  C(std::string);
};
void h(C);
h({"foo"});             // OK: h(C(std​::​string("foo")))

struct D {
  D(A, C);
};
void i(D);
i({ {1,2}, {"bar"} });  // OK: i(D(A(std​::​initializer_­list<int>{1,2}), C(std​::​string("bar"))))
end example
]
Otherwise, if the parameter has an aggregate type which can be initialized from the initializer list according to the rules for aggregate initialization ([dcl.init.aggr]), the implicit conversion sequence is a user-defined conversion sequence with the second standard conversion sequence an identity conversion.
[Example
:
struct A {
  int m1;
  double m2;
};

void f(A);
f( {'a', 'b'} );        // OK: f(A(int,double)) user-defined conversion
f( {1.0} );             // error: narrowing
end example
]
Otherwise, if the parameter is a reference, see [over.ics.ref].
[Note
:
The rules in this section will apply for initializing the underlying temporary for the reference.
end note
]
[Example
:
struct A {
  int m1;
  double m2;
};

void f(const A&);
f( {'a', 'b'} );        // OK: f(A(int,double)) user-defined conversion
f( {1.0} );             // error: narrowing

void g(const double &);
g({1});                 // same conversion as int to double
end example
]
Otherwise, if the parameter type is not a class:
  • if the initializer list has one element that is not itself an initializer list, the implicit conversion sequence is the one required to convert the element to the parameter type;
    [Example
    :
    void f(int);
    f( {'a'} );             // OK: same conversion as char to int
    f( {1.0} );             // error: narrowing
    
    end example
    ]
  • if the initializer list has no elements, the implicit conversion sequence is the identity conversion.
    [Example
    :
    void f(int);
    f( { } );               // OK: identity conversion
    
    end example
    ]
In all cases other than those enumerated above, no conversion is possible.
Since there are no parameters of array type, this will only occur as the referenced type of a reference parameter.

16.3.3.2 Ranking implicit conversion sequences [over.ics.rank]

This subclause defines a partial ordering of implicit conversion sequences based on the relationships better conversion sequence and better conversion.
If an implicit conversion sequence S1 is defined by these rules to be a better conversion sequence than S2, then it is also the case that S2 is a worse conversion sequence than S1.
If conversion sequence S1 is neither better than nor worse than conversion sequence S2, S1 and S2 are said to be indistinguishable conversion sequences.
When comparing the basic forms of implicit conversion sequences (as defined in [over.best.ics])
  • a standard conversion sequence ([over.ics.scs]) is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and
  • a user-defined conversion sequence ([over.ics.user]) is a better conversion sequence than an ellipsis conversion sequence ([over.ics.ellipsis]).
Two implicit conversion sequences of the same form are indistinguishable conversion sequences unless one of the following rules applies:
  • List-initialization sequence L1 is a better conversion sequence than list-initialization sequence L2 if
    • L1 converts to std​::​initializer_­list<X> for some X and L2 does not, or, if not that,
    • L1 converts to type “array of N1 T”, L2 converts to type “array of N2 T”, and N1 is smaller than N2,
    even if one of the other rules in this paragraph would otherwise apply.
    [Example
    :
      void f1(int);                                 // #1
      void f1(std::initializer_list<long>);         // #2
      void g1() { f1({42}); }                       // chooses #2
    
      void f2(std::pair<const char*, const char*>); // #3
      void f2(std::initializer_list<std::string>);  // #4
      void g2() { f2({"foo","bar"}); }              // chooses #4
    
    end example
    ]
  • Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if
    • S1 is a proper subsequence of S2 (comparing the conversion sequences in the canonical form defined by [over.ics.scs], excluding any Lvalue Transformation; the identity conversion sequence is considered to be a subsequence of any non-identity conversion sequence) or, if not that,
    • the rank of S1 is better than the rank of S2, or S1 and S2 have the same rank and are distinguishable by the rules in the paragraph below, or, if not that,
    • S1 and S2 are reference bindings ([dcl.init.ref]) and neither refers to an implicit object parameter of a non-static member function declared without a ref-qualifier, and S1 binds an rvalue reference to an rvalue and S2 binds an lvalue reference
      [Example
      :
      int i;
      int f1();
      int&& f2();
      int g(const int&);
      int g(const int&&);
      int j = g(i);                   // calls g(const int&)
      int k = g(f1());                // calls g(const int&&)
      int l = g(f2());                // calls g(const int&&)
      
      struct A {
        A& operator<<(int);
        void p() &;
        void p() &&;
      };
      A& operator<<(A&&, char);
      A() << 1;                       // calls A​::​operator<<(int)
      A() << 'c';                     // calls operator<<(A&&, char)
      A a;
      a << 1;                         // calls A​::​operator<<(int)
      a << 'c';                       // calls A​::​operator<<(int)
      A().p();                        // calls A​::​p()&&
      a.p();                          // calls A​::​p()&
      
      end example
      ]
      or, if not that,
    • S1 and S2 are reference bindings ([dcl.init.ref]) and S1 binds an lvalue reference to a function lvalue and S2 binds an rvalue reference to a function lvalue
      [Example
      :
      int f(void(&)());               // #1
      int f(void(&&)());              // #2
      void g();
      int i1 = f(g);                  // calls #1
      
      end example
      ]
      or, if not that,
    • S1 and S2 differ only in their qualification conversion and yield similar types T1 and T2 ([conv.qual]), respectively, and the cv-qualification signature of type T1 is a proper subset of the cv-qualification signature of type T2
      [Example
      :
      int f(const volatile int *);
      int f(const int *);
      int i;
      int j = f(&i);                  // calls f(const int*)
      
      end example
      ]
      or, if not that,
    • S1 and S2 are reference bindings ([dcl.init.ref]), and the types to which the references refer are the same type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers is more cv-qualified than the type to which the reference initialized by S1 refers.
      [Example
      :
      int f(const int &);
      int f(int &);
      int g(const int &);
      int g(int);
      
      int i;
      int j = f(i);                   // calls f(int &)
      int k = g(i);                   // ambiguous
      
      struct X {
        void f() const;
        void f();
      };
      void g(const X& a, X b) {
        a.f();                        // calls X​::​f() const
        b.f();                        // calls X​::​f()
      }
      end example
      ]
  • User-defined conversion sequence U1 is a better conversion sequence than another user-defined conversion sequence U2 if they contain the same user-defined conversion function or constructor or they initialize the same class in an aggregate initialization and in either case the second standard conversion sequence of U1 is better than the second standard conversion sequence of U2.
    [Example
    :
    struct A {
      operator short();
    } a;
    int f(int);
    int f(float);
    int i = f(a);                   // calls f(int), because short  int is
                                    // better than short  float.
    
    end example
    ]
Standard conversion sequences are ordered by their ranks: an Exact Match is a better conversion than a Promotion, which is a better conversion than a Conversion.
Two conversion sequences with the same rank are indistinguishable unless one of the following rules applies:
  • A conversion that does not convert a pointer, a pointer to member, or std​::​nullptr_­t to bool is better than one that does.
  • A conversion that promotes an enumeration whose underlying type is fixed to its underlying type is better than one that promotes to the promoted underlying type, if the two are different.
  • If class B is derived directly or indirectly from class A, conversion of B* to A* is better than conversion of B* to void*, and conversion of A* to void* is better than conversion of B* to void*.
  • If class B is derived directly or indirectly from class A and class C is derived directly or indirectly from B,
    • conversion of C* to B* is better than conversion of C* to A*,
      [Example
      :
      struct A {};
      struct B : public A {};
      struct C : public B {};
      C* pc;
      int f(A*);
      int f(B*);
      int i = f(pc);                  // calls f(B*)
      
      end example
      ]
    • binding of an expression of type C to a reference to type B is better than binding an expression of type C to a reference to type A,
    • conversion of A​::​* to B​::​* is better than conversion of A​::​* to C​::​*,
    • conversion of C to B is better than conversion of C to A,
    • conversion of B* to A* is better than conversion of C* to A*,
    • binding of an expression of type B to a reference to type A is better than binding an expression of type C to a reference to type A,
    • conversion of B​::​* to C​::​* is better than conversion of A​::​* to C​::​*, and
    • conversion of B to A is better than conversion of C to A.
    [Note
    :
    Compared conversion sequences will have different source types only in the context of comparing the second standard conversion sequence of an initialization by user-defined conversion (see [over.match.best]); in all other contexts, the source types will be the same and the target types will be different.
    end note
    ]

16.4 Address of overloaded function [over.over]

A use of an overloaded function name without arguments is resolved in certain contexts to a function, a pointer to function or a pointer to member function for a specific function from the overload set.
A function template name is considered to name a set of overloaded functions in such contexts.
A function with type F is selected for the function type FT of the target type required in the context if F (after possibly applying the function pointer conversion ([conv.fctptr])) is identical to FT.
[Note
:
That is, the class of which the function is a member is ignored when matching a pointer-to-member-function type.
end note
]
The target can be
The overloaded function name can be preceded by the & operator.
An overloaded function name shall not be used without arguments in contexts other than those listed.
[Note
:
Any redundant set of parentheses surrounding the overloaded function name is ignored ([expr.prim]).
end note
]
If the name is a function template, template argument deduction is done ([temp.deduct.funcaddr]), and if the argument deduction succeeds, the resulting template argument list is used to generate a single function template specialization, which is added to the set of overloaded functions considered.
[Note
:
As described in [temp.arg.explicit], if deduction fails and the function template name is followed by an explicit template argument list, the template-id is then examined to see whether it identifies a single function template specialization.
If it does, the template-id is considered to be an lvalue for that function template specialization.
The target type is not used in that determination.
end note
]
Non-member functions and static member functions match targets of function pointer type or reference to function type.
Non-static member functions match targets of pointer to member function type.
If a non-static member function is selected, the reference to the overloaded function name is required to have the form of a pointer to member as described in [expr.unary.op].
If more than one function is selected, any function template specializations in the set are eliminated if the set also contains a function that is not a function template specialization, and any given function template specialization F1 is eliminated if the set contains a second function template specialization whose function template is more specialized than the function template of F1 according to the partial ordering rules of [temp.func.order].
After such eliminations, if any, there shall remain exactly one selected function.
[Example
:
int f(double);
int f(int);
int (*pfd)(double) = &f;        // selects f(double)
int (*pfi)(int) = &f;           // selects f(int)
int (*pfe)(...) = &f;           // error: type mismatch
int (&rfi)(int) = f;            // selects f(int)
int (&rfd)(double) = f;         // selects f(double)
void g() {
  (int (*)(int))&f;             // cast expression as selector
}
The initialization of pfe is ill-formed because no f() with type int(...) has been declared, and not because of any ambiguity.
For another example,
struct X {
  int f(int);
  static int f(long);
};

int (X::*p1)(int)  = &X::f;     // OK
int    (*p2)(int)  = &X::f;     // error: mismatch
int    (*p3)(long) = &X::f;     // OK
int (X::*p4)(long) = &X::f;     // error: mismatch
int (X::*p5)(int)  = &(X::f);   // error: wrong syntax for
                                // pointer to member
int    (*p6)(long) = &(X::f);   // OK
end example
]
[Note
:
If f() and g() are both overloaded functions, the cross product of possibilities must be considered to resolve f(&g), or the equivalent expression f(g).
end note
]
[Note
:
Even if B is a public base of D, we have
D* f();
B* (*p1)() = &f;                // error

void g(D*);
void (*p2)(B*) = &g;            // error
end note
]

16.5 Overloaded operators [over.oper]

A function declaration having one of the following operator-function-ids as its name declares an operator function.
A function template declaration having one of the following operator-function-ids as its name declares an operator function template.
A specialization of an operator function template is also an operator function.
An operator function is said to implement the operator named in its operator-function-id.
operator-function-id:
	operator operator
operator: one of
	new	delete	new[]	delete[]
	+	-	*	/	%	^	&	|	~
	!	=	<	>	+=	-=	*=	/=	%=
	^=	&=	|=	<<	>>	>>=	<<=	==	!=
	<=	>=	&&	||	++	--	,	->*	->
	()	[]
[Note
:
The last two operators are function call ([expr.call]) and subscripting ([expr.sub]).
The operators new[], delete[], (), and [] are formed from more than one token.
end note
]
Both the unary and binary forms of
+    -    *     &
can be overloaded.
The following operators cannot be overloaded:
.    .*   ::    ?:
nor can the preprocessing symbols # and ## (Clause [cpp]).
Operator functions are usually not called directly; instead they are invoked to evaluate the operators they implement ([over.unary][over.inc]).
They can be explicitly called, however, using the operator-function-id as the name of the function in the function call syntax ([expr.call]).
[Example
:
complex z = a.operator+(b);     // complex z = a+b;
void* p = operator new(sizeof(int)*n);
end example
]
The allocation and deallocation functions, operator new, operator new[], operator delete and operator delete​[], are described completely in [basic.stc.dynamic].
The attributes and restrictions found in the rest of this subclause do not apply to them unless explicitly stated in [basic.stc.dynamic].
An operator function shall either be a non-static member function or be a non-member function that has at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.
It is not possible to change the precedence, grouping, or number of operands of operators.
The meaning of the operators =, (unary) &, and , (comma), predefined for each type, can be changed for specific class and enumeration types by defining operator functions that implement these operators.
Operator functions are inherited in the same manner as other base class functions.
The identities among certain predefined operators applied to basic types (for example, ++a a+=1) need not hold for operator functions.
Some predefined operators, such as +=, require an operand to be an lvalue when applied to basic types; this is not required by operator functions.
An operator function cannot have default arguments ([dcl.fct.default]), except where explicitly stated below.
Operator functions cannot have more or fewer parameters than the number required for the corresponding operator, as described in the rest of this subclause.
Operators not mentioned explicitly in subclauses [over.ass] through [over.inc] act as ordinary unary and binary operators obeying the rules of [over.unary] or [over.binary].

16.5.1 Unary operators [over.unary]

A prefix unary operator shall be implemented by a non-static member function ([class.mfct]) with no parameters or a non-member function with one parameter.
Thus, for any prefix unary operator @, @x can be interpreted as either x.operator@() or operator@(x).
If both forms of the operator function have been declared, the rules in [over.match.oper] determine which, if any, interpretation is used.
See [over.inc] for an explanation of the postfix unary operators ++ and --.
The unary and binary forms of the same operator are considered to have the same name.
[Note
:
Consequently, a unary operator can hide a binary operator from an enclosing scope, and vice versa.
end note
]

16.5.2 Binary operators [over.binary]

A binary operator shall be implemented either by a non-static member function ([class.mfct]) with one parameter or by a non-member function with two parameters.
Thus, for any binary operator @, x@y can be interpreted as either x.operator@(y) or operator@(x,y).
If both forms of the operator function have been declared, the rules in [over.match.oper] determine which, if any, interpretation is used.

16.5.3 Assignment [over.ass]

An assignment operator shall be implemented by a non-static member function with exactly one parameter.
Because a copy assignment operator operator= is implicitly declared for a class if not declared by the user ([class.copy]), a base class assignment operator is always hidden by the copy assignment operator of the derived class.
Any assignment operator, even the copy and move assignment operators, can be virtual.
[Note
:
For a derived class D with a base class B for which a virtual copy/move assignment has been declared, the copy/move assignment operator in D does not override B's virtual copy/move assignment operator.
[Example
:
struct B {
  virtual int operator= (int);
  virtual B& operator= (const B&);
};
struct D : B {
  virtual int operator= (int);
  virtual D& operator= (const B&);
};

D dobj1;
D dobj2;
B* bptr = &dobj1;
void f() {
  bptr->operator=(99);          // calls D​::​operator=(int)
  *bptr = 99;                   // ditto
  bptr->operator=(dobj2);       // calls D​::​operator=(const B&)
  *bptr = dobj2;                // ditto
  dobj1 = dobj2;                // calls implicitly-declared D​::​operator=(const D&)
}
end example
]
end note
]

16.5.4 Function call [over.call]

operator() shall be a non-static member function with an arbitrary number of parameters.
It can have default arguments.
It implements the function call syntax
postfix-expression ( expression-list )
where the postfix-expression evaluates to a class object and the possibly empty expression-list matches the parameter list of an operator() member function of the class.
Thus, a call x(arg1,...) is interpreted as x.operator()(arg1, ...) for a class object x of type T if T​::​operator()(T1, T2, T3) exists and if the operator is selected as the best match function by the overload resolution mechanism ([over.match.best]).

16.5.5 Subscripting [over.sub]

operator[] shall be a non-static member function with exactly one parameter.
It implements the subscripting syntax
postfix-expression [ expr-or-braced-init-list ]
Thus, a subscripting expression x[y] is interpreted as x.operator[](y) for a class object x of type T if T​::​operator[](T1) exists and if the operator is selected as the best match function by the overload resolution mechanism ([over.match.best]).
[Example
:
struct X {
  Z operator[](std::initializer_list<int>);
};
X x;
x[{1,2,3}] = 7;           // OK: meaning x.operator[]({1,2,3})
int a[10];
a[{1,2,3}] = 7;           // error: built-in subscript operator
end example
]

16.5.6 Class member access [over.ref]

operator-> shall be a non-static member function taking no parameters.
It implements the class member access syntax that uses ->.
postfix-expression -> template id-expression
postfix-expression -> pseudo-destructor-name
An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T​::​operator->() exists and if the operator is selected as the best match function by the overload resolution mechanism ([over.match]).

16.5.7 Increment and decrement [over.inc]

The user-defined function called operator++ implements the prefix and postfix ++ operator.
If this function is a non-static member function with no parameters, or a non-member function with one parameter, it defines the prefix increment operator ++ for objects of that type.
If the function is a non-static member function with one parameter (which shall be of type int) or a non-member function with two parameters (the second of which shall be of type int), it defines the postfix increment operator ++ for objects of that type.
When the postfix increment is called as a result of using the ++ operator, the int argument will have value zero.134
[Example
:
struct X {
  X&   operator++();            // prefix ++a
  X    operator++(int);         // postfix a++
};

struct Y { };
Y&   operator++(Y&);            // prefix ++b
Y    operator++(Y&, int);       // postfix b++

void f(X a, Y b) {
  ++a;                          // a.operator++();
  a++;                          // a.operator++(0);
  ++b;                          // operator++(b);
  b++;                          // operator++(b, 0);

  a.operator++();               // explicit call: like ++a;
  a.operator++(0);              // explicit call: like a++;
  operator++(b);                // explicit call: like ++b;
  operator++(b, 0);             // explicit call: like b++;
}
end example
]
The prefix and postfix decrement operators -- are handled analogously.
Calling operator++ explicitly, as in expressions like a.operator++(2), has no special properties: The argument to operator++ is 2.

16.5.8 User-defined literals [over.literal]

The string-literal or user-defined-string-literal in a literal-operator-id shall have no encoding-prefix and shall contain no characters other than the implicit terminating '\0'.
Some literal suffix identifiers are reserved for future standardization; see [usrlit.suffix].
A declaration whose literal-operator-id uses such a literal suffix identifier is ill-formed, no diagnostic required.
A declaration whose declarator-id is a literal-operator-id shall be a declaration of a namespace-scope function or function template (it could be a friend function ([class.friend])), an explicit instantiation or specialization of a function template, or a using-declaration.
A function declared with a literal-operator-id is a literal operator.
A function template declared with a literal-operator-id is a literal operator template.
The declaration of a literal operator shall have a parameter-declaration-clause equivalent to one of the following:
const char*
unsigned long long int
long double
char
wchar_t
char16_t
char32_t
const char*, std::size_t
const wchar_t*, std::size_t
const char16_t*, std::size_t
const char32_t*, std::size_t
If a parameter has a default argument ([dcl.fct.default]), the program is ill-formed.
A raw literal operator is a literal operator with a single parameter whose type is const char*.
The declaration of a literal operator template shall have an empty parameter-declaration-clause and its template-parameter-list shall have a single template-parameter that is a non-type template parameter pack ([temp.variadic]) with element type char.
Literal operators and literal operator templates shall not have C language linkage.
[Note
:
Literal operators and literal operator templates are usually invoked implicitly through user-defined literals ([lex.ext]).
However, except for the constraints described above, they are ordinary namespace-scope functions and function templates.
In particular, they are looked up like ordinary functions and function templates and they follow the same overload resolution rules.
Also, they can be declared inline or constexpr, they may have internal or external linkage, they can be called explicitly, their addresses can be taken, etc.
end note
]
[Example
:
void operator "" _km(long double);                  // OK
string operator "" _i18n(const char*, std::size_t); // OK
template <char...> double operator "" _\u03C0();    // OK: UCN for lowercase pi
float operator ""_e(const char*);                   // OK
float operator ""E(const char*);                    // error: reserved literal suffix ([usrlit.suffix], [lex.ext])
double operator""_Bq(long double);                  // OK: does not use the reserved identifier _­Bq ([lex.name])
double operator"" _Bq(long double);                 // uses the reserved identifier _­Bq ([lex.name])
float operator " " B(const char*);                  // error: non-empty string-literal
string operator "" 5X(const char*, std::size_t);    // error: invalid literal suffix identifier
double operator "" _miles(double);                  // error: invalid parameter-declaration-clause
template <char...> int operator "" _j(const char*); // error: invalid parameter-declaration-clause
extern "C" void operator "" _m(long double);        // error: C language linkage
end example
]

16.6 Built-in operators [over.built]

The candidate operator functions that represent the built-in operators defined in Clause [expr] are specified in this subclause.
These candidate functions participate in the operator overload resolution process as described in [over.match.oper] and are used for no other purpose.
[Note
:
Because built-in operators take only operands with non-class type, and operator overload resolution occurs only when an operand expression originally has class or enumeration type, operator overload resolution can resolve to a built-in operator only when an operand has a class type that has a user-defined conversion to a non-class type appropriate for the operator, or when an operand has an enumeration type that can be converted to a type appropriate for the operator.
Also note that some of the candidate operator functions given in this subclause are more permissive than the built-in operators themselves.
As described in [over.match.oper], after a built-in operator is selected by overload resolution the expression is subject to the requirements for the built-in operator given in Clause [expr], and therefore to any additional semantic constraints given there.
If there is a user-written candidate with the same name and parameter types as a built-in candidate operator function, the built-in operator function is hidden and is not included in the set of candidate functions.
end note
]
In this subclause, the term promoted integral type is used to refer to those integral types which are preserved by integral promotion ([conv.prom]) (including e.g. int and long but excluding e.g. char).
Similarly, the term promoted arithmetic type refers to floating types plus promoted integral types.
[Note
:
In all cases where a promoted integral type or promoted arithmetic type is required, an operand of enumeration type will be acceptable by way of the integral promotions.
end note
]
In the remainder of this section, vq represents either volatile or no cv-qualifier.
For every pair (T, vq), where T is an arithmetic type other than bool, there exist candidate operator functions of the form
vq T& operator++(vq T&);
T operator++(vq T&, int);
For every pair (T, vq), where T is an arithmetic type other than bool, there exist candidate operator functions of the form
vq T& operator--(vq T&);
T operator--(vq T&, int);
For every pair (T, vq), where T is a cv-qualified or cv-unqualified object type, there exist candidate operator functions of the form
T*vq& operator++(T*vq&);
T*vq& operator--(T*vq&);
T*    operator++(T*vq&, int);
T*    operator--(T*vq&, int);
For every cv-qualified or cv-unqualified object type T, there exist candidate operator functions of the form
T&    operator*(T*);
For every function type T that does not have cv-qualifiers or a ref-qualifier, there exist candidate operator functions of the form
T&    operator*(T*);
For every type T there exist candidate operator functions of the form
T*    operator+(T*);
For every promoted arithmetic type T, there exist candidate operator functions of the form
T operator+(T);
T operator-(T);
For every promoted integral type T, there exist candidate operator functions of the form
T operator~(T);
For every quintuple (C1, C2, T, cv1, cv2), where C2 is a class type, C1 is the same type as C2 or is a derived class of C2, and T is an object type or a function type, there exist candidate operator functions of the form
cv12 T& operator->*(cv1 C1*, cv2 T C2::*);
where cv12 is the union of cv1 and cv2.
The return type is shown for exposition only; see [expr.mptr.oper] for the determination of the operator's result type.
For every pair of promoted arithmetic types L and R, there exist candidate operator functions of the form
LR      operator*(L, R);
LR      operator/(L, R);
LR      operator+(L, R);
LR      operator-(L, R);
bool    operator<(L, R);
bool    operator>(L, R);
bool    operator<=(L, R);
bool    operator>=(L, R);
bool    operator==(L, R);
bool    operator!=(L, R);
where LR is the result of the usual arithmetic conversions between types L and R.
For every cv-qualified or cv-unqualified object type T there exist candidate operator functions of the form
T*      operator+(T*, std::ptrdiff_t);
T&      operator[](T*, std::ptrdiff_t);
T*      operator-(T*, std::ptrdiff_t);
T*      operator+(std::ptrdiff_t, T*);
T&      operator[](std::ptrdiff_t, T*);
For every T, where T is a pointer to object type, there exist candidate operator functions of the form
std::ptrdiff_t   operator-(T, T);
For every T, where T is an enumeration type or a pointer type, there exist candidate operator functions of the form
bool    operator<(T, T);
bool    operator>(T, T);
bool    operator<=(T, T);
bool    operator>=(T, T);
bool    operator==(T, T);
bool    operator!=(T, T);
For every pointer to member type T or type std​::​nullptr_­t there exist candidate operator functions of the form
bool    operator==(T, T);
bool    operator!=(T, T);
For every pair of promoted integral types L and R, there exist candidate operator functions of the form
LR      operator%(L, R);
LR      operator&(L, R);
LR      operator^(L, R);
LR      operator|(L, R);
L       operator<<(L, R);
L       operator>>(L, R);
where LR is the result of the usual arithmetic conversions between types L and R.
For every triple (L, vq, R), where L is an arithmetic type, and R is a promoted arithmetic type, there exist candidate operator functions of the form
vq L&   operator=(vq L&, R);
vq L&   operator*=(vq L&, R);
vq L&   operator/=(vq L&, R);
vq L&   operator+=(vq L&, R);
vq L&   operator-=(vq L&, R);
For every pair (T, vq), where T is any type, there exist candidate operator functions of the form
T*vq&   operator=(T*vq&, T*);
For every pair (T, vq), where T is an enumeration or pointer to member type, there exist candidate operator functions of the form
vq T&   operator=(vq T&, T);
For every pair (T, vq), where T is a cv-qualified or cv-unqualified object type, there exist candidate operator functions of the form
T*vq&   operator+=(T*vq&, std::ptrdiff_t);
T*vq&   operator-=(T*vq&, std::ptrdiff_t);
For every triple (L, vq, R), where L is an integral type, and R is a promoted integral type, there exist candidate operator functions of the form
vq L&   operator%=(vq L&, R);
vq L&   operator<<=(vq L&, R);
vq L&   operator>>=(vq L&, R);
vq L&   operator&=(vq L&, R);
vq L&   operator^=(vq L&, R);
vq L&   operator|=(vq L&, R);
There also exist candidate operator functions of the form
bool    operator!(bool);
bool    operator&&(bool, bool);
bool    operator||(bool, bool);
For every pair of promoted arithmetic types L and R, there exist candidate operator functions of the form
LR      operator?:(bool, L, R);
where LR is the result of the usual arithmetic conversions between types L and R.
[Note
:
As with all these descriptions of candidate functions, this declaration serves only to describe the built-in operator for purposes of overload resolution.
The operator “?:” cannot be overloaded.
end note
]
For every type T, where T is a pointer, pointer-to-member, or scoped enumeration type, there exist candidate operator functions of the form
T       operator?:(bool, T, T);

17 Templates [temp]

A template defines a family of classes, functions, or variables, or an alias for a family of types.
template-declaration:
	template < template-parameter-list > declaration
template-parameter-list:
	template-parameter
	template-parameter-list , template-parameter
[Note
:
The > token following the template-parameter-list of a template-declaration may be the product of replacing a >> token by two consecutive > tokens ([temp.names]).
end note
]
The declaration in a template-declaration shall
  • declare or define a function, a class, or a variable, or
  • define a member function, a member class, a member enumeration, or a static data member of a class template or of a class nested within a class template, or
  • define a member template of a class or class template, or
A template-declaration is also a definition if its declaration defines a function, a class, a variable, or a static data member.
A declaration introduced by a template declaration of a variable is a variable template.
A variable template at class scope is a static data member template.
[Example
:
template<class T>
  constexpr T pi = T(3.1415926535897932385L);
template<class T>
T circular_area(T r) {
  return pi<T> * r * r;
}
struct matrix_constants {
  template<class T>
   using pauli = hermitian_matrix<T, 2>;
  template<class T>
   constexpr pauli<T> sigma1 = { { 0, 1 }, { 1, 0 } };
  template<class T>
   constexpr pauli<T> sigma2 = { { 0, -1i }, { 1i, 0 } };
  template<class T>
   constexpr pauli<T> sigma3 = { { 1, 0 }, { 0, -1 } };
};
end example
]
A template-declaration can appear only as a namespace scope or class scope declaration.
In a function template declaration, the last component of the declarator-id shall not be a template-id.
[Note
:
That last component may be an identifier, an operator-function-id, a conversion-function-id, or a literal-operator-id.
In a class template declaration, if the class name is a simple-template-id, the declaration declares a class template partial specialization ([temp.class.spec]).
end note
]
In a template-declaration, explicit specialization, or explicit instantiation the init-declarator-list in the declaration shall contain at most one declarator.
When such a declaration is used to declare a class template, no declarator is permitted.
A template name has linkage ([basic.link]).
Specializations (explicit or implicit) of a template that has internal linkage are distinct from all specializations in other translation units.
A template, a template explicit specialization ([temp.expl.spec]), and a class template partial specialization shall not have C linkage.
Use of a linkage specification other than "C" or "C++" with any of these constructs is conditionally-supported, with implementation-defined semantics.
Template definitions shall obey the one-definition rule ([basic.def.odr]).
[Note
:
Default arguments for function templates and for member functions of class templates are considered definitions for the purpose of template instantiation ([temp.decls]) and must also obey the one-definition rule.
end note
]
A class template shall not have the same name as any other template, class, function, variable, enumeration, enumerator, namespace, or type in the same scope ([basic.scope]), except as specified in [temp.class.spec].
Except that a function template can be overloaded either by non-template functions ([dcl.fct]) with the same name or by other function templates with the same name ([temp.over]), a template name declared in namespace scope or in class scope shall be unique in that scope.
[Note
:
A local class, a local variable, or a friend function defined in a templated entity is a templated entity.
end note
]
A function template, member function of a class template, variable template, or static data member of a class template shall be defined in every translation unit in which it is implicitly instantiated ([temp.inst]) unless the corresponding specialization is explicitly instantiated ([temp.explicit]) in some translation unit; no diagnostic is required.

17.1 Template parameters [temp.param]

The syntax for template-parameters is:
template-parameter:
	type-parameter
	parameter-declaration
type-parameter:
	type-parameter-key ... identifier
	type-parameter-key identifier = type-id
	template < template-parameter-list > type-parameter-key ... identifier
	template < template-parameter-list > type-parameter-key identifier = id-expression
type-parameter-key:
	class
	typename
[Note
:
The > token following the template-parameter-list of a type-parameter may be the product of replacing a >> token by two consecutive > tokens ([temp.names]).
end note
]
There is no semantic difference between class and typename in a type-parameter-key.
typename followed by an unqualified-id names a template type parameter.
typename followed by a qualified-id denotes the type in a non-type135 parameter-declaration.
[Example
:
class T { /* ... */ };
int i;

template<class T, T i> void f(T t) {
  T t1 = i;         // template-parameters T and i
  ::T t2 = ::i;     // global namespace members T and i
}
Here, the template f has a type-parameter called T, rather than an unnamed non-type template-parameter of class T.
end example
]
A storage class shall not be specified in a template-parameter declaration.
Types shall not be defined in a template-parameter declaration.
A type-parameter whose identifier does not follow an ellipsis defines its identifier to be a typedef-name (if declared without template) or template-name (if declared with template) in the scope of the template declaration.
[Note
:
A template argument may be a class template or alias template.
For example,
template<class T> class myarray { /* ... */ };

template<class K, class V, template<class T> class C = myarray>
class Map {
  C<K> key;
  C<V> value;
};
end note
]
A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
  • integral or enumeration type,
  • pointer to object or pointer to function,
  • lvalue reference to object or lvalue reference to function,
  • pointer to member,
  • std​::​nullptr_­t, or
  • a type that contains a placeholder type ([dcl.spec.auto]).
[Note
:
Other types are disallowed either explicitly below or implicitly by the rules governing the form of template-arguments ([temp.arg]).
end note
]
The top-level cv-qualifiers on the template-parameter are ignored when determining its type.
A non-type non-reference template-parameter is a prvalue.
It shall not be assigned to or in any other way have its value changed.
A non-type non-reference template-parameter cannot have its address taken.
When a non-type non-reference template-parameter is used as an initializer for a reference, a temporary is always used.
[Example
:
template<const X& x, int i> void f() {
  i++;                          // error: change of template-parameter value

  &x;                           // OK
  &i;                           // error: address of non-reference template-parameter

  int& ri = i;                  // error: non-const reference bound to temporary
  const int& cri = i;           // OK: const reference bound to temporary
}
end example
]
A non-type template-parameter shall not be declared to have floating-point, class, or void type.
[Example
:
template<double d> class X;     // error
template<double* pd> class Y;   // OK
template<double& rd> class Z;   // OK
end example
]
A non-type template-parameter of type “array of T” or of function type T is adjusted to be of type “pointer to T.
[Example
:
template<int* a>   struct R { /* ... */ };
template<int b[5]> struct S { /* ... */ };
int p;
R<&p> w;                        // OK
S<&p> x;                        // OK due to parameter adjustment
int v[5];
R<v> y;                         // OK due to implicit argument conversion
S<v> z;                         // OK due to both adjustment and conversion
end example
]
A default template-argument may be specified for any kind of template-parameter (type, non-type, template) that is not a template parameter pack ([temp.variadic]).
A default template-argument may be specified in a template declaration.
A default template-argument shall not be specified in the template-parameter-lists of the definition of a member of a class template that appears outside of the member's class.
A default template-argument shall not be specified in a friend class template declaration.
If a friend function template declaration specifies a default template-argument, that declaration shall be a definition and shall be the only declaration of the function template in the translation unit.
The set of default template-arguments available for use is obtained by merging the default arguments from all prior declarations of the template in the same way default function arguments are ([dcl.fct.default]).
[Example
:
template<class T1, class T2 = int> class A;
template<class T1 = int, class T2> class A;
is equivalent to
template<class T1 = int, class T2 = int> class A;
end example
]
If a template-parameter of a class template, variable template, or alias template has a default template-argument, each subsequent template-parameter shall either have a default template-argument supplied or be a template parameter pack.
If a template-parameter of a primary class template, primary variable template, or alias template is a template parameter pack, it shall be the last template-parameter.
A template parameter pack of a function template shall not be followed by another template parameter unless that template parameter can be deduced from the parameter-type-list ([dcl.fct]) of the function template or has a default argument ([temp.deduct]).
A template parameter of a deduction guide template ([temp.deduct.guide]) that does not have a default argument shall be deducible from the parameter-type-list of the deduction guide template.
[Example
:
template<class T1 = int, class T2> class B;     // error

// U can be neither deduced from the parameter-type-list nor specified
template<class... T, class... U> void f() { }   // error
template<class... T, class U> void g() { }      // error
end example
]
A template-parameter shall not be given default arguments by two different declarations in the same scope.
[Example
:
template<class T = int> class X;
template<class T = int> class X { /* ... */ };  // error
end example
]
When parsing a default template-argument for a non-type template-parameter, the first non-nested > is taken as the end of the template-parameter-list rather than a greater-than operator.
[Example
:
template<int i = 3 > 4 >        // syntax error
class X { /* ... */ };

template<int i = (3 > 4) >      // OK
class Y { /* ... */ };
end example
]
A template-parameter of a template template-parameter is permitted to have a default template-argument.
When such default arguments are specified, they apply to the template template-parameter in the scope of the template template-parameter.
[Example
:
template <class T = float> struct B {};
template <template <class TT = float> class T> struct A {
  inline void f();
  inline void g();
};
template <template <class TT> class T> void A<T>::f() {
  T<> t;            // error - TT has no default template argument
}
template <template <class TT = char> class T> void A<T>::g() {
    T<> t;          // OK - T<char>
}
end example
]
If a template-parameter is a type-parameter with an ellipsis prior to its optional identifier or is a parameter-declaration that declares a parameter pack ([dcl.fct]), then the template-parameter is a template parameter pack ([temp.variadic]).
A template parameter pack that is a parameter-declaration whose type contains one or more unexpanded parameter packs is a pack expansion.
Similarly, a template parameter pack that is a type-parameter with a template-parameter-list containing one or more unexpanded parameter packs is a pack expansion.
A template parameter pack that is a pack expansion shall not expand a parameter pack declared in the same template-parameter-list.
[Example
:
template <class... Types> class Tuple;                // Types is a template type parameter pack
                                                      // but not a pack expansion
template <class T, int... Dims> struct multi_array;   // Dims is a non-type template parameter pack
                                                      // but not a pack expansion
template<class... T> struct value_holder {
  template<T... Values> struct apply { };             // Values is a non-type template parameter pack
                                                      // and a pack expansion
};
template<class... T, T... Values> struct static_array;// error: Values expands template type parameter
                                                      // pack T within the same template parameter list
end example
]
Since template template-parameters and template template-arguments are treated as types for descriptive purposes, the terms non-type parameter and non-type argument are used to refer to non-type, non-template parameters and arguments.

17.2 Names of template specializations [temp.names]

A template specialization ([temp.spec]) can be referred to by a template-id:
For a template-name to be explicitly qualified by the template arguments, the name must be known to refer to a template.
After name lookup ([basic.lookup]) finds that a name is a template-name or that an operator-function-id or a literal-operator-id refers to a set of overloaded functions any member of which is a function template, if this is followed by a <, the < is always taken as the delimiter of a template-argument-list and never as the less-than operator.
When parsing a template-argument-list, the first non-nested >136 is taken as the ending delimiter rather than a greater-than operator.
Similarly, the first non-nested >> is treated as two consecutive but distinct > tokens, the first of which is taken as the end of the template-argument-list and completes the template-id.
[Note
:
The second > token produced by this replacement rule may terminate an enclosing template-id construct or it may be part of a different construct (e.g. a cast).
end note
]
[Example
:
template<int i> class X { /* ... */ };

X< 1>2 > x1;                            // syntax error
X<(1>2)> x2;                            // OK

template<class T> class Y { /* ... */ };
Y<X<1>> x3;                             // OK, same as Y<X<1> > x3;
Y<X<6>>1>> x4;                          // syntax error
Y<X<(6>>1)>> x5;                        // OK
end example
]
The keyword template is said to appear at the top level in a qualified-id if it appears outside of a template-argument-list or decltype-specifier.
In a qualified-id of a declarator-id or in a qualified-id formed by a class-head-name or enum-head-name, the keyword template shall not appear at the top level.
In a qualified-id used as the name in a typename-specifier, elaborated-type-specifier, using-declaration, or class-or-decltype, an optional keyword template appearing at the top level is ignored.
In these contexts, a < token is always assumed to introduce a template-argument-list.
In all other contexts, when naming a template specialization of a member of an unknown specialization ([temp.dep.type]), the member template name shall be prefixed by the keyword template.
[Example
:
struct X {
  template<std::size_t> X* alloc();
  template<std::size_t> static X* adjust();
};
template<class T> void f(T* p) {
  T* p1 = p->alloc<200>();              // ill-formed: < means less than
  T* p2 = p->template alloc<200>();     // OK: < starts template argument list
  T::adjust<100>();                     // ill-formed: < means less than
  T::template adjust<100>();            // OK: < starts template argument list
}
end example
]
A name prefixed by the keyword template shall be a template-id or the name shall refer to a class template or an alias template.
[Note
:
The keyword template may not be applied to non-template members of class templates.
end note
]
[Note
:
As is the case with the typename prefix, the template prefix is allowed in cases where it is not strictly necessary; i.e., when the nested-name-specifier or the expression on the left of the -> or . is not dependent on a template-parameter, or the use does not appear in the scope of a template.
end note
]
[Example
:
template <class T> struct A {
  void f(int);
  template <class U> void f(U);
};

template <class T> void f(T t) {
  A<T> a;
  a.template f<>(t);                    // OK: calls template
  a.template f(t);                      // error: not a template-id
}

template <class T> struct B {
  template <class T2> struct C { };
};

// OK: T​::​template C names a class template:
template <class T, template <class X> class TT = T::template C> struct D { };
D<B<int> > db;
end example
]
A simple-template-id that names a class template specialization is a class-name.
A template-id that names an alias template specialization is a type-name.
A > that encloses the type-id of a dynamic_­cast, static_­cast, reinterpret_­cast or const_­cast, or which encloses the template-arguments of a subsequent template-id, is considered nested for the purpose of this description.

17.3 Template arguments [temp.arg]

There are three forms of template-argument, corresponding to the three forms of template-parameter: type, non-type and template.
The type and form of each template-argument specified in a template-id shall match the type and form specified for the corresponding parameter declared by the template in its template-parameter-list.
When the parameter declared by the template is a template parameter pack ([temp.variadic]), it will correspond to zero or more template-arguments.
[Example
:
template<class T> class Array {
  T* v;
  int sz;
public:
  explicit Array(int);
  T& operator[](int);
  T& elem(int i) { return v[i]; }
};

Array<int> v1(20);
typedef std::complex<double> dcomplex;  // std​::​complex is a standard library template
Array<dcomplex> v2(30);
Array<dcomplex> v3(40);

void bar() {
  v1[3] = 7;
  v2[3] = v3.elem(4) = dcomplex(7,8);
}
end example
]
In a template-argument, an ambiguity between a type-id and an expression is resolved to a type-id, regardless of the form of the corresponding template-parameter.137
[Example
:
template<class T> void f();
template<int I> void f();

void g() {
  f<int()>();       // int() is a type-id: call the first f()
}
end example
]
The name of a template-argument shall be accessible at the point where it is used as a template-argument.
[Note
:
If the name of the template-argument is accessible at the point where it is used as a template-argument, there is no further access restriction in the resulting instantiation where the corresponding template-parameter name is used.
end note
]
[Example
:
template<class T> class X {
  static T t;
};

class Y {
private:
  struct S { /* ... */ };
  X<S> x;           // OK: S is accessible
                    // X<Y​::​S> has a static member of type Y​::​S
                    // OK: even though Y​::​S is private
};

X<Y::S> y;          // error: S not accessible
end example
]
For a template-argument that is a class type or a class template, the template definition has no special access rights to the members of the template-argument.
[Example
:
template <template <class TT> class T> class A {
  typename T<int>::S s;
};

template <class U> class B {
private:
  struct S { /* ... */ };
};

A<B> b;             // ill-formed: A has no access to B​::​S
end example
]
When template argument packs or default template-arguments are used, a template-argument list can be empty.
In that case the empty <> brackets shall still be used as the template-argument-list.
[Example
:
template<class T = char> class String;
String<>* p;                    // OK: String<char>
String* q;                      // syntax error
template<class ... Elements> class Tuple;
Tuple<>* t;                     // OK: Elements is empty
Tuple* u;                       // syntax error
end example
]
An explicit destructor call ([class.dtor]) for an object that has a type that is a class template specialization may explicitly specify the template-arguments.
[Example
:
template<class T> struct A {
  ~A();
};
void f(A<int>* p, A<int>* q) {
  p->A<int>::~A();              // OK: destructor call
  q->A<int>::~A<int>();         // OK: destructor call
}
end example
]
If the use of a template-argument gives rise to an ill-formed construct in the instantiation of a template specialization, the program is ill-formed.
When the template in a template-id is an overloaded function template, both non-template functions in the overload set and function templates in the overload set for which the template-arguments do not match the template-parameters are ignored.
If none of the function templates have matching template-parameters, the program is ill-formed.
When a simple-template-id does not name a function, a default template-argument is implicitly instantiated ([temp.inst]) when the value of that default argument is needed.
[Example
:
template<typename T, typename U = int> struct S { };
S<bool>* p;         // the type of p is S<bool, int>*
The default argument for U is instantiated to form the type S<bool, int>*.
end example
]
A template-argument followed by an ellipsis is a pack expansion ([temp.variadic]).
There is no such ambiguity in a default template-argument because the form of the template-parameter determines the allowable forms of the template-argument.

17.3.1 Template type arguments [temp.arg.type]

A template-argument for a template-parameter which is a type shall be a type-id.
[Example
:
template <class T> class X { };
template <class T> void f(T t) { }
struct { } unnamed_obj;

void f() {
  struct A { };
  enum { e1 };
  typedef struct { } B;
  B b;
  X<A> x1;          // OK
  X<A*> x2;         // OK
  X<B> x3;          // OK
  f(e1);            // OK
  f(unnamed_obj);   // OK
  f(b);             // OK
}
end example
]
[Note
:
A template type argument may be an incomplete type ([basic.types]).
end note
]

17.3.2 Template non-type arguments [temp.arg.nontype]

If the type of a template-parameter contains a placeholder type ([dcl.spec.auto], [temp.param]), the deduced parameter type is determined from the type of the template-argument by placeholder type deduction ([dcl.type.auto.deduct]).
If a deduced parameter type is not permitted for a template-parameter declaration ([temp.param]), the program is ill-formed.
A template-argument for a non-type template-parameter shall be a converted constant expression ([expr.const]) of the type of the template-parameter.
For a non-type template-parameter of reference or pointer type, the value of the constant expression shall not refer to (or for a pointer type, shall not be the address of):
[Note
:
If the template-argument represents a set of overloaded functions (or a pointer or member pointer to such), the matching function is selected from the set ([over.over]).
end note
]
[Example
:
template<const int* pci> struct X { /* ... */ };
int ai[10];
X<ai> xi;                       // array to pointer and qualification conversions

struct Y { /* ... */ };
template<const Y& b> struct Z { /* ... */ };
Y y;
Z<y> z;                         // no conversion, but note extra cv-qualification

template<int (&pa)[5]> struct W { /* ... */ };
int b[5];
W<b> w;                         // no conversion

void f(char);
void f(int);

template<void (*pf)(int)> struct A { /* ... */ };

A<&f> a;                        // selects f(int)

template<auto n> struct B { /* ... */ };
B<5> b1;                        // OK: template parameter type is int
B<'a'> b2;                      // OK: template parameter type is char
B<2.5> b3;                      // error: template parameter type cannot be double
end example
]
[Note
:
A string literal ([lex.string]) is not an acceptable template-argument.
[Example
:
template<class T, const char* p> class X {
  /* ... */
};

X<int, "Studebaker"> x1;        // error: string literal as template-argument

const char p[] = "Vivisectionist";
X<int,p> x2;                    // OK
end example
]
end note
]
[Note
:
The address of an array element or non-static data member is not an acceptable template-argument.
[Example
:
template<int* p> class X { };

int a[10];
struct S { int m; static int s; } s;

X<&a[2]> x3;                    // error: address of array element
X<&s.m> x4;                     // error: address of non-static member
X<&s.s> x5;                     // OK: address of static member
X<&S::s> x6;                    // OK: address of static member
end example
]
end note
]
[Note
:
A temporary object is not an acceptable template-argument when the corresponding template-parameter has reference type.
[Example
:
template<const int& CRI> struct B { /* ... */ };

B<1> b2;                        // error: temporary would be required for template argument

int c = 1;
B<c> b1;                        // OK
end example
]
end note
]

17.3.3 Template template arguments [temp.arg.template]

A template-argument for a template template-parameter shall be the name of a class template or an alias template, expressed as id-expression.
When the template-argument names a class template, only primary class templates are considered when matching the template template argument with the corresponding parameter; partial specializations are not considered even if their parameter lists match that of the template template parameter.
Any partial specializations ([temp.class.spec]) associated with the primary class template or primary variable template are considered when a specialization based on the template template-parameter is instantiated.
If a specialization is not visible at the point of instantiation, and it would have been selected had it been visible, the program is ill-formed, no diagnostic required.
[Example
:
template<class T> class A {     // primary template
  int x;
};
template<class T> class A<T*> { // partial specialization
  long x;
};
template<template<class U> class V> class C {
  V<int>  y;
  V<int*> z;
};
C<A> c;             // V<int> within C<A> uses the primary template, so c.y.x has type int
                    // V<int*> within C<A> uses the partial specialization, so c.z.x has type long
end example
]
A template-argument matches a template template-parameter P when P is at least as specialized as the template-argument A.
If P contains a parameter pack, then A also matches P if each of A's template parameters matches the corresponding template parameter in the template-parameter-list of P.
Two template parameters match if they are of the same kind (type, non-type, template), for non-type template-parameters, their types are equivalent ([temp.over.link]), and for template template-parameters, each of their corresponding template-parameters matches, recursively.
When P's template-parameter-list contains a template parameter pack ([temp.variadic]), the template parameter pack will match zero or more template parameters or template parameter packs in the template-parameter-list of A with the same type and form as the template parameter pack in P (ignoring whether those template parameters are template parameter packs).
[Example
:
template<class T> class A { /* ... */ };
template<class T, class U = T> class B { /* ... */ };
template<class ... Types> class C { /* ... */ };
template<auto n> class D { /* ... */ };
template<template<class> class P> class X { /* ... */ };
template<template<class ...> class Q> class Y { /* ... */ };
template<template<int> class R> class Z { /* ... */ };

X<A> xa;            // OK
X<B> xb;            // OK
X<C> xc;            // OK
Y<A> ya;            // OK
Y<B> yb;            // OK
Y<C> yc;            // OK
Z<D> zd;            // OK
end example
]
[Example
:
template <class T> struct eval;

template <template <class, class...> class TT, class T1, class... Rest>
struct eval<TT<T1, Rest...>> { };

template <class T1> struct A;
template <class T1, class T2> struct B;
template <int N> struct C;
template <class T1, int N> struct D;
template <class T1, class T2, int N = 17> struct E;

eval<A<int>> eA;                // OK: matches partial specialization of eval
eval<B<int, float>> eB;         // OK: matches partial specialization of eval
eval<C<17>> eC;                 // error: C does not match TT in partial specialization
eval<D<int, 17>> eD;            // error: D does not match TT in partial specialization
eval<E<int, float>> eE;         // error: E does not match TT in partial specialization
end example
]
A template template-parameter P is at least as specialized as a template template-argument A if, given the following rewrite to two function templates, the function template corresponding to P is at least as specialized as the function template corresponding to A according to the partial ordering rules for function templates ([temp.func.order]).
Given an invented class template X with the template parameter list of A (including default arguments):
  • Each of the two function templates has the same template parameters, respectively, as P or A.
  • Each function template has a single function parameter whose type is a specialization of X with template arguments corresponding to the template parameters from the respective function template where, for each template parameter PP in the template parameter list of the function template, a corresponding template argument AA is formed.
    If PP declares a parameter pack, then AA is the pack expansion PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
If the rewrite produces an invalid type, then P is not at least as specialized as A.

17.4 Type equivalence [temp.type]

Two template-ids refer to the same class, function, or variable if
[Example
:
template<class E, int size> class buffer { /* ... */ };
buffer<char,2*512> x;
buffer<char,1024> y;
declares x and y to be of the same type, and
template<class T, void(*err_fct)()> class list { /* ... */ };
list<int,&error_handler1> x1;
list<int,&error_handler2> x2;
list<int,&error_handler2> x3;
list<char,&error_handler2> x4;
declares x2 and x3 to be of the same type.
Their type differs from the types of x1 and x4.
template<class T> struct X { };
template<class> struct Y { };
template<class T> using Z = Y<T>;
X<Y<int> > y;
X<Z<int> > z;
declares y and z to be of the same type.
end example
]
If an expression e is type-dependent ([temp.dep.expr]), decltype(e) denotes a unique dependent type.
Two such decltype-specifiers refer to the same type only if their expressions are equivalent ([temp.over.link]).
[Note
:
However, such a type may be aliased, e.g., by a typedef-name.
end note
]

17.5 Template declarations [temp.decls]

A template-id, that is, the template-name followed by a template-argument-list shall not be specified in the declaration of a primary template declaration.
[Example
:
template<class T1, class T2, int I> class A<T1, T2, I> { };     // error
template<class T1, int I> void sort<T1, I>(T1 data[I]);         // error
end example
]
[Note
:
However, this syntax is allowed in class template partial specializations ([temp.class.spec]).
end note
]
For purposes of name lookup and instantiation, default arguments and noexcept-specifiers of function templates and default arguments and noexcept-specifiers of member functions of class templates are considered definitions; each default argument or noexcept-specifier is a separate definition which is unrelated to the function template definition or to any other default arguments or noexcept-specifiers.
For the purpose of instantiation, the substatements of a constexpr if statement ([stmt.if]) are considered definitions.
Because an alias-declaration cannot declare a template-id, it is not possible to partially or explicitly specialize an alias template.

17.5.1 Class templates [temp.class]

A class template defines the layout and operations for an unbounded set of related types.
[Example
:
A single class template List might provide an unbounded set of class definitions: one class List<T> for every type T, each describing a linked list of elements of type T.
Similarly, a class template Array describing a contiguous, dynamic array might be defined like this:
template<class T> class Array {
  T* v;
  int sz;
public:
  explicit Array(int);
  T& operator[](int);
  T& elem(int i) { return v[i]; }
};
The prefix template<class T> specifies that a template is being declared and that a type-name T may be used in the declaration.
In other words, Array is a parameterized type with T as its parameter.
end example
]
When a member function, a member class, a member enumeration, a static data member or a member template of a class template is defined outside of the class template definition, the member definition is defined as a template definition in which the template-parameters are those of the class template.
The names of the template parameters used in the definition of the member may be different from the template parameter names used in the class template definition.
The template argument list following the class template name in the member definition shall name the parameters in the same order as the one used in the template parameter list of the member.
Each template parameter pack shall be expanded with an ellipsis in the template argument list.
[Example
:
template<class T1, class T2> struct A {
  void f1();
  void f2();
};

template<class T2, class T1> void A<T2,T1>::f1() { }    // OK
template<class T2, class T1> void A<T1,T2>::f2() { }    // error
template<class ... Types> struct B {
  void f3();
  void f4();
};

template<class ... Types> void B<Types ...>::f3() { }    // OK
template<class ... Types> void B<Types>::f4() { }        // error
end example
]
In a redeclaration, partial specialization, explicit specialization or explicit instantiation of a class template, the class-key shall agree in kind with the original class template declaration ([dcl.type.elab]).

17.5.1.1 Member functions of class templates [temp.mem.func]

A member function of a class template may be defined outside of the class template definition in which it is declared.
[Example
:
template<class T> class Array {
  T* v;
  int sz;
public:
  explicit Array(int);
  T& operator[](int);
  T& elem(int i) { return v[i]; }
};
declares three function templates.
The subscript function might be defined like this:
template<class T> T& Array<T>::operator[](int i) {
  if (i<0 || sz<=i) error("Array: range error");
  return v[i];
}
end example
]
The template-arguments for a member function of a class template are determined by the template-arguments of the type of the object for which the member function is called.
[Example
:
The template-argument for Array<T>​::​operator[]() will be determined by the Array to which the subscripting operation is applied.
Array<int> v1(20);
Array<dcomplex> v2(30);

v1[3] = 7;                      // Array<int>​::​operator[]()
v2[3] = dcomplex(7,8);          // Array<dcomplex>​::​operator[]()
end example
]

17.5.1.2 Member classes of class templates [temp.mem.class]

A member class of a class template may be defined outside the class template definition in which it is declared.
[Note
:
The member class must be defined before its first use that requires an instantiation ([temp.inst]).
For example,
template<class T> struct A {
  class B;
};
A<int>::B* b1;                  // OK: requires A to be defined but not A​::​B
template<class T> class A<T>::B { };
A<int>::B  b2;                  // OK: requires A​::​B to be defined
end note
]

17.5.1.3 Static data members of class templates [temp.static]

A definition for a static data member or static data member template may be provided in a namespace scope enclosing the definition of the static member's class template.
[Example
:
template<class T> class X {
  static T s;
};
template<class T> T X<T>::s = 0;

struct limits {
  template<class T>
    static const T min;         // declaration
};

template<class T>
  const T limits::min = { };    // definition
end example
]
An explicit specialization of a static data member declared as an array of unknown bound can have a different bound from its definition, if any.
[Example
:
template <class T> struct A {
  static int i[];
};
template <class T> int A<T>::i[4];              // 4 elements
template <> int A<int>::i[] = { 1 };            // OK: 1 element
end example
]

17.5.1.4 Enumeration members of class templates [temp.mem.enum]

An enumeration member of a class template may be defined outside the class template definition.
[Example
:
template<class T> struct A {
  enum E : T;
};
A<int> a;
template<class T> enum A<T>::E : T { e1, e2 };
A<int>::E e = A<int>::e1;
end example
]

17.5.2 Member templates [temp.mem]

A template can be declared within a class or class template; such a template is called a member template.
A member template can be defined within or outside its class definition or class template definition.
A member template of a class template that is defined outside of its class template definition shall be specified with the template-parameters of the class template followed by the template-parameters of the member template.
[Example
:
template<class T> struct string {
  template<class T2> int compare(const T2&);
  template<class T2> string(const string<T2>& s) { /* ... */ }
};

template<class T> template<class T2> int string<T>::compare(const T2& s) {
}
end example
]
A local class of non-closure type shall not have member templates.
Access control rules (Clause [class.access]) apply to member template names.
A destructor shall not be a member template.
A non-template member function ([dcl.fct]) with a given name and type and a member function template of the same name, which could be used to generate a specialization of the same type, can both be declared in a class.
When both exist, a use of that name and type refers to the non-template member unless an explicit template argument list is supplied.
[Example
:
template <class T> struct A {
  void f(int);
  template <class T2> void f(T2);
};

template <> void A<int>::f(int) { }                 // non-template member function
template <> template <> void A<int>::f<>(int) { }   // member function template specialization

int main() {
  A<char> ac;
  ac.f(1);          // non-template
  ac.f('c');        // template
  ac.f<>(1);        // template
}
end example
]
A member function template shall not be virtual.
[Example
:
template <class T> struct AA {
  template <class C> virtual void g(C);     // error
  virtual void f();                         // OK
};
end example
]
A specialization of a member function template does not override a virtual function from a base class.
[Example
:
class B {
  virtual void f(int);
};

class D : public B {
  template <class T> void f(T); // does not override B​::​f(int)
  void f(int i) { f<>(i); }     // overriding function that calls the template instantiation
};
end example
]
A specialization of a conversion function template is referenced in the same way as a non-template conversion function that converts to the same type.
[Example
:
struct A {
  template <class T> operator T*();
};
template <class T> A::operator T*(){ return 0; }
template <> A::operator char*(){ return 0; }    // specialization
template A::operator void*();                   // explicit instantiation

int main() {
  A a;
  int* ip;
  ip = a.operator int*();       // explicit call to template operator A​::​operator int*()
}
end example
]
[Note
:
Because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates.
end note
]
A specialization of a conversion function template is not found by name lookup.
Instead, any conversion function templates visible in the context of the use are considered.
For each such operator, if argument deduction succeeds ([temp.deduct.conv]), the resulting specialization is used as if found by name lookup.
A using-declaration in a derived class cannot refer to a specialization of a conversion function template in a base class.
Overload resolution ([over.ics.rank]) and partial ordering ([temp.func.order]) are used to select the best conversion function among multiple specializations of conversion function templates and/or non-template conversion functions.

17.5.3 Variadic templates [temp.variadic]

A template parameter pack is a template parameter that accepts zero or more template arguments.
[Example
:
template<class ... Types> struct Tuple { };

Tuple<> t0;                     // Types contains no arguments
Tuple<int> t1;                  // Types contains one argument: int
Tuple<int, float> t2;           // Types contains two arguments: int and float
Tuple<0> error;                 // error: 0 is not a type
end example
]
A function parameter pack is a function parameter that accepts zero or more function arguments.
[Example
:
template<class ... Types> void f(Types ... args);

f();                            // OK: args contains no arguments
f(1);                           // OK: args contains one argument: int
f(2, 1.0);                      // OK: args contains two arguments: int and double
end example
]
A parameter pack is either a template parameter pack or a function parameter pack.
A pack expansion consists of a pattern and an ellipsis, the instantiation of which produces zero or more instantiations of the pattern in a list (described below).
The form of the pattern depends on the context in which the expansion occurs.
Pack expansions can occur in the following contexts:
[Example
:
template<class ... Types> void f(Types ... rest);
template<class ... Types> void g(Types ... rest) {
  f(&rest ...);     // “&rest ...” is a pack expansion; “&rest” is its pattern
}
end example
]
For the purpose of determining whether a parameter pack satisfies a rule regarding entities other than parameter packs, the parameter pack is considered to be the entity that would result from an instantiation of the pattern in which it appears.
A parameter pack whose name appears within the pattern of a pack expansion is expanded by that pack expansion.
An appearance of the name of a parameter pack is only expanded by the innermost enclosing pack expansion.
The pattern of a pack expansion shall name one or more parameter packs that are not expanded by a nested pack expansion; such parameter packs are called unexpanded parameter packs in the pattern.
All of the parameter packs expanded by a pack expansion shall have the same number of arguments specified.
An appearance of a name of a parameter pack that is not expanded is ill-formed.
[Example
:
template<typename...> struct Tuple {};
template<typename T1, typename T2> struct Pair {};

template<class ... Args1> struct zip {
  template<class ... Args2> struct with {
    typedef Tuple<Pair<Args1, Args2> ... > type;
  };
};

typedef zip<short, int>::with<unsigned short, unsigned>::type T1;
    // T1 is Tuple<Pair<short, unsigned short>, Pair<int, unsigned>>
typedef zip<short>::with<unsigned short, unsigned>::type T2;
    // error: different number of arguments specified for Args1 and Args2

template<class ... Args>
  void g(Args ... args) {                   // OK: Args is expanded by the function parameter pack args
    f(const_cast<const Args*>(&args)...);   // OK: “Args” and “args” are expanded
    f(5 ...);                               // error: pattern does not contain any parameter packs
    f(args);                                // error: parameter pack “args” is not expanded
    f(h(args ...) + args ...);              // OK: first “args” expanded within h,
                                            // second “args” expanded within f
  }
end example
]
The instantiation of a pack expansion that is neither a sizeof... expression nor a fold-expression produces a list , where N is the number of elements in the pack expansion parameters.
Each is generated by instantiating the pattern and replacing each pack expansion parameter with its ith element.
Such an element, in the context of the instantiation, is interpreted as follows:
  • if the pack is a template parameter pack, the element is a template parameter ([temp.param]) of the corresponding kind (type or non-type) designating the type or value from the template argument; otherwise,
  • if the pack is a function parameter pack, the element is an id-expression designating the function parameter that resulted from the instantiation of the pattern where the pack is declared.
All of the become elements in the enclosing list.
[Note
:
The variety of list varies with the context: expression-list, base-specifier-list, template-argument-list, etc.
end note
]
When N is zero, the instantiation of the expansion produces an empty list.
Such an instantiation does not alter the syntactic interpretation of the enclosing construct, even in cases where omitting the list entirely would otherwise be ill-formed or would result in an ambiguity in the grammar.
[Example
:
template<class... T> struct X : T... { };
template<class... T> void f(T... values) {
  X<T...> x(values...);
}

template void f<>();    // OK: X<> has no base classes
                        // x is a variable of type X<> that is value-initialized
end example
]
The instantiation of a sizeof... expression ([expr.sizeof]) produces an integral constant containing the number of elements in the parameter pack it expands.
The instantiation of a fold-expression produces:
  • (( op ) op ) op for a unary left fold,
  • op ( op ( op )) for a unary right fold,
  • (((E op ) op ) op ) op for a binary left fold, and
  • op ( op ( op ( op E))) for a binary right fold.
In each case, op is the fold-operator, N is the number of elements in the pack expansion parameters, and each is generated by instantiating the pattern and replacing each pack expansion parameter with its ith element.
For a binary fold-expression, E is generated by instantiating the cast-expression that did not contain an unexpanded parameter pack.
[Example
:
template<typename ...Args>
  bool all(Args ...args) { return (... && args); }

bool b = all(true, true, true, false);
Within the instantiation of all, the returned expression expands to ((true && true) && true) && false, which evaluates to false.
end example
]
If N is zero for a unary fold-expression, the value of the expression is shown in Table 14; if the operator is not listed in Table 14, the instantiation is ill-formed.
Table 14 — Value of folding empty sequences
Operator
Value when parameter pack is empty
&&
true
||
false
,
void()

17.5.4 Friends [temp.friend]

A friend of a class or class template can be a function template or class template, a specialization of a function template or class template, or a non-template function or class.
For a friend function declaration that is not a template declaration:
  • if the name of the friend is a qualified or unqualified template-id, the friend declaration refers to a specialization of a function template, otherwise,
  • if the name of the friend is a qualified-id and a matching non-template function is found in the specified class or namespace, the friend declaration refers to that function, otherwise,
  • if the name of the friend is a qualified-id and a matching function template is found in the specified class or namespace, the friend declaration refers to the deduced specialization of that function template ([temp.deduct.decl]), otherwise,
  • the name shall be an unqualified-id that declares (or redeclares) a non-template function.
[Example
:
template<class T> class task;
template<class T> task<T>* preempt(task<T>*);

template<class T> class task {
  friend void next_time();
  friend void process(task<T>*);
  friend task<T>* preempt<T>(task<T>*);
  template<class C> friend int func(C);

  friend class task<int>;
  template<class P> friend class frd;
};
Here, each specialization of the task class template has the function next_­time as a friend; because process does not have explicit template-arguments, each specialization of the task class template has an appropriately typed function process as a friend, and this friend is not a function template specialization; because the friend preempt has an explicit template-argument T, each specialization of the task class template has the appropriate specialization of the function template preempt as a friend; and each specialization of the task class template has all specializations of the function template func as friends.
Similarly, each specialization of the task class template has the class template specialization task<int> as a friend, and has all specializations of the class template frd as friends.
end example
]
A friend template may be declared within a class or class template.
A friend function template may be defined within a class or class template, but a friend class template may not be defined in a class or class template.
In these cases, all specializations of the friend class or friend function template are friends of the class or class template granting friendship.
[Example
:
class A {
  template<class T> friend class B;                 // OK
  template<class T> friend void f(T){ /* ... */ }   // OK
};
end example
]
A template friend declaration specifies that all specializations of that template, whether they are implicitly instantiated ([temp.inst]), partially specialized ([temp.class.spec]) or explicitly specialized ([temp.expl.spec]), are friends of the class containing the template friend declaration.
[Example
:
class X {
  template<class T> friend struct A;
  class Y { };
};

template<class T> struct A { X::Y ab; };            // OK
template<class T> struct A<T*> { X::Y ab; };        // OK
end example
]
A member of a class template may be declared to be a friend of a non-template class.
In this case, the corresponding member of every specialization of the primary class template and class template partial specializations thereof is a friend of the class granting friendship.
For explicit specializations and specializations of partial specializations, the corresponding member is the member (if any) that has the same name, kind (type, function, class template, or function template), template parameters, and signature as the member of the class template instantiation that would otherwise have been generated.
[Example
:
template<class T> struct A {
  struct B { };
  void f();
  struct D {
    void g();
  };
};
template<> struct A<int> {
  struct B { };
  int f();
  struct D {
    void g();
  };
};

class C {
  template<class T> friend struct A<T>::B;      // grants friendship to A<int>​::​B even though
                                                // it is not a specialization of A<T>​::​B
  template<class T> friend void A<T>::f();      // does not grant friendship to A<int>​::​f()
                                                // because its return type does not match
  template<class T> friend void A<T>::D::g();   // does not grant friendship to A<int>​::​D​::​g()
                                                // because A<int>​::​D is not a specialization of A<T>​::​D
};
end example
]
[Note
:
A friend declaration may first declare a member of an enclosing namespace scope ([temp.inject]).
end note
]
A friend template shall not be declared in a local class.
Friend declarations shall not declare partial specializations.
[Example
:
template<class T> class A { };
class X {
  template<class T> friend class A<T*>;         // error
};
end example
]
When a friend declaration refers to a specialization of a function template, the function parameter declarations shall not include default arguments, nor shall the inline specifier be used in such a declaration.

17.5.5 Class template partial specializations [temp.class.spec]

A primary class template declaration is one in which the class template name is an identifier.
A template declaration in which the class template name is a simple-template-id is a partial specialization of the class template named in the simple-template-id.
A partial specialization of a class template provides an alternative definition of the template that is used instead of the primary definition when the arguments in a specialization match those given in the partial specialization ([temp.class.spec.match]).
The primary template shall be declared before any specializations of that template.
A partial specialization shall be declared before the first use of a class template specialization that would make use of the partial specialization as the result of an implicit or explicit instantiation in every translation unit in which such a use occurs; no diagnostic is required.
Each class template partial specialization is a distinct template and definitions shall be provided for the members of a template partial specialization ([temp.class.spec.mfunc]).
[Example
:
template<class T1, class T2, int I> class A             { };
template<class T, int I>            class A<T, T*, I>   { };
template<class T1, class T2, int I> class A<T1*, T2, I> { };
template<class T>                   class A<int, T*, 5> { };
template<class T1, class T2, int I> class A<T1, T2*, I> { };
The first declaration declares the primary (unspecialized) class template.
The second and subsequent declarations declare partial specializations of the primary template.
end example
]
The template parameters are specified in the angle bracket enclosed list that immediately follows the keyword template.
For partial specializations, the template argument list is explicitly written immediately following the class template name.
For primary templates, this list is implicitly described by the template parameter list.
Specifically, the order of the template arguments is the sequence in which they appear in the template parameter list.
[Example
:
The template argument list for the primary template in the example above is <T1, T2, I>.
end example
]
[Note
:
The template argument list shall not be specified in the primary template declaration.
For example,
template<class T1, class T2, int I>
class A<T1, T2, I> { };                         // error
end note
]
A class template partial specialization may be declared in any scope in which the corresponding primary template may be defined ([namespace.memdef], [class.mem], [temp.mem]).
[Example
:
template<class T> struct A {
  struct C {
    template<class T2> struct B { };
    template<class T2> struct B<T2**> { };      // partial specialization #1
  };
};

// partial specialization of A<T>​::​C​::​B<T2>
template<class T> template<class T2>
  struct A<T>::C::B<T2*> { };                   // #2

A<short>::C::B<int*> absip;                     // uses partial specialization #2
end example
]
Partial specialization declarations themselves are not found by name lookup.
Rather, when the primary template name is used, any previously-declared partial specializations of the primary template are also considered.
One consequence is that a using-declaration which refers to a class template does not restrict the set of partial specializations which may be found through the using-declaration.
[Example
:
namespace N {
  template<class T1, class T2> class A { };     // primary template
}

using N::A;                                     // refers to the primary template

namespace N {
  template<class T> class A<T, T*> { };         // partial specialization
}

A<int,int*> a;      // uses the partial specialization, which is found through the using-declaration
                    // which refers to the primary template
end example
]
A non-type argument is non-specialized if it is the name of a non-type parameter.
All other non-type arguments are specialized.
Within the argument list of a class template partial specialization, the following restrictions apply:
  • The type of a template parameter corresponding to a specialized non-type argument shall not be dependent on a parameter of the specialization.
    [Example
    :
    template <class T, T t> struct C {};
    template <class T> struct C<T, 1>;              // error
    
    template< int X, int (*array_ptr)[X] > class A {};
    int array[5];
    template< int X > class A<X,&array> { };        // error
    
    end example
    ]
  • The specialization shall be more specialized than the primary template ([temp.class.order]).
  • The template parameter list of a specialization shall not contain default template argument values.138
  • An argument shall not contain an unexpanded parameter pack.
    If an argument is a pack expansion ([temp.variadic]), it shall be the last argument in the template argument list.
There is no way in which they could be used.

17.5.5.1 Matching of class template partial specializations [temp.class.spec.match]

When a class template is used in a context that requires an instantiation of the class, it is necessary to determine whether the instantiation is to be generated using the primary template or one of the partial specializations.
This is done by matching the template arguments of the class template specialization with the template argument lists of the partial specializations.
  • If exactly one matching specialization is found, the instantiation is generated from that specialization.
  • If more than one matching specialization is found, the partial order rules ([temp.class.order]) are used to determine whether one of the specializations is more specialized than the others.
    If none of the specializations is more specialized than all of the other matching specializations, then the use of the class template is ambiguous and the program is ill-formed.
  • If no matches are found, the instantiation is generated from the primary template.
A partial specialization matches a given actual template argument list if the template arguments of the partial specialization can be deduced from the actual template argument list ([temp.deduct]).
[Example
:
template<class T1, class T2, int I> class A             { };    // #1
template<class T, int I>            class A<T, T*, I>   { };    // #2
template<class T1, class T2, int I> class A<T1*, T2, I> { };    // #3
template<class T>                   class A<int, T*, 5> { };    // #4
template<class T1, class T2, int I> class A<T1, T2*, I> { };    // #5

A<int, int, 1>   a1;            // uses #1
A<int, int*, 1>  a2;            // uses #2, T is int, I is 1
A<int, char*, 5> a3;            // uses #4, T is char
A<int, char*, 1> a4;            // uses #5, T1 is int, T2 is char, I is 1
A<int*, int*, 2> a5;            // ambiguous: matches #3 and #5
end example
]
If the template arguments of a partial specialization cannot be deduced because of the structure of its template-parameter-list and the template-id, the program is ill-formed.
[Example
:
template <int I, int J> struct A {};
template <int I> struct A<I+5, I*2> {};     // error

template <int I> struct A<I, I> {};         // OK

template <int I, int J, int K> struct B {};
template <int I> struct B<I, I*2, 2> {};    // OK
end example
]
In a type name that refers to a class template specialization, (e.g., A<int, int, 1>) the argument list shall match the template parameter list of the primary template.
The template arguments of a specialization are deduced from the arguments of the primary template.

17.5.5.2 Partial ordering of class template specializations [temp.class.order]

For two class template partial specializations, the first is more specialized than the second if, given the following rewrite to two function templates, the first function template is more specialized than the second according to the ordering rules for function templates ([temp.func.order]):
  • Each of the two function templates has the same template parameters as the corresponding partial specialization.
  • Each function template has a single function parameter whose type is a class template specialization where the template arguments are the corresponding template parameters from the function template for each template argument in the template-argument-list of the simple-template-id of the partial specialization.
[Example
:
template<int I, int J, class T> class X { };
template<int I, int J>          class X<I, J, int> { };         // #1
template<int I>                 class X<I, I, int> { };         // #2

template<int I0, int J0> void f(X<I0, J0, int>);                // A
template<int I0>         void f(X<I0, I0, int>);                // B

template <auto v>    class Y { };
template <auto* p>   class Y<p> { };                            // #3
template <auto** pp> class Y<pp> { };                           // #4

template <auto* p0>   void g(Y<p0>);                            // C
template <auto** pp0> void g(Y<pp0>);                           // D
According to the ordering rules for function templates, the function template B is more specialized than the function template A and the function template D is more specialized than the function template C.
Therefore, the partial specialization #2 is more specialized than the partial specialization #1 and the partial specialization #4 is more specialized than the partial specialization #3.
end example
]

17.5.5.3 Members of class template specializations [temp.class.spec.mfunc]

The template parameter list of a member of a class template partial specialization shall match the template parameter list of the class template partial specialization.
The template argument list of a member of a class template partial specialization shall match the template argument list of the class template partial specialization.
A class template specialization is a distinct template.
The members of the class template partial specialization are unrelated to the members of the primary template.
Class template partial specialization members that are used in a way that requires a definition shall be defined; the definitions of members of the primary template are never used as definitions for members of a class template partial specialization.
An explicit specialization of a member of a class template partial specialization is declared in the same way as an explicit specialization of the primary template.
[Example
:
// primary class template
template<class T, int I> struct A {
  void f();
};

// member of primary class template
template<class T, int I> void A<T,I>::f() { }

// class template partial specialization
template<class T> struct A<T,2> {
  void f();
  void g();
  void h();
};

// member of class template partial specialization
template<class T> void A<T,2>::g() { }

// explicit specialization
template<> void A<char,2>::h() { }

int main() {
  A<char,0> a0;
  A<char,2> a2;
  a0.f();           // OK, uses definition of primary template's member
  a2.g();           // OK, uses definition of partial specialization's member
  a2.h();           // OK, uses definition of explicit specialization's member
  a2.f();           // ill-formed, no definition of f for A<T,2>; the primary template is not used here
}
end example
]
If a member template of a class template is partially specialized, the member template partial specializations are member templates of the enclosing class template; if the enclosing class template is instantiated ([temp.inst], [temp.explicit]), a declaration for every member template partial specialization is also instantiated as part of creating the members of the class template specialization.
If the primary member template is explicitly specialized for a given (implicit) specialization of the enclosing class template, the partial specializations of the member template are ignored for this specialization of the enclosing class template.
If a partial specialization of the member template is explicitly specialized for a given (implicit) specialization of the enclosing class template, the primary member template and its other partial specializations are still considered for this specialization of the enclosing class template.
[Example
:
template<class T> struct A {
  template<class T2> struct B {};                     // #1
  template<class T2> struct B<T2*> {};                // #2
};

template<> template<class T2> struct A<short>::B {};  // #3

A<char>::B<int*>  abcip;  // uses #2
A<short>::B<int*> absip;  // uses #3
A<char>::B<int>  abci;    // uses #1
end example
]

17.5.6 Function templates [temp.fct]

A function template defines an unbounded set of related functions.
[Example
:
A family of sort functions might be declared like this:
template<class T> class Array { };
template<class T> void sort(Array<T>&);
end example
]
A function template can be overloaded with other function templates and with non-template functions ([dcl.fct]).
A non-template function is not related to a function template (i.e., it is never considered to be a specialization), even if it has the same name and type as a potentially generated function template specialization.139
That is, declarations of non-template functions do not merely guide overload resolution of function template specializations with the same name.
If such a non-template function is odr-used ([basic.def.odr]) in a program, it must be defined; it will not be implicitly instantiated using the function template definition.

17.5.6.2 Partial ordering of function templates [temp.func.order]

If a function template is overloaded, the use of a function template specialization might be ambiguous because template argument deduction ([temp.deduct]) may associate the function template specialization with more than one function template declaration.
Partial ordering of overloaded function template declarations is used in the following contexts to select the function template to which a function template specialization refers:
Partial ordering selects which of two function templates is more specialized than the other by transforming each template in turn (see next paragraph) and performing template argument deduction using the function type.
The deduction process determines whether one of the templates is more specialized than the other.
If so, the more specialized template is the one chosen by the partial ordering process.
To produce the transformed template, for each type, non-type, or template template parameter (including template parameter packs ([temp.variadic]) thereof) synthesize a unique type, value, or class template respectively and substitute it for each occurrence of that parameter in the function type of the template.
[Note
:
The type replacing the placeholder in the type of the value synthesized for a non-type template parameter is also a unique synthesized type.
end note
]
If only one of the function templates M is a non-static member of some class A, M is considered to have a new first parameter inserted in its function parameter list.
Given cv as the cv-qualifiers of M (if any), the new parameter is of type “rvalue reference to cv A” if the optional ref-qualifier of M is && or if M has no ref-qualifier and the first parameter of the other template has rvalue reference type.
Otherwise, the new parameter is of type “lvalue reference to cv A.
[Note
:
This allows a non-static member to be ordered with respect to a non-member function and for the results to be equivalent to the ordering of two equivalent non-members.
end note
]
[Example
:
struct A { };
template<class T> struct B {
  template<class R> int operator*(R&);              // #1
};

template<class T, class R> int operator*(T&, R&);   // #2

// The declaration of B​::​operator* is transformed into the equivalent of
// template<class R> int operator*(B<A>&, R&);      // #1a

int main() {
  A a;
  B<A> b;
  b * a;                                            // calls #1a
}
end example
]
Using the transformed function template's function type, perform type deduction against the other template as described in [temp.deduct.partial].
[Example
:
template<class T> struct A { A(); };

template<class T> void f(T);
template<class T> void f(T*);
template<class T> void f(const T*);

template<class T> void g(T);
template<class T> void g(T&);

template<class T> void h(const T&);
template<class T> void h(A<T>&);

void m() {
  const int* p;
  f(p);             // f(const T*) is more specialized than f(T) or f(T*)
  float x;
  g(x);             // ambiguous: g(T) or g(T&)
  A<int> z;
  h(z);             // overload resolution selects h(A<T>&)
  const A<int> z2;
  h(z2);            // h(const T&) is called because h(A<T>&) is not callable
}
end example
]
[Note
:
Since partial ordering in a call context considers only parameters for which there are explicit call arguments, some parameters are ignored (namely, function parameter packs, parameters with default arguments, and ellipsis parameters).
[Example
:
template<class T> void f(T);                            // #1
template<class T> void f(T*, int=1);                    // #2
template<class T> void g(T);                            // #3
template<class T> void g(T*, ...);                      // #4
int main() {
  int* ip;
  f(ip);                                                // calls #2
  g(ip);                                                // calls #4
}
end example
]
[Example
:
template<class T, class U> struct A { };

template<class T, class U> void f(U, A<U, T>* p = 0);   // #1
template<         class U> void f(U, A<U, U>* p = 0);   // #2
template<class T         > void g(T, T = T());          // #3
template<class T, class... U> void g(T, U ...);         // #4

void h() {
  f<int>(42, (A<int, int>*)0);                          // calls #2
  f<int>(42);                                           // error: ambiguous
  g(42);                                                // error: ambiguous
}
end example
]
[Example
:
template<class T, class... U> void f(T, U...);          // #1
template<class T            > void f(T);                // #2
template<class T, class... U> void g(T*, U...);         // #3
template<class T            > void g(T);                // #4

void h(int i) {
  f(&i);                                                // error: ambiguous
  g(&i);                                                // OK: calls #3
}
end example
]
end note
]

17.5.7 Alias templates [temp.alias]

An alias template is a name for a family of types.
The name of the alias template is a template-name.
When a template-id refers to the specialization of an alias template, it is equivalent to the associated type obtained by substitution of its template-arguments for the template-parameters in the type-id of the alias template.
[Note
:
An alias template name is never deduced.
end note
]
[Example
:
template<class T> struct Alloc { /* ... */ };
template<class T> using Vec = vector<T, Alloc<T>>;
Vec<int> v;         // same as vector<int, Alloc<int>> v;

template<class T>
  void process(Vec<T>& v)
  { /* ... */ }

template<class T>
  void process(vector<T, Alloc<T>>& w)
  { /* ... */ }     // error: redefinition

template<template<class> class TT>
  void f(TT<int>);

f(v);               // error: Vec not deduced

template<template<class,class> class TT>
  void g(TT<int, Alloc<int>>);
g(v);               // OK: TT = vector
end example
]
However, if the template-id is dependent, subsequent template argument substitution still applies to the template-id.
[Example
:
template<typename...> using void_t = void;
template<typename T> void_t<typename T::foo> f();
f<int>();           // error, int does not have a nested type foo
end example
]
The type-id in an alias template declaration shall not refer to the alias template being declared.
The type produced by an alias template specialization shall not directly or indirectly make use of that specialization.
[Example
:
template <class T> struct A;
template <class T> using B = typename A<T>::U;
template <class T> struct A {
  typedef B<T> U;
};
B<short> b;         // error: instantiation of B<short> uses own type via A<short>​::​U
end example
]

17.6 Name resolution [temp.res]

Three kinds of names can be used within a template definition:
A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename.
[Example
:
// no B declared here

class X;

template<class T> class Y {
  class Z;                      // forward declaration of member class

  void f() {
    X* a1;                      // declare pointer to X
    T* a2;                      // declare pointer to T
    Y* a3;                      // declare pointer to Y<T>
    Z* a4;                      // declare pointer to Z
    typedef typename T::A TA;
    TA* a5;                     // declare pointer to T's A
    typename T::A* a6;          // declare pointer to T's A
    T::A* a7;                   // T​::​A is not a type name:
                                // multiplication of T​::​A by a7; ill-formed, no visible declaration of a7
    B* a8;                      // B is not a type name:
                                // multiplication of B by a8; ill-formed, no visible declarations of B and a8
  }
};
end example
]
When a qualified-id is intended to refer to a type that is not a member of the current instantiation ([temp.dep.type]) and its nested-name-specifier refers to a dependent type, it shall be prefixed by the keyword typename, forming a typename-specifier.
If the qualified-id in a typename-specifier does not denote a type or a class template, the program is ill-formed.
If a specialization of a template is instantiated for a set of template-arguments such that the qualified-id prefixed by typename does not denote a type or a class template, the specialization is ill-formed.
The usual qualified name lookup ([basic.lookup.qual]) is used to find the qualified-id even in the presence of typename.
[Example
:
struct A {
  struct X { };
  int X;
};
struct B {
  struct X { };
};
template<class T> void f(T t) {
  typename T::X x;
}
void foo() {
  A a;
  B b;
  f(b);             // OK: T​::​X refers to B​::​X
  f(a);             // error: T​::​X refers to the data member A​::​X not the struct A​::​X
}
end example
]
A qualified name used as the name in a class-or-decltype or an elaborated-type-specifier is implicitly assumed to name a type, without the use of the typename keyword.
In a nested-name-specifier that immediately contains a nested-name-specifier that depends on a template parameter, the identifier or simple-template-id is implicitly assumed to name a type, without the use of the typename keyword.
[Note
:
The typename keyword is not permitted by the syntax of these constructs.
end note
]
If, for a given set of template arguments, a specialization of a template is instantiated that refers to a qualified-id that denotes a type or a class template, and the qualified-id refers to a member of an unknown specialization, the qualified-id shall either be prefixed by typename or shall be used in a context in which it implicitly names a type as described above.
[Example
:
template <class T> void f(int i) {
  T::x * i;         // T​::​x must not be a type
}

struct Foo {
  typedef int x;
};

struct Bar {
  static int const x = 5;
};

int main() {
  f<Bar>(1);        // OK
  f<Foo>(1);        // error: Foo​::​x is a type
}
end example
]
Within the definition of a class template or within the definition of a member of a class template following the declarator-id, the keyword typename is not required when referring to the name of a previously declared member of the class template that declares a type or a class template.
[Note
:
Such names can be found using unqualified name lookup ([basic.lookup.unqual]), class member lookup ([class.qual]) into the current instantiation ([temp.dep.type]), or class member access expression lookup ([basic.lookup.classref]) when the type of the object expression is the current instantiation ([temp.dep.expr]).
end note
]
[Example
:
template<class T> struct A {
  typedef int B;
  B b;              // OK, no typename required
};
end example
]
Knowing which names are type names allows the syntax of every template to be checked.
The program is ill-formed, no diagnostic required, if:
  • no valid specialization can be generated for a template or a substatement of a constexpr if statement ([stmt.if]) within a template and the template is not instantiated, or
  • every valid specialization of a variadic template requires an empty template parameter pack, or
  • a hypothetical instantiation of a template immediately following its definition would be ill-formed due to a construct that does not depend on a template parameter, or
  • the interpretation of such a construct in the hypothetical instantiation is different from the interpretation of the corresponding construct in any actual instantiation of the template.
    [Note
    :
    This can happen in situations including the following:
    • a type used in a non-dependent name is incomplete at the point at which a template is defined but is complete at the point at which an instantiation is performed, or
    • lookup for a name in the template definition found a using-declaration, but the lookup in the corresponding scope in the instantiation does not find any declarations because the using-declaration was a pack expansion and the corresponding pack is empty, or
    • an instantiation uses a default argument or default template argument that had not been defined at the point at which the template was defined, or
    • constant expression evaluation ([expr.const]) within the template instantiation uses
      • the value of a const object of integral or unscoped enumeration type or
      • the value of a constexpr object or
      • the value of a reference or
      • the definition of a constexpr function,
      and that entity was not defined when the template was defined, or
    • a class template specialization or variable template specialization that is specified by a non-dependent simple-template-id is used by the template, and either it is instantiated from a partial specialization that was not defined when the template was defined or it names an explicit specialization that was not declared when the template was defined.
    end note
    ]
Otherwise, no diagnostic shall be issued for a template for which a valid specialization can be generated.
[Note
:
If a template is instantiated, errors will be diagnosed according to the other rules in this International Standard.
Exactly when these errors are diagnosed is a quality of implementation issue.
end note
]
[Example
:
int j;
template<class T> class X {
  void f(T t, int i, char* p) {
    t = i;          // diagnosed if X​::​f is instantiated, and the assignment to t is an error
    p = i;          // may be diagnosed even if X​::​f is not instantiated
    p = j;          // may be diagnosed even if X​::​f is not instantiated
  }
  void g(T t) {
    +;              // may be diagnosed even if X​::​g is not instantiated
  }
};

template<class... T> struct A {
  void operator++(int, T... t);                     // error: too many parameters
};
template<class... T> union X : T... { };            // error: union with base class
template<class... T> struct A : T...,  T... { };    // error: duplicate base class
end example
]
When looking for the declaration of a name used in a template definition, the usual lookup rules ([basic.lookup.unqual], [basic.lookup.argdep]) are used for non-dependent names.
The lookup of names dependent on the template parameters is postponed until the actual template argument is known ([temp.dep]).
[Example
:
#include <iostream>
using namespace std;

template<class T> class Set {
  T* p;
  int cnt;
public:
  Set();
  Set<T>(const Set<T>&);
  void printall() {
    for (int i = 0; i<cnt; i++)
      cout << p[i] << '\n';
  }
};
in the example, i is the local variable i declared in printall, cnt is the member cnt declared in Set, and cout is the standard output stream declared in iostream.
However, not every declaration can be found this way; the resolution of some names must be postponed until the actual template-arguments are known.
For example, even though the name operator<< is known within the definition of printall() and a declaration of it can be found in <iostream>, the actual declaration of operator<< needed to print p[i] cannot be known until it is known what type T is ([temp.dep]).
end example
]
If a name does not depend on a template-parameter (as defined in [temp.dep]), a declaration (or set of declarations) for that name shall be in scope at the point where the name appears in the template definition; the name is bound to the declaration (or declarations) found at that point and this binding is not affected by declarations that are visible at the point of instantiation.
[Example
:
void f(char);

template<class T> void g(T t) {
  f(1);             // f(char)
  f(T(1));          // dependent
  f(t);             // dependent
  dd++;             // not dependent; error: declaration for dd not found
}

enum E { e };
void f(E);

double dd;
void h() {
  g(e);             // will cause one call of f(char) followed by two calls of f(E)
  g('a');           // will cause three calls of f(char)
}
end example
]
[Note
:
For purposes of name lookup, default arguments and noexcept-specifiers of function templates and default arguments and noexcept-specifiers of member functions of class templates are considered definitions ([temp.decls]).
end note
]

17.6.1 Locally declared names [temp.local]

Like normal (non-template) classes, class templates have an injected-class-name (Clause [class]).
The injected-class-name can be used as a template-name or a type-name.
When it is used with a template-argument-list, as a template-argument for a template template-parameter, or as the final identifier in the elaborated-type-specifier of a friend class template declaration, it refers to the class template itself.
Otherwise, it is equivalent to the template-name followed by the template-parameters of the class template enclosed in <>.
Within the scope of a class template specialization or partial specialization, when the injected-class-name is used as a type-name, it is equivalent to the template-name followed by the template-arguments of the class template specialization or partial specialization enclosed in <>.
[Example
:
template<template<class> class T> class A { };
template<class T> class Y;
template<> class Y<int> {
  Y* p;                               // meaning Y<int>
  Y<char>* q;                         // meaning Y<char>
  A<Y>* a;                            // meaning A<​::​Y>
  class B {
    template<class> friend class Y;   // meaning ​::​Y
  };
};
end example
]
The injected-class-name of a class template or class template specialization can be used either as a template-name or a type-name wherever it is in scope.
[Example
:
template <class T> struct Base {
  Base* p;
};

template <class T> struct Derived: public Base<T> {
  typename Derived::Base* p;    // meaning Derived​::​Base<T>
};

template<class T, template<class> class U = T::template Base> struct Third { };
Third<Base<int> > t;            // OK: default argument uses injected-class-name as a template
end example
]
A lookup that finds an injected-class-name ([class.member.lookup]) can result in an ambiguity in certain cases (for example, if it is found in more than one base class).
If all of the injected-class-names that are found refer to specializations of the same class template, and if the name is used as a template-name, the reference refers to the class template itself and not a specialization thereof, and is not ambiguous.
[Example
:
template <class T> struct Base { };
template <class T> struct Derived: Base<int>, Base<char> {
  typename Derived::Base b;             // error: ambiguous
  typename Derived::Base<double> d;     // OK
};
end example
]
When the normal name of the template (i.e., the name from the enclosing scope, not the injected-class-name) is used, it always refers to the class template itself and not a specialization of the template.
[Example
:
template<class T> class X {
  X* p;             // meaning X<T>
  X<T>* p2;
  X<int>* p3;
  ::X* p4;          // error: missing template argument list
                    // ​::​X does not refer to the injected-class-name
};
end example
]
A template-parameter shall not be redeclared within its scope (including nested scopes).
A template-parameter shall not have the same name as the template name.
[Example
:
template<class T, int i> class Y {
  int T;            // error: template-parameter redeclared
  void f() {
    char T;         // error: template-parameter redeclared
  }
};

template<class X> class X;      // error: template-parameter redeclared
end example
]
In the definition of a member of a class template that appears outside of the class template definition, the name of a member of the class template hides the name of a template-parameter of any enclosing class templates (but not a template-parameter of the member if the member is a class or function template).
[Example
:
template<class T> struct A {
  struct B { /* ... */ };
  typedef void C;
  void f();
  template<class U> void g(U);
};

template<class B> void A<B>::f() {
  B b;              // A's B, not the template parameter
}

template<class B> template<class C> void A<B>::g(C) {
  B b;              // A's B, not the template parameter
  C c;              // the template parameter C, not A's C
}
end example
]
In the definition of a member of a class template that appears outside of the namespace containing the class template definition, the name of a template-parameter hides the name of a member of this namespace.
[Example
:
namespace N {
  class C { };
  template<class T> class B {
    void f(T);
  };
}
template<class C> void N::B<C>::f(C) {
  C b;              // C is the template parameter, not N​::​C
}
end example
]
In the definition of a class template or in the definition of a member of such a template that appears outside of the template definition, for each non-dependent base class ([temp.dep.type]), if the name of the base class or the name of a member of the base class is the same as the name of a template-parameter, the base class name or member name hides the template-parameter name ([basic.scope.hiding]).
[Example
:
struct A {
  struct B { /* ... */ };
  int a;
  int Y;
};

template<class B, class a> struct X : A {
  B b;              // A's B
  a b;              // error: A's a isn't a type name
};
end example
]

17.6.2 Dependent names [temp.dep]

Inside a template, some constructs have semantics which may differ from one instantiation to another.
Such a construct depends on the template parameters.
In particular, types and expressions may depend on the type and/or value of template parameters (as determined by the template arguments) and this determines the context for name lookup for certain names.
An expressions may be type-dependent (that is, its type may depend on a template parameter) or value-dependent (that is, its value when evaluated as a constant expression ([expr.const]) may depend on a template parameter) as described in this subclause.
In an expression of the form:
If an operand of an operator is a type-dependent expression, the operator also denotes a dependent name.
Such names are unbound and are looked up at the point of the template instantiation ([temp.point]) in both the context of the template definition and the context of the point of instantiation.
[Example
:
template<class T> struct X : B<T> {
  typename T::A* pa;
  void f(B<T>* pb) {
    static int i = B<T>::i;
    pb->j++;
  }
};
the base class name B<T>, the type name T​::​A, the names B<T>​::​i and pb->j explicitly depend on the template-parameter.
end example
]
In the definition of a class or class template, the scope of a dependent base class ([temp.dep.type]) is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.
[Example
:
typedef double A;
template<class T> class B {
  typedef int A;
};
template<class T> struct X : B<T> {
  A a;              // a has type double
};
The type name A in the definition of X<T> binds to the typedef name defined in the global namespace scope, not to the typedef name defined in the base class B<T>.
end example
]
[Example
:
struct A {
  struct B { /* ... */ };
  int a;
  int Y;
};

int a;

template<class T> struct Y : T {
  struct B { /* ... */ };
  B b;                          // The B defined in Y
  void f(int i) { a = i; }      // ​::​a
  Y* p;                         // Y<T>
};

Y<A> ya;
The members A​::​B, A​::​a, and A​::​Y of the template argument A do not affect the binding of names in Y<A>.
end example
]

17.6.2.1 Dependent types [temp.dep.type]

A name refers to the current instantiation if it is
  • in the definition of a class template, a nested class of a class template, a member of a class template, or a member of a nested class of a class template, the injected-class-name (Clause [class]) of the class template or nested class,
  • in the definition of a primary class template or a member of a primary class template, the name of the class template followed by the template argument list of the primary template (as described below) enclosed in <> (or an equivalent template alias specialization),
  • in the definition of a nested class of a class template, the name of the nested class referenced as a member of the current instantiation, or
  • in the definition of a partial specialization or a member of a partial specialization, the name of the class template followed by the template argument list of the partial specialization enclosed in <> (or an equivalent template alias specialization).
    If the nth template parameter is a parameter pack, the nth template argument is a pack expansion ([temp.variadic]) whose pattern is the name of the parameter pack.
The template argument list of a primary template is a template argument list in which the nth template argument has the value of the nth template parameter of the class template.
If the nth template parameter is a template parameter pack ([temp.variadic]), the nth template argument is a pack expansion ([temp.variadic]) whose pattern is the name of the template parameter pack.
A template argument that is equivalent to a template parameter (i.e., has the same constant value or the same type as the template parameter) can be used in place of that template parameter in a reference to the current instantiation. In the case of a non-type template argument, the argument must have been given the value of the template parameter and not an expression in which the template parameter appears as a subexpression.
[Example
:
template <class T> class A {
  A* p1;                        // A is the current instantiation
  A<T>* p2;                     // A<T> is the current instantiation
  A<T*> p3;                     // A<T*> is not the current instantiation
  ::A<T>* p4;                   // ​::​A<T> is the current instantiation
  class B {
    B* p1;                      // B is the current instantiation
    A<T>::B* p2;                // A<T>​::​B is the current instantiation
    typename A<T*>::B* p3;      // A<T*>​::​B is not the current instantiation
  };
};

template <class T> class A<T*> {
  A<T*>* p1;                    // A<T*> is the current instantiation
  A<T>* p2;                     // A<T> is not the current instantiation
};

template <class T1, class T2, int I> struct B {
  B<T1, T2, I>* b1;             // refers to the current instantiation
  B<T2, T1, I>* b2;             // not the current instantiation
  typedef T1 my_T1;
  static const int my_I = I;
  static const int my_I2 = I+0;
  static const int my_I3 = my_I;
  B<my_T1, T2, my_I>* b3;       // refers to the current instantiation
  B<my_T1, T2, my_I2>* b4;      // not the current instantiation
  B<my_T1, T2, my_I3>* b5;      // refers to the current instantiation
};
end example
]
A dependent base class is a base class that is a dependent type and is not the current instantiation.
[Note
:
A base class can be the current instantiation in the case of a nested class naming an enclosing class as a base.
[Example
:
template<class T> struct A {
  typedef int M;
  struct B {
    typedef void M;
    struct C;
  };
};

template<class T> struct A<T>::B::C : A<T> {
  M m;                          // OK, A<T>​::​M
};
end example
]
end note
]
  • An unqualified name that, when looked up, refers to at least one member of a class that is the current instantiation or a non-dependent base class thereof.
    [Note
    :
    This can only occur when looking up a name in a scope enclosed by the definition of a class template.
    end note
    ]
  • A qualified-id in which the nested-name-specifier refers to the current instantiation and that, when looked up, refers to at least one member of a class that is the current instantiation or a non-dependent base class thereof.
    [Note
    :
    If no such member is found, and the current instantiation has any dependent base classes, then the qualified-id is a member of an unknown specialization; see below.
    end note
    ]
  • An id-expression denoting the member in a class member access expression ([expr.ref]) for which the type of the object expression is the current instantiation, and the id-expression, when looked up ([basic.lookup.classref]), refers to at least one member of a class that is the current instantiation or a non-dependent base class thereof.
    [Note
    :
    If no such member is found, and the current instantiation has any dependent base classes, then the id-expression is a member of an unknown specialization; see below.
    end note
    ]
[Example
:
template <class T> class A {
  static const int i = 5;
  int n1[i];                    // i refers to a member of the current instantiation
  int n2[A::i];                 // A​::​i refers to a member of the current instantiation
  int n3[A<T>::i];              // A<T>​::​i refers to a member of the current instantiation
  int f();
};

template <class T> int A<T>::f() {
  return i;                     // i refers to a member of the current instantiation
}
end example
]
A name is a dependent member of the current instantiation if it is a member of the current instantiation that, when looked up, refers to at least one member of a class that is the current instantiation.
  • A qualified-id in which the nested-name-specifier names a dependent type that is not the current instantiation.
  • A qualified-id in which the nested-name-specifier refers to the current instantiation, the current instantiation has at least one dependent base class, and name lookup of the qualified-id does not find any member of a class that is the current instantiation or a non-dependent base class thereof.
  • An id-expression denoting the member in a class member access expression ([expr.ref]) in which either
    • the type of the object expression is the current instantiation, the current instantiation has at least one dependent base class, and name lookup of the id-expression does not find a member of a class that is the current instantiation or a non-dependent base class thereof; or
    • the type of the object expression is dependent and is not the current instantiation.
If a qualified-id in which the nested-name-specifier refers to the current instantiation is not a member of the current instantiation or a member of an unknown specialization, the program is ill-formed even if the template containing the qualified-id is not instantiated; no diagnostic required.
Similarly, if the id-expression in a class member access expression for which the type of the object expression is the current instantiation does not refer to a member of the current instantiation or a member of an unknown specialization, the program is ill-formed even if the template containing the member access expression is not instantiated; no diagnostic required.
[Example
:
template<class T> class A {
  typedef int type;
  void f() {
    A<T>::type i;               // OK: refers to a member of the current instantiation
    typename A<T>::other j;     // error: neither a member of the current instantiation nor
                                // a member of an unknown specialization
  }
};
end example
]
If, for a given set of template arguments, a specialization of a template is instantiated that refers to a member of the current instantiation with a qualified-id or class member access expression, the name in the qualified-id or class member access expression is looked up in the template instantiation context.
If the result of this lookup differs from the result of name lookup in the template definition context, name lookup is ambiguous.
[Example
:
struct A {
  int m;
};

struct B {
  int m;
};

template<typename T>
struct C : A, T {
  int f() { return this->m; }   // finds A​::​m in the template definition context
  int g() { return m; }         // finds A​::​m in the template definition context
};

template int C<B>::f();         // error: finds both A​::​m and B​::​m
template int C<B>::g();         // OK: transformation to class member access syntax
                                // does not occur in the template definition context; see [class.mfct.non-static]
end example
]
A type is dependent if it is
  • a template parameter,
  • a member of an unknown specialization,
  • a nested class or enumeration that is a dependent member of the current instantiation,
  • a cv-qualified type where the cv-unqualified type is dependent,
  • a compound type constructed from any dependent type,
  • an array type whose element type is dependent or whose bound (if any) is value-dependent,
  • a function type whose exception specification is value-dependent,
  • a simple-template-id in which either the template name is a template parameter or any of the template arguments is a dependent type or an expression that is type-dependent or value-dependent or is a pack expansion
    [Note
    :
    This includes an injected-class-name (Clause [class]) of a class template used without a template-argument-list.
    end note
    ]
    , or
  • denoted by decltype(expression), where expression is type-dependent ([temp.dep.expr]).
[Note
:
Because typedefs do not introduce new types, but instead simply refer to other types, a name that refers to a typedef that is a member of the current instantiation is dependent only if the type referred to is dependent.
end note
]

17.6.2.2 Type-dependent expressions [temp.dep.expr]

Except as described below, an expression is type-dependent if any subexpression is type-dependent.
this is type-dependent if the class type of the enclosing member function is dependent ([temp.dep.type]).
An id-expression is type-dependent if it contains
or if it names a dependent member of the current instantiation that is a static data member of type “array of unknown bound of T” for some T ([temp.static]).
Expressions of the following forms are type-dependent only if the type specified by the type-id, simple-type-specifier or new-type-id is dependent, even if any subexpression is type-dependent:
Expressions of the following forms are never type-dependent (because the type of the expression cannot be dependent):
literal
postfix-expression . pseudo-destructor-name
postfix-expression -> pseudo-destructor-name
sizeof unary-expression
sizeof ( type-id )
sizeof ... ( identifier )
alignof ( type-id )
typeid ( expression )
typeid ( type-id )
:: delete cast-expression
:: delete [ ] cast-expression
throw assignment-expression
noexcept ( expression )
[Note
:
For the standard library macro offsetof, see [support.types].
end note
]
A class member access expression ([expr.ref]) is type-dependent if the expression refers to a member of the current instantiation and the type of the referenced member is dependent, or the class member access expression refers to a member of an unknown specialization.
[Note
:
In an expression of the form x.y or xp->y the type of the expression is usually the type of the member y of the class of x (or the class pointed to by xp).
However, if x or xp refers to a dependent type that is not the current instantiation, the type of y is always dependent.
If x or xp refers to a non-dependent type or refers to the current instantiation, the type of y is the type of the class member access expression.
end note
]
A braced-init-list is type-dependent if any element is type-dependent or is a pack expansion.
A fold-expression is type-dependent.

17.6.2.3 Value-dependent expressions [temp.dep.constexpr]

Except as described below, an expression used in a context where a constant expression is required is value-dependent if any subexpression is value-dependent.
An id-expression is value-dependent if:
  • it is type-dependent,
  • it is the name of a non-type template parameter,
  • it names a static data member that is a dependent member of the current instantiation and is not initialized in a member-declarator,
  • it names a static member function that is a dependent member of the current instantiation, or
  • it is a constant with literal type and is initialized with an expression that is value-dependent.
Expressions of the following form are value-dependent if the unary-expression or expression is type-dependent or the type-id is dependent:
sizeof unary-expression
sizeof ( type-id )
typeid ( expression )
typeid ( type-id )
alignof ( type-id )
noexcept ( expression )
[Note
:
For the standard library macro offsetof, see [support.types].
end note
]
Expressions of the following form are value-dependent if either the type-id or simple-type-specifier is dependent or the expression or cast-expression is value-dependent:
simple-type-specifier ( expression-list )
static_cast < type-id > ( expression )
const_cast < type-id > ( expression )
reinterpret_cast < type-id > ( expression )
( type-id ) cast-expression
Expressions of the following form are value-dependent:
sizeof ... ( identifier )
fold-expression
An expression of the form &qualified-id where the qualified-id names a dependent member of the current instantiation is value-dependent.
An expression of the form &cast-expression is also value-dependent if evaluating cast-expression as a core constant expression ([expr.const]) succeeds and the result of the evaluation refers to a templated entity that is an object with static or thread storage duration or a member function.

17.6.2.4 Dependent template arguments [temp.dep.temp]

A type template-argument is dependent if the type it specifies is dependent.
A non-type template-argument is dependent if its type is dependent or the constant expression it specifies is value-dependent.
Furthermore, a non-type template-argument is dependent if the corresponding non-type template-parameter is of reference or pointer type and the template-argument designates or points to a member of the current instantiation or a member of a dependent type.
A template template-argument is dependent if it names a template-parameter or is a qualified-id that refers to a member of an unknown specialization.

17.6.3 Non-dependent names [temp.nondep]

Non-dependent names used in a template definition are found using the usual name lookup and bound at the point they are used.
[Example
:
void g(double);
void h();

template<class T> class Z {
public:
  void f() {
    g(1);           // calls g(double)
    h++;            // ill-formed: cannot increment function; this could be diagnosed
                    // either here or at the point of instantiation
  }
};

void g(int);        // not in scope at the point of the template definition, not considered for the call g(1)
end example
]

17.6.4 Dependent name resolution [temp.dep.res]

In resolving dependent names, names from the following sources are considered:
  • Declarations that are visible at the point of definition of the template.
  • Declarations from namespaces associated with the types of the function arguments both from the instantiation context ([temp.point]) and from the definition context.

17.6.4.1 Point of instantiation [temp.point]

For a function template specialization, a member function template specialization, or a specialization for a member function or static data member of a class template, if the specialization is implicitly instantiated because it is referenced from within another template specialization and the context from which it is referenced depends on a template parameter, the point of instantiation of the specialization is the point of instantiation of the enclosing specialization.
Otherwise, the point of instantiation for such a specialization immediately follows the namespace scope declaration or definition that refers to the specialization.
If a function template or member function of a class template is called in a way which uses the definition of a default argument of that function template or member function, the point of instantiation of the default argument is the point of instantiation of the function template or member function specialization.
For a noexcept-specifier of a function template specialization or specialization of a member function of a class template, if the noexcept-specifier is implicitly instantiated because it is needed by another template specialization and the context that requires it depends on a template parameter, the point of instantiation of the noexcept-specifier is the point of instantiation of the specialization that requires it.
Otherwise, the point of instantiation for such a noexcept-specifier immediately follows the namespace scope declaration or definition that requires the noexcept-specifier.
For a class template specialization, a class member template specialization, or a specialization for a class member of a class template, if the specialization is implicitly instantiated because it is referenced from within another template specialization, if the context from which the specialization is referenced depends on a template parameter, and if the specialization is not instantiated previous to the instantiation of the enclosing template, the point of instantiation is immediately before the point of instantiation of the enclosing template.
Otherwise, the point of instantiation for such a specialization immediately precedes the namespace scope declaration or definition that refers to the specialization.
If a virtual function is implicitly instantiated, its point of instantiation is immediately following the point of instantiation of its enclosing class template specialization.
An explicit instantiation definition is an instantiation point for the specialization or specializations specified by the explicit instantiation.
The instantiation context of an expression that depends on the template arguments is the set of declarations with external linkage declared prior to the point of instantiation of the template specialization in the same translation unit.
A specialization for a function template, a member function template, or of a member function or static data member of a class template may have multiple points of instantiations within a translation unit, and in addition to the points of instantiation described above, for any such specialization that has a point of instantiation within the translation unit, the end of the translation unit is also considered a point of instantiation.
A specialization for a class template has at most one point of instantiation within a translation unit.
A specialization for any template may have points of instantiation in multiple translation units.
If two different points of instantiation give a template specialization different meanings according to the one-definition rule ([basic.def.odr]), the program is ill-formed, no diagnostic required.

17.6.4.2 Candidate functions [temp.dep.candidate]

For a function call where the postfix-expression is a dependent name, the candidate functions are found using the usual lookup rules ([basic.lookup.unqual], [basic.lookup.argdep]) except that:
  • For the part of the lookup using unqualified name lookup ([basic.lookup.unqual]), only function declarations from the template definition context are found.
  • For the part of the lookup using associated namespaces ([basic.lookup.argdep]), only function declarations found in either the template definition context or the template instantiation context are found.
If the call would be ill-formed or would find a better match had the lookup within the associated namespaces considered all the function declarations with external linkage introduced in those namespaces in all translation units, not just considering those declarations found in the template definition and template instantiation contexts, then the program has undefined behavior.

17.6.5 Friend names declared within a class template [temp.inject]

Friend classes or functions can be declared within a class template.
When a template is instantiated, the names of its friends are treated as if the specialization had been explicitly declared at its point of instantiation.
As with non-template classes, the names of namespace-scope friend functions of a class template specialization are not visible during an ordinary lookup unless explicitly declared at namespace scope ([class.friend]).
Such names may be found under the rules for associated classes ([basic.lookup.argdep]).140
[Example
:
template<typename T> struct number {
  number(int);
  friend number gcd(number x, number y) { return 0; };
};

void g() {
  number<double> a(3), b(4);
  a = gcd(a,b);     // finds gcd because number<double> is an associated class,
                    // making gcd visible in its namespace (global scope)
  b = gcd(3,4);     // ill-formed; gcd is not visible
}
end example
]
Friend declarations do not introduce new names into any scope, either when the template is declared or when it is instantiated.

17.7 Template instantiation and specialization [temp.spec]

The act of instantiating a function, a class, a member of a class template or a member template is referred to as template instantiation.
A function instantiated from a function template is called an instantiated function.
A class instantiated from a class template is called an instantiated class.
A member function, a member class, a member enumeration, or a static data member of a class template instantiated from the member definition of the class template is called, respectively, an instantiated member function, member class, member enumeration, or static data member.
A member function instantiated from a member function template is called an instantiated member function.
A member class instantiated from a member class template is called an instantiated member class.
An explicit specialization may be declared for a function template, a class template, a member of a class template or a member template.
An explicit specialization declaration is introduced by template<>.
In an explicit specialization declaration for a class template, a member of a class template or a class member template, the name of the class that is explicitly specialized shall be a simple-template-id.
In the explicit specialization declaration for a function template or a member function template, the name of the function or member function explicitly specialized may be a template-id.
[Example
:
template<class T = int> struct A {
  static int x;
};
template<class U> void g(U) { }

template<> struct A<double> { };        // specialize for T == double
template<> struct A<> { };              // specialize for T == int
template<> void g(char) { }             // specialize for U == char
                                        // U is deduced from the parameter type
template<> void g<int>(int) { }         // specialize for U == int
template<> int A<char>::x = 0;          // specialize for T == char

template<class T = int> struct B {
  static int x;
};
template<> int B<>::x = 1;              // specialize for T == int
end example
]
An instantiated template specialization can be either implicitly instantiated ([temp.inst]) for a given argument list or be explicitly instantiated ([temp.explicit]).
A specialization is a class, function, or class member that is either instantiated or explicitly specialized ([temp.expl.spec]).
For a given template and a given set of template-arguments,
  • an explicit instantiation definition shall appear at most once in a program,
  • an explicit specialization shall be defined at most once in a program (according to [basic.def.odr]), and
  • both an explicit instantiation and a declaration of an explicit specialization shall not appear in a program unless the explicit instantiation follows a declaration of the explicit specialization.
An implementation is not required to diagnose a violation of this rule.
Each class template specialization instantiated from a template has its own copy of any static members.
[Example
:
template<class T> class X {
  static T s;
};
template<class T> T X<T>::s = 0;
X<int> aa;
X<char*> bb;
X<int> has a static member s of type int and X<char*> has a static member s of type char*.
end example
]
If a function declaration acquired its function type through a dependent type ([temp.dep.type]) without using the syntactic form of a function declarator, the program is ill-formed.
[Example
:
template<class T> struct A {
  static T t;
};
typedef int function();
A<function> a;      // ill-formed: would declare A<function>​::​t as a static member function
end example
]

17.7.1 Implicit instantiation [temp.inst]

Unless a class template specialization has been explicitly instantiated ([temp.explicit]) or explicitly specialized ([temp.expl.spec]), the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type or when the completeness of the class type affects the semantics of the program.
[Note
:
In particular, if the semantics of an expression depend on the member or base class lists of a class template specialization, the class template specialization is implicitly generated.
For instance, deleting a pointer to class type depends on whether or not the class declares a destructor, and a conversion between pointers to class type depends on the inheritance relationship between the two classes involved.
end note
]
[Example
:
template<class T> class B { /* ... */ };
template<class T> class D : public B<T> { /* ... */ };

void f(void*);
void f(B<int>*);

void g(D<int>* p, D<char>* pp, D<double>* ppp) {
  f(p);             // instantiation of D<int> required: call f(B<int>*)
  B<char>* q = pp;  // instantiation of D<char> required: convert D<char>* to B<char>*
  delete ppp;       // instantiation of D<double> required
}
end example
]
If a class template has been declared, but not defined, at the point of instantiation ([temp.point]), the instantiation yields an incomplete class type ([basic.types]).
[Example
:
template<class T> class X;
X<char> ch;         // error: incomplete type X<char>
end example
]
[Note
:
Within a template declaration, a local class ([class.local]) or enumeration and the members of a local class are never considered to be entities that can be separately instantiated (this includes their default arguments, noexcept-specifiers, and non-static data member initializers, if any).
As a result, the dependent names are looked up, the semantic constraints are checked, and any templates used are instantiated as part of the instantiation of the entity within which the local class or enumeration is declared.
end note
]
The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions, default arguments, or noexcept-specifiers of the class member functions, member classes, scoped member enumerations, static data members, member templates, and friends; and it causes the implicit instantiation of the definitions of unscoped member enumerations and member anonymous unions.
However, for the purpose of determining whether an instantiated redeclaration is valid according to [basic.def.odr] and [class.mem], a declaration that corresponds to a definition in the template is considered to be a definition.
[Example
:
template<class T, class U>
struct Outer {
  template<class X, class Y> struct Inner;
  template<class Y> struct Inner<T, Y>;         // #1a
  template<class Y> struct Inner<T, Y> { };     // #1b; OK: valid redeclaration of #1a
  template<class Y> struct Inner<U, Y> { };     // #2
};

Outer<int, int> outer;                          // error at #2
Outer<int, int>​::​Inner<int, Y> is redeclared at #1b.
(It is not defined but noted as being associated with a definition in Outer<T, U>.)
#2 is also a redeclaration of #1a.
It is noted as associated with a definition, so it is an invalid redeclaration of the same partial specialization.
template<typename T> struct Friendly {
  template<typename U> friend int f(U) { return sizeof(T); }
};
Friendly<char> fc;
Friendly<float> ff;                             // ill-formed: produces second definition of f(U)
end example
]
Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.
Unless a function template specialization has been explicitly instantiated or explicitly specialized, the function template specialization is implicitly instantiated when the specialization is referenced in a context that requires a function definition to exist.
A function whose declaration was instantiated from a friend function definition is implicitly instantiated when it is referenced in a context that requires a function definition to exist.
Unless a call is to a function template explicit specialization or to a member function of an explicitly specialized class template, a default argument for a function template or a member function of a class template is implicitly instantiated when the function is called in a context that requires the value of the default argument.
[Example
:
template<class T> struct Z {
  void f();
  void g();
};

void h() {
  Z<int> a;         // instantiation of class Z<int> required
  Z<char>* p;       // instantiation of class Z<char> not required
  Z<double>* q;     // instantiation of class Z<double> not required

  a.f();            // instantiation of Z<int>​::​f() required
  p->g();           // instantiation of class Z<char> required, and
                    // instantiation of Z<char>​::​g() required
}
Nothing in this example requires class Z<double>, Z<int>​::​g(), or Z<char>​::​f() to be implicitly instantiated.
end example
]
Unless a variable template specialization has been explicitly instantiated or explicitly specialized, the variable template specialization is implicitly instantiated when the specialization is used.
A default template argument for a variable template is implicitly instantiated when the variable template is referenced in a context that requires the value of the default argument.
If the function selected by overload resolution ([over.match]) can be determined without instantiating a class template definition, it is unspecified whether that instantiation actually takes place.
[Example
:
template <class T> struct S {
  operator int();
};

void f(int);
void f(S<int>&);
void f(S<float>);

void g(S<int>& sr) {
  f(sr);            // instantiation of S<int> allowed but not required
                    // instantiation of S<float> allowed but not required
};
end example
]
If a function template or a member function template specialization is used in a way that involves overload resolution, a declaration of the specialization is implicitly instantiated ([temp.over]).
An implementation shall not implicitly instantiate a function template, a variable template, a member template, a non-virtual member function, a member class, a static data member of a class template, or a substatement of a constexpr if statement ([stmt.if]), unless such instantiation is required.
It is unspecified whether or not an implementation implicitly instantiates a virtual member function of a class template if the virtual member function would not otherwise be instantiated.
The use of a template specialization in a default argument shall not cause the template to be implicitly instantiated except that a class template may be instantiated where its complete type is needed to determine the correctness of the default argument.
The use of a default argument in a function call causes specializations in the default argument to be implicitly instantiated.
Implicitly instantiated class, function, and variable template specializations are placed in the namespace where the template is defined.
Implicitly instantiated specializations for members of a class template are placed in the namespace where the enclosing class template is defined.
Implicitly instantiated member templates are placed in the namespace where the enclosing class or class template is defined.
[Example
:
namespace N {
  template<class T> class List {
  public:
    T* get();
  };
}

template<class K, class V> class Map {
public:
  N::List<V> lt;
  V get(K);
};

void g(Map<const char*,int>& m) {
  int i = m.get("Nicholas");
}
a call of lt.get() from Map<const char*,int>​::​get() would place List<int>​::​get() in the namespace N rather than in the global namespace.
end example
]
If a function template f is called in a way that requires a default argument to be used, the dependent names are looked up, the semantics constraints are checked, and the instantiation of any template used in the default argument is done as if the default argument had been an initializer used in a function template specialization with the same scope, the same template parameters and the same access as that of the function template f used at that point, except that the scope in which a closure type is declared ([expr.prim.lambda.closure]) – and therefore its associated namespaces – remain as determined from the context of the definition for the default argument.
This analysis is called default argument instantiation.
The instantiated default argument is then used as the argument of f.
Each default argument is instantiated independently.
[Example
:
template<class T> void f(T x, T y = ydef(T()), T z = zdef(T()));

class  A { };

A zdef(A);

void g(A a, A b, A c) {
  f(a, b, c);       // no default argument instantiation
  f(a, b);          // default argument z = zdef(T()) instantiated
  f(a);             // ill-formed; ydef is not declared
}
end example
]
The noexcept-specifier of a function template specialization is not instantiated along with the function declaration; it is instantiated when needed ([except.spec]).
If such an noexcept-specifier is needed but has not yet been instantiated, the dependent names are looked up, the semantics constraints are checked, and the instantiation of any template used in the noexcept-specifier is done as if it were being done as part of instantiating the declaration of the specialization at that point.
[Note
:
[temp.point] defines the point of instantiation of a template specialization.
end note
]
There is an implementation-defined quantity that specifies the limit on the total depth of recursive instantiations ([implimits]), which could involve more than one template.
The result of an infinite recursion in instantiation is undefined.
[Example
:
template<class T> class X {
  X<T>* p;          // OK
  X<T*> a;          // implicit generation of X<T> requires
                    // the implicit instantiation of X<T*> which requires
                    // the implicit instantiation of X<T**> which …
};
end example
]

17.7.2 Explicit instantiation [temp.explicit]

A class, function, variable, or member template specialization can be explicitly instantiated from its template.
A member function, member class or static data member of a class template can be explicitly instantiated from the member definition associated with its class template.
An explicit instantiation of a function template or member function of a class template shall not use the inline or constexpr specifiers.
The syntax for explicit instantiation is:
explicit-instantiation:
	extern template declaration
There are two forms of explicit instantiation: an explicit instantiation definition and an explicit instantiation declaration.
An explicit instantiation declaration begins with the extern keyword.
If the explicit instantiation is for a class or member class, the elaborated-type-specifier in the declaration shall include a simple-template-id.
If the explicit instantiation is for a function or member function, the unqualified-id in the declaration shall be either a template-id or, where all template arguments can be deduced, a template-name or operator-function-id.
[Note
:
The declaration may declare a qualified-id, in which case the unqualified-id of the qualified-id must be a template-id.
end note
]
If the explicit instantiation is for a member function, a member class or a static data member of a class template specialization, the name of the class template specialization in the qualified-id for the member name shall be a simple-template-id.
If the explicit instantiation is for a variable, the unqualified-id in the declaration shall be a template-id.
An explicit instantiation shall appear in an enclosing namespace of its template.
If the name declared in the explicit instantiation is an unqualified name, the explicit instantiation shall appear in the namespace where its template is declared or, if that namespace is inline ([namespace.def]), any namespace from its enclosing namespace set.
[Note
:
Regarding qualified names in declarators, see [dcl.meaning].
end note
]
[Example
:
template<class T> class Array { void mf(); };
template class Array<char>;
template void Array<int>::mf();

template<class T> void sort(Array<T>& v) { /* ... */ }
template void sort(Array<char>&);       // argument is deduced here

namespace N {
  template<class T> void f(T&) { }
}
template void N::f<int>(int&);
end example
]
A declaration of a function template, a variable template, a member function or static data member of a class template, or a member function template of a class or class template shall precede an explicit instantiation of that entity.
A definition of a class template, a member class of a class template, or a member class template of a class or class template shall precede an explicit instantiation of that entity unless the explicit instantiation is preceded by an explicit specialization of the entity with the same template arguments.
If the declaration of the explicit instantiation names an implicitly-declared special member function (Clause [special]), the program is ill-formed.
For a given set of template arguments, if an explicit instantiation of a template appears after a declaration of an explicit specialization for that template, the explicit instantiation has no effect.
Otherwise, for an explicit instantiation definition the definition of a function template, a variable template, a member function template, or a member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.
An explicit instantiation of a class, function template, or variable template specialization is placed in the namespace in which the template is defined.
An explicit instantiation for a member of a class template is placed in the namespace where the enclosing class template is defined.
An explicit instantiation for a member template is placed in the namespace where the enclosing class or class template is defined.
[Example
:
namespace N {
  template<class T> class Y { void mf() { } };
}

template class Y<int>;          // error: class template Y not visible in the global namespace

using N::Y;
template class Y<int>;          // error: explicit instantiation outside of the namespace of the template

template class N::Y<char*>;             // OK: explicit instantiation in namespace N
template void N::Y<double>::mf();       // OK: explicit instantiation in namespace N
end example
]
A trailing template-argument can be left unspecified in an explicit instantiation of a function template specialization or of a member function template specialization provided it can be deduced from the type of a function parameter ([temp.deduct]).
[Example
:
template<class T> class Array { /* ... */ };
template<class T> void sort(Array<T>& v) { /* ... */ }

// instantiate sort(Array<int>&) – template-argument deduced
template void sort<>(Array<int>&);
end example
]
An explicit instantiation that names a class template specialization is also an explicit instantiation of the same kind (declaration or definition) of each of its members (not including members inherited from base classes and members that are templates) that has not been previously explicitly specialized in the translation unit containing the explicit instantiation, except as described below.
[Note
:
In addition, it will typically be an explicit instantiation of certain implementation-dependent data about the class.
end note
]
An explicit instantiation definition that names a class template specialization explicitly instantiates the class template specialization and is an explicit instantiation definition of only those members that have been defined at the point of instantiation.
Except for inline functions and variables, declarations with types deduced from their initializer or return value ([dcl.spec.auto]), const variables of literal types, variables of reference types, and class template specializations, explicit instantiation declarations have the effect of suppressing the implicit instantiation of the entity to which they refer.
[Note
:
The intent is that an inline function that is the subject of an explicit instantiation declaration will still be implicitly instantiated when odr-used ([basic.def.odr]) so that the body can be considered for inlining, but that no out-of-line copy of the inline function would be generated in the translation unit.
end note
]
If an entity is the subject of both an explicit instantiation declaration and an explicit instantiation definition in the same translation unit, the definition shall follow the declaration.
An entity that is the subject of an explicit instantiation declaration and that is also used in a way that would otherwise cause an implicit instantiation ([temp.inst]) in the translation unit shall be the subject of an explicit instantiation definition somewhere in the program; otherwise the program is ill-formed, no diagnostic required.
[Note
:
This rule does apply to inline functions even though an explicit instantiation declaration of such an entity has no other normative effect.
This is needed to ensure that if the address of an inline function is taken in a translation unit in which the implementation chose to suppress the out-of-line body, another translation unit will supply the body.
end note
]
An explicit instantiation declaration shall not name a specialization of a template with internal linkage.
The usual access checking rules do not apply to names used to specify explicit instantiations.
[Note
:
In particular, the template arguments and names used in the function declarator (including parameter types, return types and exception specifications) may be private types or objects which would normally not be accessible and the template may be a member template or member function which would not normally be accessible.
end note
]
An explicit instantiation does not constitute a use of a default argument, so default argument instantiation is not done.
[Example
:
char* p = 0;
template<class T> T g(T x = &p) { return x; }
template int g<int>(int);       // OK even though &p isn't an int.
end example
]

17.7.3 Explicit specialization [temp.expl.spec]

An explicit specialization of any of the following:
  • function template
  • class template
  • variable template
  • member function of a class template
  • static data member of a class template
  • member class of a class template
  • member enumeration of a class template
  • member class template of a class or class template
  • member function template of a class or class template
can be declared by a declaration introduced by template<>; that is:
explicit-specialization:
	template < > declaration
[Example
:
template<class T> class stream;

template<> class stream<char> { /* ... */ };

template<class T> class Array { /* ... */ };
template<class T> void sort(Array<T>& v) { /* ... */ }

template<> void sort<char*>(Array<char*>&);
Given these declarations, stream<char> will be used as the definition of streams of chars; other streams will be handled by class template specializations instantiated from the class template.
Similarly, sort<char*> will be used as the sort function for arguments of type Array<char*>; other Array types will be sorted by functions generated from the template.
end example
]
An explicit specialization may be declared in any scope in which the corresponding primary template may be defined ([namespace.memdef], [class.mem], [temp.mem]).
A declaration of a function template, class template, or variable template being explicitly specialized shall precede the declaration of the explicit specialization.
[Note
:
A declaration, but not a definition of the template is required.
end note
]
The definition of a class or class template shall precede the declaration of an explicit specialization for a member template of the class or class template.
[Example
:
template<> class X<int> { /* ... */ };          // error: X not a template

template<class T> class X;

template<> class X<char*> { /* ... */ };        // OK: X is a template
end example
]
A member function, a member function template, a member class, a member enumeration, a member class template, a static data member, or a static data member template of a class template may be explicitly specialized for a class specialization that is implicitly instantiated; in this case, the definition of the class template shall precede the explicit specialization for the member of the class template.
If such an explicit specialization for the member of a class template names an implicitly-declared special member function (Clause [special]), the program is ill-formed.
A member of an explicitly specialized class is not implicitly instantiated from the member declaration of the class template; instead, the member of the class template specialization shall itself be explicitly defined if its definition is required.
In this case, the definition of the class template explicit specialization shall be in scope at the point at which the member is defined.
The definition of an explicitly specialized class is unrelated to the definition of a generated specialization.
That is, its members need not have the same names, types, etc.
as the members of a generated specialization.
Members of an explicitly specialized class template are defined in the same manner as members of normal classes, and not using the template<> syntax.
The same is true when defining a member of an explicitly specialized member class.
However, template<> is used in defining a member of an explicitly specialized member class template that is specialized as a class template.
[Example
:
template<class T> struct A {
  struct B { };
  template<class U> struct C { };
};

template<> struct A<int> {
  void f(int);
};

void h() {
  A<int> a;
  a.f(16);          // A<int>​::​f must be defined somewhere
}

// template<> not used for a member of an explicitly specialized class template
void A<int>::f(int) { /* ... */ }

template<> struct A<char>::B {
  void f();
};
// template<> also not used when defining a member of an explicitly specialized member class
void A<char>::B::f() { /* ... */ }

template<> template<class U> struct A<char>::C {
  void f();
};
// template<> is used when defining a member of an explicitly specialized member class template
// specialized as a class template
template<>
template<class U> void A<char>::C<U>::f() { /* ... */ }

template<> struct A<short>::B {
  void f();
};
template<> void A<short>::B::f() { /* ... */ }              // error: template<> not permitted

template<> template<class U> struct A<short>::C {
  void f();
};
template<class U> void A<short>::C<U>::f() { /* ... */ }    // error: template<> required
end example
]
If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required.
If the program does not provide a definition for an explicit specialization and either the specialization is used in a way that would cause an implicit instantiation to take place or the member is a virtual member function, the program is ill-formed, no diagnostic required.
An implicit instantiation is never generated for an explicit specialization that is declared but not defined.
[Example
:
class String { };
template<class T> class Array { /* ... */ };
template<class T> void sort(Array<T>& v) { /* ... */ }

void f(Array<String>& v) {
  sort(v);          // use primary template sort(Array<T>&), T is String
}

template<> void sort<String>(Array<String>& v);     // error: specialization after use of primary template
template<> void sort<>(Array<char*>& v);            // OK: sort<char*> not yet used
template<class T> struct A {
  enum E : T;
  enum class S : T;
};
template<> enum A<int>::E : int { eint };           // OK
template<> enum class A<int>::S : int { sint };     // OK
template<class T> enum A<T>::E : T { eT };
template<class T> enum class A<T>::S : T { sT };
template<> enum A<char>::E : char { echar };        // ill-formed, A<char>​::​E was instantiated
                                                    // when A<char> was instantiated
template<> enum class A<char>::S : char { schar };  // OK
end example
]
The placement of explicit specialization declarations for function templates, class templates, variable templates, member functions of class templates, static data members of class templates, member classes of class templates, member enumerations of class templates, member class templates of class templates, member function templates of class templates, static data member templates of class templates, member functions of member templates of class templates, member functions of member templates of non-template classes, static data member templates of non-template classes, member function templates of member classes of class templates, etc.
, and the placement of partial specialization declarations of class templates, variable templates, member class templates of non-template classes, static data member templates of non-template classes, member class templates of class templates, etc.
, can affect whether a program is well-formed according to the relative positioning of the explicit specialization declarations and their points of instantiation in the translation unit as specified above and below.
When writing a specialization, be careful about its location; or to make it compile will be such a trial as to kindle its self-immolation.
A template explicit specialization is in the scope of the namespace in which the template was defined.
[Example
:
namespace N {
  template<class T> class X { /* ... */ };
  template<class T> class Y { /* ... */ };

  template<> class X<int> { /* ... */ };        // OK: specialization in same namespace
  template<> class Y<double>;                   // forward-declare intent to specialize for double
}

template<> class N::Y<double> { /* ... */ };    // OK: specialization in enclosing namespace
template<> class N::Y<short> { /* ... */ };     // OK: specialization in enclosing namespace
end example
]
A simple-template-id that names a class template explicit specialization that has been declared but not defined can be used exactly like the names of other incompletely-defined classes ([basic.types]).
[Example
:
template<class T> class X;                      // X is a class template
template<> class X<int>;

X<int>* p;                                      // OK: pointer to declared class X<int>
X<int> x;                                       // error: object of incomplete class X<int>
end example
]
A trailing template-argument can be left unspecified in the template-id naming an explicit function template specialization provided it can be deduced from the function argument type.
[Example
:
template<class T> class Array { /* ... */ };
template<class T> void sort(Array<T>& v);

// explicit specialization for sort(Array<int>&)
// with deduced template-argument of type int
template<> void sort(Array<int>&);
end example
]
A function with the same name as a template and a type that exactly matches that of a template specialization is not an explicit specialization ([temp.fct]).
An explicit specialization of a function or variable template is inline only if it is declared with the inline specifier or defined as deleted, and independently of whether its function or variable template is inline.
[Example
:
template<class T> void f(T) { /* ... */ }
template<class T> inline T g(T) { /* ... */ }

template<> inline void f<>(int) { /* ... */ }   // OK: inline
template<> int g<>(int) { /* ... */ }           // OK: not inline
end example
]
An explicit specialization of a static data member of a template or an explicit specialization of a static data member template is a definition if the declaration includes an initializer; otherwise, it is a declaration.
[Note
:
The definition of a static data member of a template that requires default-initialization must use a braced-init-list:
template<> X Q<int>::x;                         // declaration
template<> X Q<int>::x ();                      // error: declares a function
template<> X Q<int>::x { };                     // definition
end note
]
A member or a member template of a class template may be explicitly specialized for a given implicit instantiation of the class template, even if the member or member template is defined in the class template definition.
An explicit specialization of a member or member template is specified using the syntax for explicit specialization.
[Example
:
template<class T> struct A {
  void f(T);
  template<class X1> void g1(T, X1);
  template<class X2> void g2(T, X2);
  void h(T) { }
};

// specialization
template<> void A<int>::f(int);

// out of class member template definition
template<class T> template<class X1> void A<T>::g1(T, X1) { }

// member template specialization
template<> template<class X1> void A<int>::g1(int, X1);

// member template specialization
template<> template<>
  void A<int>::g1(int, char);           // X1 deduced as char
template<> template<>
  void A<int>::g2<char>(int, char);     // X2 specified as char

// member specialization even if defined in class definition
template<> void A<int>::h(int) { }
end example
]
A member or a member template may be nested within many enclosing class templates.
In an explicit specialization for such a member, the member declaration shall be preceded by a template<> for each enclosing class template that is explicitly specialized.
[Example
:
template<class T1> class A {
  template<class T2> class B {
    void mf();
  };
};
template<> template<> class A<int>::B<double>;
template<> template<> void A<char>::B<char>::mf();
end example
]
In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well.
In such explicit specialization declaration, the keyword template followed by a template-parameter-list shall be provided instead of the template<> preceding the explicit specialization declaration of the member.
The types of the template-parameters in the template-parameter-list shall be the same as those specified in the primary template definition.
[Example
:
template <class T1> class A {
  template<class T2> class B {
    template<class T3> void mf1(T3);
    void mf2();
  };
};
template <> template <class X>
  class A<int>::B {
      template <class T> void mf1(T);
  };
template <> template <> template<class T>
  void A<int>::B<double>::mf1(T t) { }
template <class Y> template <>
  void A<Y>::B<double>::mf2() { }       // ill-formed; B<double> is specialized but
                                        // its enclosing class template A is not
end example
]
A specialization of a member function template, member class template, or static data member template of a non-specialized class template is itself a template.
An explicit specialization declaration shall not be a friend declaration.
Default function arguments shall not be specified in a declaration or a definition for one of the following explicit specializations:
  • the explicit specialization of a function template;
  • the explicit specialization of a member function template;
  • the explicit specialization of a member function of a class template where the class template specialization to which the member function specialization belongs is implicitly instantiated.
    [Note
    :
    Default function arguments may be specified in the declaration or definition of a member function of a class template specialization that is explicitly specialized.
    end note
    ]

17.8 Function template specializations [temp.fct.spec]

A function instantiated from a function template is called a function template specialization; so is an explicit specialization of a function template.
Template arguments can be explicitly specified when naming the function template specialization, deduced from the context (e.g., deduced from the function arguments in a call to the function template specialization, see [temp.deduct]), or obtained from default template arguments.
Each function template specialization instantiated from a template has its own copy of any static variable.
[Example
:
template<class T> void f(T* p) {
  static T s;
};

void g(int a, char* b) {
  f(&a);            // calls f<int>(int*)
  f(&b);            // calls f<char*>(char**)
}
Here f<int>(int*) has a static variable s of type int and f<char*>(char**) has a static variable s of type char*.
end example
]

17.8.1 Explicit template argument specification [temp.arg.explicit]

Template arguments can be specified when referring to a function template specialization by qualifying the function template name with the list of template-arguments in the same way as template-arguments are specified in uses of a class template specialization.
[Example
:
template<class T> void sort(Array<T>& v);
void f(Array<dcomplex>& cv, Array<int>& ci) {
  sort<dcomplex>(cv);                   // sort(Array<dcomplex>&)
  sort<int>(ci);                        // sort(Array<int>&)
}
and
template<class U, class V> U convert(V v);

void g(double d) {
  int i = convert<int,double>(d);       // int convert(double)
  char c = convert<char,double>(d);     // char convert(double)
}
end example
]
A template argument list may be specified when referring to a specialization of a function template
  • when a function is called,
  • when the address of a function is taken, when a function initializes a reference to function, or when a pointer to member function is formed,
  • in an explicit specialization,
  • in an explicit instantiation, or
  • in a friend declaration.
Trailing template arguments that can be deduced ([temp.deduct]) or obtained from default template-arguments may be omitted from the list of explicit template-arguments.
A trailing template parameter pack ([temp.variadic]) not otherwise deduced will be deduced to an empty sequence of template arguments.
If all of the template arguments can be deduced, they may all be omitted; in this case, the empty template argument list <> itself may also be omitted.
In contexts where deduction is done and fails, or in contexts where deduction is not done, if a template argument list is specified and it, along with any default template arguments, identifies a single function template specialization, then the template-id is an lvalue for the function template specialization.
[Example
:
template<class X, class Y> X f(Y);
template<class X, class Y, class ... Z> X g(Y);
void h() {
  int i = f<int>(5.6);          // Y is deduced to be double
  int j = f(5.6);               // ill-formed: X cannot be deduced
  f<void>(f<int, bool>);        // Y for outer f deduced to be int (*)(bool)
  f<void>(f<int>);              // ill-formed: f<int> does not denote a single function template specialization
  int k = g<int>(5.6);          // Y is deduced to be double, Z is deduced to an empty sequence
  f<void>(g<int, bool>);        // Y for outer f is deduced to be int (*)(bool),
                                // Z is deduced to an empty sequence
}
end example
]
[Note
:
An empty template argument list can be used to indicate that a given use refers to a specialization of a function template even when a non-template function ([dcl.fct]) is visible that would otherwise be used.
For example:
template <class T> int f(T);    // #1
int f(int);                     // #2
int k = f(1);                   // uses #2
int l = f<>(1);                 // uses #1
end note
]
Template arguments that are present shall be specified in the declaration order of their corresponding template-parameters.
The template argument list shall not specify more template-arguments than there are corresponding template-parameters unless one of the template-parameters is a template parameter pack.
[Example
:
template<class X, class Y, class Z> X f(Y,Z);
template<class ... Args> void f2();
void g() {
  f<int,const char*,double>("aa",3.0);
  f<int,const char*>("aa",3.0); // Z is deduced to be double
  f<int>("aa",3.0);             // Y is deduced to be const char*, and Z is deduced to be double
  f("aa",3.0);                  // error: X cannot be deduced
  f2<char, short, int, long>(); // OK
}
end example
]
Implicit conversions (Clause [conv]) will be performed on a function argument to convert it to the type of the corresponding function parameter if the parameter type contains no template-parameters that participate in template argument deduction.
[Note
:
Template parameters do not participate in template argument deduction if they are explicitly specified.
For example,
template<class T> void f(T);

class Complex {
  Complex(double);
};

void g() {
  f<Complex>(1);    // OK, means f<Complex>(Complex(1))
}
end note
]
[Note
:
Because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates.
end note
]
[Note
:
For simple function names, argument dependent lookup ([basic.lookup.argdep]) applies even when the function name is not visible within the scope of the call.
This is because the call still has the syntactic form of a function call ([basic.lookup.unqual]).
But when a function template with explicit template arguments is used, the call does not have the correct syntactic form unless there is a function template with that name visible at the point of the call.
If no such name is visible, the call is not syntactically well-formed and argument-dependent lookup does not apply.
If some such name is visible, argument dependent lookup applies and additional function templates may be found in other namespaces.
[Example
:
namespace A {
  struct B { };
  template<int X> void f(B);
}
namespace C {
  template<class T> void f(T t);
}
void g(A::B b) {
  f<3>(b);          // ill-formed: not a function call
  A::f<3>(b);       // well-formed
  C::f<3>(b);       // ill-formed; argument dependent lookup applies only to unqualified names
  using C::f;
  f<3>(b);          // well-formed because C​::​f is visible; then A​::​f is found by argument dependent lookup
}
end example
]
end note
]
Template argument deduction can extend the sequence of template arguments corresponding to a template parameter pack, even when the sequence contains explicitly specified template arguments.
[Example
:
template<class ... Types> void f(Types ... values);

void g() {
  f<int*, float*>(0, 0, 0);     // Types is deduced to the sequence int*, float*, int
}
end example
]

17.8.2 Template argument deduction [temp.deduct]

When a function template specialization is referenced, all of the template arguments shall have values.
The values can be explicitly specified or, in some cases, be deduced from the use or obtained from default template-arguments.
[Example
:
void f(Array<dcomplex>& cv, Array<int>& ci) {
  sort(cv);                     // calls sort(Array<dcomplex>&)
  sort(ci);                     // calls sort(Array<int>&)
}
and
void g(double d) {
  int i = convert<int>(d);      // calls convert<int,double>(double)
  int c = convert<char>(d);     // calls convert<char,double>(double)
}
end example
]
When an explicit template argument list is specified, the template arguments must be compatible with the template parameter list and must result in a valid function type as described below; otherwise type deduction fails.
Specifically, the following steps are performed when evaluating an explicitly specified template argument list with respect to a given function template:
  • The specified template arguments must match the template parameters in kind (i.e., type, non-type, template). There must not be more arguments than there are parameters unless at least one parameter is a template parameter pack, and there shall be an argument for each non-pack parameter. Otherwise, type deduction fails.
  • Non-type arguments must match the types of the corresponding non-type template parameters, or must be convertible to the types of the corresponding non-type parameters as specified in [temp.arg.nontype], otherwise type deduction fails.
  • The specified template argument values are substituted for the corresponding template parameters as specified below.
After this substitution is performed, the function parameter type adjustments described in [dcl.fct] are performed.
[Example
:
A parameter type of “void (const int, int[5])” becomes “void(*)(int,int*).
end example
]
[Note
:
A top-level qualifier in a function parameter declaration does not affect the function type but still affects the type of the function parameter variable within the function.
end note
]
[Example
:
template <class T> void f(T t);
template <class X> void g(const X x);
template <class Z> void h(Z, Z*);

int main() {
  // #1: function type is f(int), t is non const
  f<int>(1);

  // #2: function type is f(int), t is const
  f<const int>(1);

  // #3: function type is g(int), x is const
  g<int>(1);

  // #4: function type is g(int), x is const
  g<const int>(1);

  // #5: function type is h(int, const int*)
  h<const int>(1,0);
}
end example
]
[Note
:
f<int>(1) and f<const int>(1) call distinct functions even though both of the functions called have the same function type.
end note
]
The resulting substituted and adjusted function type is used as the type of the function template for template argument deduction.
If a template argument has not been deduced and its corresponding template parameter has a default argument, the template argument is determined by substituting the template arguments determined for preceding template parameters into the default argument.
If the substitution results in an invalid type, as described above, type deduction fails.
[Example
:
template <class T, class U = double>
void f(T t = 0, U u = 0);

void g() {
  f(1, 'c');        // f<int,char>(1,'c')
  f(1);             // f<int,double>(1,0)
  f();              // error: T cannot be deduced
  f<int>();         // f<int,double>(0,0)
  f<int,char>();    // f<int,char>(0,0)
}
end example
]
When all template arguments have been deduced or obtained from default template arguments, all uses of template parameters in the template parameter list of the template and the function type are replaced with the corresponding deduced or default argument values.
If the substitution results in an invalid type, as described above, type deduction fails.
At certain points in the template argument deduction process it is necessary to take a function type that makes use of template parameters and replace those template parameters with the corresponding template arguments.
This is done at the beginning of template argument deduction when any explicitly specified template arguments are substituted into the function type, and again at the end of template argument deduction when any template arguments that were deduced or obtained from default arguments are substituted.
The substitution occurs in all types and expressions that are used in the function type and in template parameter declarations.
The expressions include not only constant expressions such as those that appear in array bounds or as nontype template arguments but also general expressions (i.e., non-constant expressions) inside sizeof, decltype, and other contexts that allow non-constant expressions.
The substitution proceeds in lexical order and stops when a condition that causes deduction to fail is encountered.
[Note
:
The equivalent substitution in exception specifications is done only when the noexcept-specifier is instantiated, at which point a program is ill-formed if the substitution results in an invalid type or expression.
end note
]
[Example
:
template <class T> struct A { using X = typename T::X; };
template <class T> typename T::X f(typename A<T>::X);
template <class T> void f(...) { }
template <class T> auto g(typename A<T>::X) -> typename T::X;
template <class T> void g(...) { }

void h() {
  f<int>(0);        // OK, substituting return type causes deduction to fail
  g<int>(0);        // error, substituting parameter type instantiates A<int>
}
end example
]
If a substitution results in an invalid type or expression, type deduction fails.
An invalid type or expression is one that would be ill-formed, with a diagnostic required, if written using the substituted arguments.
[Note
:
If no diagnostic is required, the program is still ill-formed.
Access checking is done as part of the substitution process.
end note
]
Only invalid types and expressions in the immediate context of the function type and its template parameter types can result in a deduction failure.
[Note
:
The substitution into types and expressions can result in effects such as the instantiation of class template specializations and/or function template specializations, the generation of implicitly-defined functions, etc.
Such effects are not in the “immediate context” and can result in the program being ill-formed.
end note
]
[Example
:
struct X { };
struct Y {
  Y(X){}
};

template <class T> auto f(T t1, T t2) -> decltype(t1 + t2);     // #1
X f(Y, Y);          // #2

X x1, x2;
X x3 = f(x1, x2);   // deduction fails on #1 (cannot add X+X), calls #2
end example
]
[Note
:
Type deduction may fail for the following reasons:
  • Attempting to instantiate a pack expansion containing multiple parameter packs of differing lengths.
  • Attempting to create an array with an element type that is void, a function type, a reference type, or an abstract class type, or attempting to create an array with a size that is zero or negative.
    [Example
    :
    template <class T> int f(T[5]);
    int I = f<int>(0);
    int j = f<void>(0);             // invalid array
    
    end example
    ]
  • Attempting to use a type that is not a class or enumeration type in a qualified name.
    [Example
    :
    template <class T> int f(typename T::B*);
    int i = f<int>(0);
    end example
    ]
  • Attempting to use a type in a nested-name-specifier of a qualified-id when that type does not contain the specified member, or
    • the specified member is not a type where a type is required, or
    • the specified member is not a template where a template is required, or
    • the specified member is not a non-type where a non-type is required.
    [Example
    :
    template <int I> struct X { };
    template <template <class T> class> struct Z { };
    template <class T> void f(typename T::Y*){}
    template <class T> void g(X<T::N>*){}
    template <class T> void h(Z<T::template TT>*){}
    struct A {};
    struct B { int Y; };
    struct C {
      typedef int N;
    };
    struct D {
      typedef int TT;
    };
    
    int main() {
      // Deduction fails in each of these cases:
      f<A>(0);          // A does not contain a member Y
      f<B>(0);          // The Y member of B is not a type
      g<C>(0);          // The N member of C is not a non-type
      h<D>(0);          // The TT member of D is not a template
    }
    end example
    ]
  • Attempting to create a pointer to reference type.
  • Attempting to create a reference to void.
  • Attempting to create “pointer to member of T” when T is not a class type.
    [Example
    :
    template <class T> int f(int T::*);
    int i = f<int>(0);
    end example
    ]
  • Attempting to give an invalid type to a non-type template parameter.
    [Example
    :
    template <class T, T> struct S {};
    template <class T> int f(S<T, T()>*);
    struct X {};
    int i0 = f<X>(0);
    end example
    ]
  • Attempting to perform an invalid conversion in either a template argument expression, or an expression used in the function declaration.
    [Example
    :
    template <class T, T*> int f(int);
    int i2 = f<int,1>(0);           // can't conv 1 to int*
    
    end example
    ]
  • Attempting to create a function type in which a parameter has a type of void, or in which the return type is a function type or array type.
  • Attempting to create a function type in which a parameter type or the return type is an abstract class type ([class.abstract]).
end note
]
[Example
:
In the following example, assuming a signed char cannot represent the value 1000, a narrowing conversion ([dcl.init.list]) would be required to convert the template-argument of type int to signed char, therefore substitution fails for the second template ([temp.arg.nontype]).
template <int> int f(int);
template <signed char> int f(int);
int i1 = f<1000>(0);            // OK
int i2 = f<1>(0);               // ambiguous; not narrowing
end example
]

17.8.2.1 Deducing template arguments from a function call [temp.deduct.call]

Template argument deduction is done by comparing each function template parameter type (call it P) that contains template-parameters that participate in template argument deduction with the type of the corresponding argument of the call (call it A) as described below.
If removing references and cv-qualifiers from P gives std​::​initializer_­list<P'> or P'[N] for some P' and N and the argument is a non-empty initializer list ([dcl.init.list]), then deduction is performed instead for each element of the initializer list, taking P' as a function template parameter type and the initializer element as its argument, and in the P'[N] case, if N is a non-type template parameter, N is deduced from the length of the initializer list.
Otherwise, an initializer list argument causes the parameter to be considered a non-deduced context ([temp.deduct.type]).
[Example
:
template<class T> void f(std::initializer_list<T>);
f({1,2,3});                     // T deduced to int
f({1,"asdf"});                  // error: T deduced to both int and const char*

template<class T> void g(T);
g({1,2,3});                     // error: no argument deduced for T

template<class T, int N> void h(T const(&)[N]);
h({1,2,3});                     // T deduced to int, N deduced to 3

template<class T> void j(T const(&)[3]);
j({42});                        // T deduced to int, array bound not considered

struct Aggr { int i; int j; };
template<int N> void k(Aggr const(&)[N]);
k({1,2,3});                     // error: deduction fails, no conversion from int to Aggr
k({{1},{2},{3}});               // OK, N deduced to 3

template<int M, int N> void m(int const(&)[M][N]);
m({{1,2},{3,4}});               // M and N both deduced to 2

template<class T, int N> void n(T const(&)[N], T);
n({{1},{2},{3}},Aggr());        // OK, T is Aggr, N is 3
end example
]
For a function parameter pack that occurs at the end of the parameter-declaration-list, deduction is performed for each remaining argument of the call, taking the type P of the declarator-id of the function parameter pack as the corresponding function template parameter type.
Each deduction deduces template arguments for subsequent positions in the template parameter packs expanded by the function parameter pack.
When a function parameter pack appears in a non-deduced context ([temp.deduct.type]), the type of that parameter pack is never deduced.
[Example
:
template<class ... Types> void f(Types& ...);
template<class T1, class ... Types> void g(T1, Types ...);
template<class T1, class ... Types> void g1(Types ..., T1);

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
  g1(x, y, z);                  // error: Types is not deduced
  g1<int, int, int>(x, y, z);   // OK, no deduction occurs
}
end example
]
If P is not a reference type:
  • If A is an array type, the pointer type produced by the array-to-pointer standard conversion ([conv.array]) 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 ([conv.func]) 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.
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.
[Example
:
template<class T> int f(const T&);
int n1 = f(5);                  // calls f<int>(const int&)
const int i = 0;
int n2 = f(i);                  // calls f<int>(const int&)
template <class T> int g(volatile T&);
int n3 = g(i);                  // calls g<const int>(const volatile int&)
end example
]
A forwarding reference is an rvalue reference to a cv-unqualified template parameter that does not represent a template parameter of a class template (during class template argument deduction ([over.match.class.deduct])).
If P is a forwarding reference and the argument is an lvalue, the type “lvalue reference to A” is used in place of A for type deduction.
[Example
:
template <class T> int f(T&& heisenreference);
template <class T> int g(const T&&);
int i;
int n1 = f(i);                  // calls f<int&>(int&)
int n2 = f(0);                  // calls f<int>(int&&)
int n3 = g(i);                  // error: would call g<int>(const int&&), which
                                // would bind an rvalue reference to an lvalue

template <class T> struct A {
  template <class U>
    A(T&&, U&&, int*);          // #1: T&& is not a forwarding reference.
                                // U&& is a forwarding reference.
  A(T&&, int*);                 // #2
};

template <class T> A(T&&, int*) -> A<T>;    // #3: T&& is a forwarding reference.

int *ip;
A a{i, 0, ip};                  // error: cannot deduce from #1
A a0{0, 0, ip};                 // uses #1 to deduce A<int> and #1 to initialize
A a2{i, ip};                    // uses #3 to deduce A<int&> and #2 to initialize
end example
]
In general, the deduction process attempts to find template argument values that will make the deduced A identical to A (after the type A is transformed as described above).
However, there are three cases that allow a difference:
  • If the original P is a reference type, the deduced A (i.e., the type referred to by the reference) can be more cv-qualified than the transformed A.
  • The transformed A can be another pointer or pointer to member type that can be converted to the deduced A via a function pointer conversion ([conv.fctptr]) and/or qualification conversion ([conv.qual]).
  • 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.
These alternatives are considered only if type deduction would otherwise fail.
If they yield more than one possible deduced A, the type deduction fails.
[Note
:
If a template-parameter is not used in any of the function parameters of a function template, or is used only in a non-deduced context, its corresponding template-argument cannot be deduced from a function call and the template-argument must be explicitly specified.
end note
]
When P is a function type, function pointer 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.
[Example
:
// Only one function of an overload set matches the call so the function parameter is a deduced context.
template <class T> int f(T (*p)(T));
int g(int);
int g(char);
int i = f(g);       // calls f(int (*)(int))
end example
]
[Example
:
// Ambiguous deduction causes the second function parameter to be a non-deduced context.
template <class T> int f(T, T (*p)(T));
int g(int);
char g(char);
int i = f(1, g);    // calls f(int, int (*)(int))
end example
]
[Example
:
// The overload set contains a template, causing the second function parameter to be a non-deduced context.
template <class T> int f(T, T (*p)(T));
char g(char);
template <class T> T g(T);
int i = f(1, g);    // calls f(int, int (*)(int))
end example
]
If deduction succeeds for all parameters that contain template-parameters that participate in template argument deduction, and all template arguments are explicitly specified, deduced, or obtained from default template arguments, remaining parameters are then compared with the corresponding arguments.
For each remaining parameter P with a type that was non-dependent before substitution of any explicitly-specified template arguments, if the corresponding argument A cannot be implicitly converted to P, deduction fails.
[Note
:
Parameters with dependent types in which no template-parameters participate in template argument deduction, and parameters that became non-dependent due to substitution of explicitly-specified template arguments, will be checked during overload resolution.
end note
]
[Example
:
  template <class T> struct Z {
    typedef typename T::x xx;
  };
  template <class T> typename Z<T>::xx f(void *, T);    // #1
  template <class T> void f(int, T);                    // #2
  struct A {} a;
  int main() {
    f(1, a);        // OK, deduction fails for #1 because there is no conversion from int to void*
  }
end example
]

17.8.2.2 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 ([over.over]).
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 [temp.deduct.type].
A placeholder type ([dcl.spec.auto]) in the return type of a function template is a non-deduced context.
If template argument deduction succeeds for such a function, the return type is determined from instantiation of the function body.

17.8.2.3 Deducing conversion function template arguments [temp.deduct.conv]

Template argument deduction is done by comparing the return type of the conversion function template (call it P) with the type that is required as the result of the conversion (call it A; see [dcl.init], [over.match.conv], and [over.match.ref] for the determination of that type) as described in [temp.deduct.type].
If P is a reference type, the type referred to by P is used in place of P for type deduction and for any further references to or transformations of P in the remainder of this section.
If A is not a reference type:
  • If P is an array type, the pointer type produced by the array-to-pointer standard conversion ([conv.array]) 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 ([conv.func]) 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.
If A is a cv-qualified type, the top-level cv-qualifiers of A's type are ignored for type deduction.
If A is a reference type, the type referred to by A is used for type deduction.
In general, the deduction process attempts to find template argument values that will make the deduced A identical to A.
However, there are four 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)
  • If the original A is a function pointer type, A can be “pointer to function” even if the deduced A is “pointer to noexcept function”.
  • If the original A is a pointer to member function type, A can be “pointer to member of type function” even if the deduced A is “pointer to member of type noexcept function”.
  • The deduced A can be another pointer or pointer to member type that can be converted to A via a qualification conversion.
These alternatives are considered only if type deduction would otherwise fail.
If they yield more than one possible deduced A, the type deduction fails.
When the deduction process requires a qualification conversion for a pointer or pointer to member type as described above, the following process is used to determine the deduced template argument values:
If A is a type “pointer to ” “pointer to” T1 and P is a type “pointer to ” “pointer to” T2, then the cv-unqualified T1 and T2 are used as the types of A and P respectively for type deduction.
[Example
:
struct A {
  template <class T> operator T***();
};
A a;
const int * const * const * p1 = a;     // T is deduced as int, not const int
end example
]

17.8.2.4 Deducing template arguments during partial ordering [temp.deduct.partial]

Template argument deduction is done by comparing certain types associated with the two function templates being compared.
Two sets of types are used to determine the partial ordering.
For each of the templates involved there is the original function type and the transformed function type.
[Note
:
The creation of the transformed type is described in [temp.func.order].
end note
]
The deduction process uses the transformed type as the argument template and the original type of the other template as the parameter template.
This process is done twice for each type involved in the partial ordering comparison: once using the transformed template-1 as the argument template and template-2 as the parameter template and again using the transformed template-2 as the argument template and template-1 as the parameter template.
The types used to determine the ordering depend on the context in which the partial ordering is done:
  • In the context of a function call, the types used are those function parameter types for which the function call has arguments.141
  • In the context of a call to a conversion function, the return types of the conversion function templates are used.
  • In other contexts ([temp.func.order]) the function template's function type is used.
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.
If a particular P contains no template-parameters that participate in template argument deduction, that P is not used to determine the ordering.
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.
If both P and A were reference types (before being replaced with the type referred to above), determine which of the two types (if any) is more cv-qualified than the other; otherwise the types are considered to be equally cv-qualified for partial ordering purposes.
The result of this determination will be used below.
Remove any top-level cv-qualifiers:
  • If P is a cv-qualified type, P is replaced by the cv-unqualified version of P.
  • If A is a cv-qualified type, A is replaced by the cv-unqualified version of A.
Using the resulting types P and A, the deduction is then done as described in [temp.deduct.type].
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.
Similarly, if A was transformed from a function parameter pack, it is compared with each remaining parameter type of the parameter template.
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<class... Args>           void f(Args... args);         // #1
template<class T1, class... Args> void f(T1 a1, Args... args);  // #2
template<class T1, class T2>      void f(T1 a1, T2 a2);         // #3

f();                // calls #1
f(1, 2, 3);         // calls #2
f(1, 2);            // calls #3; non-variadic template #3 is more specialized
                    // than the variadic templates #1 and #2
end example
]
If, for a given type, deduction succeeds in both directions (i.e., the types are identical after the transformations above) and both P and A were reference types (before being replaced with the type referred to above):
  • if the type from the argument template was an lvalue reference and the type from the parameter template was not, the parameter type is not considered to be at least as specialized as the argument type; otherwise,
  • if the type from the argument template is more cv-qualified than the type from the parameter template (as described above), the parameter type is not considered to be at least as specialized as the argument type.
Function template F is at least as specialized as function template G if, for each pair of types used to determine the ordering, the type from F is at least as specialized as the type from G.
F is more specialized than G if F is at least as specialized as G and G is not at least as specialized as F.
If, after considering the above, function template F is at least as specialized as function template G and vice-versa, and if G has a trailing parameter pack for which F does not have a corresponding parameter, and if F does not have a trailing parameter pack, then F is more specialized than G.
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 <class T> T f(int);            // #1
template <class T, class U> T f(U);     // #2
void g() {
  f<int>(1);                            // calls #1
}
end example
]
[Note
:
Partial ordering of function templates containing template parameter packs is independent of the number of deduced arguments for those template parameter packs.
end note
]
[Example
:
template<class ...> struct Tuple { };
template<class ... Types> void g(Tuple<Types ...>);                 // #1
template<class T1, class ... Types> void g(Tuple<T1, Types ...>);   // #2
template<class T1, class ... Types> void g(Tuple<T1, Types& ...>);  // #3

g(Tuple<>());                   // calls #1
g(Tuple<int, float>());         // calls #2
g(Tuple<int, float&>());        // calls #3
g(Tuple<int>());                // calls #3
end example
]
Default arguments are not considered to be arguments in this context; they only become arguments after a function has been selected.

17.8.2.5 Deducing template arguments from a type [temp.deduct.type]

Template arguments can be deduced in several different contexts, but in each case a type that is specified in terms of template parameters (call it P) is compared with an actual type (call it A), and an attempt is made to find template argument values (a type for a type parameter, a value for a non-type parameter, or a template for a template parameter) that will make P, after substitution of the deduced values (call it the deduced A), compatible with A.
In some cases, the deduction is done using a single set of types P and A, in other cases, there will be a set of corresponding types P and A.
Type deduction is done independently for each P/A pair, and the deduced template argument values are then combined.
If type deduction cannot be done for any P/A pair, or if for any pair the deduction leads to more than one possible set of deduced values, or if different pairs yield different deduced values, or if any template argument remains neither deduced nor explicitly specified, template argument deduction fails.
The type of a type parameter is only deduced from an array bound if it is not otherwise deduced.
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<int>) 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.
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.
[Note
:
Under [temp.deduct.call] and [temp.deduct.partial], if P contains no template-parameters that appear in deduced contexts, no deduction is done, so P and A need not have the same form.
end note
]
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 ([over.over]), 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 ([dcl.init.list]) but the parameter does not have a type for which deduction from an initializer list is specified ([temp.deduct.call]).
    [Example
    :
    template<class T> 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-list.
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<T>​::​B<T2>, both T and T2 are non-deduced.
Likewise, if a type is specified as A<I+J>​::​X<T>, I, J, and T are non-deduced.
If a type is specified as void f(typename A<T>​::​B, A<T>), the T in A<T>​::​B is non-deduced but the T in A<T> is deduced.
end example
]
[Example
:
Here is an example in which different parameter/argument pairs produce inconsistent template argument deductions:
template<class T> 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 <class T, class U> 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);            // OK: T is int and U is float
  f(g2);            // error: T could be char or int
  f(g3);            // 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<class T> 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 <class T> struct B { };
template <class T> struct D : public B<T> {};
struct D2 : public B<int> {};
template <class T> void f(B<T>&){}
void t() {
  D<int> d;
  D2     d2;
  f(d);             // calls f(B<int>&)
  f(d2);            // calls f(B<int>&)
}
end example
]
A template type argument T, a template template argument TT or a template non-type argument i can be deduced if P and A have one of the following forms:
T
cv-list T
T*
T&
T&&
T[integer-constant]
template-name<T>  (where template-name refers to a class template)
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<i>  (where template-name refers to a class template)
TT<T>
TT<i>
TT<>
where (T) represents a parameter-type-list ([dcl.fct]) where at least one parameter type contains a T, and () represents a parameter-type-list where no parameter type contains a T.
Similarly, <T> represents template argument lists where at least one argument contains a T, <i> 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.
If P has a form that contains <T> or <i>, then each argument of the respective template argument list of P is compared with the corresponding argument 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 is a pack expansion, then the pattern of 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 .
During partial ordering ([temp.deduct.partial]), if was originally a pack expansion:
  • if P does not contain a template argument corresponding to then is ignored;
  • otherwise, if is not a pack expansion, template argument deduction fails.
[Example
:
template<class T1, class... Z> class S;                               // #1
template<class T1, class... Z> class S<T1, const Z&...> { };          // #2
template<class T1, class T2>   class S<T1, const T2&> { };            // #3
S<int, const int&> s;         // both #2 and #3 match; #3 is more specialized

template<class T, class... U>            struct A { };                // #1
template<class T1, class T2, class... U> struct A<T1, T2*, U...> { }; // #2
template<class T1, class T2>             struct A<T1, T2> { };        // #3
template struct A<int, int*>; // selects #2
end example
]
Similarly, if P has a form that contains (T), then each parameter type of the respective parameter-type-list ([dcl.fct]) of P is compared with the corresponding parameter type 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 ([temp.deduct.funcaddr]) or when deducing template arguments from a function declaration ([temp.deduct.decl]) and and are parameters of the top-level parameter-type-list of P and A, respectively, is adjusted if it is a forwarding reference ([temp.deduct.call]) and is an lvalue reference, in which case the type of is changed to be the template parameter type (i.e., T&& is changed to simply T).
[Note
:
As a result, when is T&& and is X&, the adjusted will be T, causing T to be deduced as X&.
end note
]
[Example
:
template <class T> void f(T&&);
template <> void f(int&) { }    // #1
template <> void f(int&&) { }   // #2
void g(int i) {
  f(i);                         // calls f<int&>(int&), i.e., #1
  f(0);                         // calls f<int>(int&&), i.e., #2
}
end example
]
If the parameter-declaration corresponding to is a function parameter pack, then the type of its declarator-id is compared with each remaining parameter type in the parameter-type-list of A.
Each comparison deduces template arguments for subsequent positions in the template parameter packs expanded by the function parameter pack.
During partial ordering ([temp.deduct.partial]), if was originally a function parameter pack:
  • if P does not contain a function parameter type corresponding to then is ignored;
  • otherwise, if is not a function parameter pack, template argument deduction fails.
[Example
:
template<class T, class... U> void f(T*, U...) { }  // #1
template<class T>             void f(T) { }         // #2
template void f(int*);                              // selects #1
end example
]
These forms can be used in the same way as T is for further composition of types.
[Example
:
X<int> (*)(char[6])
is of the form
template-name<T> (*)(type[i])
which is a variant of
type (*)(T)
where type is X<int> and T is char[6].
end example
]
Template arguments cannot be deduced from function arguments involving constructs other than the ones specified above.
When the value of the argument corresponding to a non-type template parameter P that is declared with a dependent type is deduced from an expression, the template parameters in the type of P are deduced from the type of the value.
[Example
:
template<long n> struct A { };

template<typename T> struct C;
template<typename T, T n> struct C<A<n>> {
  using Q = T;
};

using R = long;
using R = C<A<2>>::Q;           // OK; T was deduced to long from the
                                // template argument value in the type A<2>
end example
]
The type of N in the type T[N] is std​::​size_­t.
[Example
:
template<typename T> struct S;
template<typename T, T n> struct S<int[n]> {
  using Q = T;
};

using V = decltype(sizeof 0);
using V = S<int[42]>::Q;        // OK; T was deduced to std​::​size_­t from the type int[42]
end example
]
[Example
:
template<class T, T i> void f(int (&a)[i]);
int v[10];
void g() {
  f(v);                         // OK: T is std​::​size_­t
}
end example
]
[Note
:
Except for reference and pointer types, a major array bound is not part of a function parameter type and cannot be deduced from an argument:
template<int i> void f1(int a[10][i]);
template<int i> void f2(int a[i][20]);
template<int i> void f3(int (&a)[i][20]);

void g() {
  int v[10][20];
  f1(v);                        // OK: i deduced to be 20
  f1<20>(v);                    // OK
  f2(v);                        // error: cannot deduce template-argument i
  f2<10>(v);                    // OK
  f3(v);                        // OK: i deduced to be 10
}
end note
]
[Note
:
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 <int i> class A { /* ... */ };
template <int i> void g(A<i+1>);
template <int i> void f(A<i>, A<i+1>);
void k() {
  A<1> a1;
  A<2> a2;
  g(a1);                        // error: deduction fails for expression i+1
  g<0>(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<int i, typename T>
T deduce(typename A<T>::X x,    // T is not deduced here
         T t,                   // but T is deduced here
         typename B<i>::Y y);   // i is not deduced here
A<int> a;
B<77>  b;

int    x = deduce<77>(a.xm, 62, b.ym);
// T is deduced to be int, a.xm must be convertible to A<int>​::​X
// i is explicitly specified to be 77, b.ym must be convertible to B<77>​::​Y
end note
]
If P has a form that contains <i>, and if the type of i differs from the type of the corresponding template parameter of the template named by the enclosing simple-template-id, deduction fails.
If P has a form that contains [i], and if the type of i is not an integral type, deduction fails.142
[Example
:
template<int i> class A { /* ... */ };
template<short s> void f(A<s>);
void k1() {
  A<1> a;
  f(a);             // error: deduction fails for conversion from int to short
  f<1>(a);          // OK
}

template<const short cs> class B { };
template<short s> void g(B<s>);
void k2() {
  B<1> b;
  g(b);             // OK: cv-qualifiers are ignored on template parameter types
}
end example
]
A template-argument can be deduced from a function, pointer to function, or pointer to member function type.
[Example
:
template<class T> void f(void(*)(T,int));
template<class T> 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
]
A template type-parameter cannot be deduced from the type of a function default argument.
[Example
:
template <class T> void f(T = 5, T = 7);
void g() {
  f(1);             // OK: call f<int>(1,7)
  f();              // error: cannot deduce T
  f<int>();         // OK: call f<int>(5,7)
}
end example
]
The template-argument corresponding to a template template-parameter is deduced from the type of the template-argument of a class template specialization used in the argument list of a function call.
[Example
:
template <template <class T> class X> struct A { };
template <template <class T> class X> void f(A<X>) { }
template<class T> struct B { };
A<B> ab;
f(ab);              // calls f(A<B>)
end example
]
[Note
:
Template argument deduction involving parameter packs ([temp.variadic]) can deduce zero or more arguments for each parameter pack.
end note
]
[Example
:
template<class> struct X { };
template<class R, class ... ArgTypes> struct X<R(int, ArgTypes ...)> { };
template<class ... Types> struct Y { };
template<class T, class ... Types> struct Y<T, Types& ...> { };

template<class ... Types> int f(void (*)(Types ...));
void g(int, float);

X<int> x1;                      // uses primary template
X<int(int, float, double)> x2;  // uses partial specialization; ArgTypes contains float, double
X<int(float, int)> x3;          // uses primary template
Y<> y1;                         // use primary template; Types is empty
Y<int&, float&, double&> y2;    // uses partial specialization; T is int&, Types contains float, double
Y<int, float, double> y3;       // uses primary template; Types contains int, float, double
int fv = f(g);                  // OK; Types contains int, float
end example
]
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 nonzero.

17.8.2.6 Deducing template arguments from a function declaration [temp.deduct.decl]

In a declaration whose declarator-id refers to a specialization of a function template, template argument deduction is performed to identify the specialization to which the declaration refers.
Specifically, this is done for explicit instantiations ([temp.explicit]), explicit specializations ([temp.expl.spec]), and certain friend declarations ([temp.friend]).
This is also done to determine whether a deallocation function template specialization matches a placement operator new ([basic.stc.dynamic.deallocation], [expr.new]).
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 [expr.new].
The deduction is done as described in [temp.deduct.type].
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 ([temp.func.order]), deduction fails and, in the declaration cases, the program is ill-formed.

17.8.3 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 ([temp.deduct]) and checking of any explicit template arguments ([temp.arg]) 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 template-arguments (deduced and/or explicit) are used to synthesize the declaration of a single function template specialization which is added to the candidate functions set to be used in overload resolution.
If, for a given function template, argument deduction fails or the synthesized function template specialization would be ill-formed, 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 [over.match.best].143
[Example
:
template<class T> 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)
}
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.
end example
]
[Example
:
Here is an example involving conversions on a function argument involved in template-argument deduction:
template<class T> struct B { /* ... */ };
template<class T> struct D : public B<T> { /* ... */ };
template<class T> void f(B<T>&);

void g(B<int>& bi, D<int>& di) {
  f(bi);            // f(bi)
  f(di);            // f((B<int>&)di)
}
end example
]
[Example
:
Here is an example involving conversions on a function argument not involved in template-parameter deduction:
template<class T> void f(T*,int);       // #1
template<class T> void f(T,char);       // #2

void h(int* pi, int i, char c) {
  f(pi,i);          // #1: f<int>(pi,i)
  f(pi,c);          // #2: f<int*>(pi,c)

  f(i,c);           // #2: f<int>(i,c);
  f(i,i);           // #2: f<int>(i,char(i))
}
end example
]
Only the signature of a function template specialization is needed to enter the specialization in a set of candidate functions.
Therefore only the function template declaration is needed to resolve a call for which a template specialization is a candidate.
[Example
:
template<class T> void f(T);    // declaration

void g() {
  f("Annemarie");               // call of f<const char*>
}
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<const char*>, either implicitly or explicitly generated, is present in some translation unit.
end example
]
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.
Non-deduced arguments allow the full range of conversions.
Note also that [over.match.best] 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.

17.9 Deduction guides [temp.deduct.guide]

Deduction guides are used when a template-name appears as a type specifier for a deduced class type ([dcl.type.class.deduct]).
Deduction guides are not found by name lookup.
Instead, when performing class template argument deduction ([over.match.class.deduct]), any deduction guides declared for the class template are considered.
[Example
:
template<class T, class D = int>
struct S {
  T data;
};
template<class U>
S(U) -> S<typename U::type>;

struct A {
  using type = short;
  operator type();
};
S x{A()};           // x is of type S<short, int>
end example
]
The same restrictions apply to the parameter-declaration-clause of a deduction guide as in a function declaration ([dcl.fct]).
The simple-template-id shall name a class template specialization.
The template-name shall be the same identifier as the template-name of the simple-template-id.
A deduction-guide shall be declared in the same scope as the corresponding class template and, for a member class template, with the same access.
Two deduction guide declarations in the same translation unit for the same class template shall not have equivalent parameter-declaration-clauses.

18 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 throwing an exception in code executed in the handler's try block or in functions called from the handler's try block.
[Note
:
Within this Clause “try block” is taken to mean both try-block and function-try-block.
end note
]
A goto or switch statement shall not be used to transfer control into a try block or into a handler.
[Example
:
void f() {
  goto l1;          // ill-formed
  goto l2;          // ill-formed
  try {
    goto l1;        // OK
    goto l2;        // ill-formed
    l1: ;
  } catch (...) {
    l2: ;
    goto l1;        // ill-formed
    goto l2;        // OK
  }
}
end example
]
A goto, break, return, or continue statement can be used to transfer control out of a try block or handler.
When this happens, each variable declared in the try block will be destroyed in the context that directly contains its declaration.
[Example
:
lab:  try {
  T1 t1;
  try {
    T2 t2;
    if (condition)
      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 thrown while destroying t2 will result in executing handler 2; any exception thrown while destroying t1 will result in executing handler 1.
end example
]
A function-try-block associates a handler-seq with the ctor-initializer, if present, and the compound-statement.
An exception thrown during the execution of the compound-statement or, for constructors and destructors, during the initialization or destruction, respectively, of the class's subobjects, transfers control to a handler in a function-try-block in the same way as an exception thrown during the execution of a try-block transfers control to other handlers.
[Example
:
int f(int);
class C {
  int i;
  double d;
public:
  C(int, double);
};

C::C(int ii, double id)
try : i(f(ii)), d(id) {
    // constructor statements
} catch (...) {
    // handles exceptions thrown from the ctor-initializer and from the constructor statements
}
end example
]
In this section, “before” and “after” refer to the “sequenced before” relation ([intro.execution]).

18.1 Throwing an exception [except.throw]

Throwing an exception transfers control to a handler.
[Note
:
An exception can be thrown from one of the following contexts: throw-expressions ([expr.throw]), allocation functions ([basic.stc.dynamic.allocation]), dynamic_­cast ([expr.dynamic.cast]), typeid ([expr.typeid]), new-expressions ([expr.new]), and standard library functions ([structure.specifications]).
end note
]
An object is passed and the type of that object determines which handlers can catch it.
[Example
:
throw "Help!";
can be caught by a handler of const char* type:
try {
    // ...
} catch(const char* p) {
    // handle character string exceptions here
}
and
class Overflow {
public:
    Overflow(char,double,double);
};

void f(double x) {
    throw Overflow('+',x,3.45e107);
}
can be caught by a handler for exceptions of type Overflow:
try {
    f(1.2);
} catch(Overflow& oo) {
    // handle exceptions of type Overflow here
}
end example
]
When an exception is thrown, control is transferred to the nearest handler with a matching type ([except.handle]); “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.
Throwing an exception copy-initializes ([dcl.init], [class.copy]) a temporary object, called the exception object.
An lvalue denoting the temporary is used to initialize the variable declared in the matching handler ([except.handle]).
If the type of the exception object would be an incomplete type or a pointer to an incomplete type other than cv void the program is ill-formed.
The memory for the exception object is allocated in an unspecified way, except as noted in [basic.stc.dynamic.allocation].
If a handler exits by rethrowing, control is passed to another handler for the same exception object.
The points of potential destruction for the exception object are:
  • when an active handler for the exception exits by any means other than rethrowing, immediately after the destruction of the object (if any) declared in the exception-declaration in the handler;
  • when an object of type std​::​exception_­ptr ([propagation]) that refers to the exception object is destroyed, before the destructor of std​::​exception_­ptr returns.
Among all points of potential destruction for the exception object, there is an unspecified last one where the exception object is destroyed.
All other points happen before that last one ([intro.races]).
[Note
:
No other thread synchronization is implied in exception handling.
end note
]
The implementation may then deallocate the memory for the exception object; any such deallocation is done in an unspecified way.
[Note
:
A thrown exception does not propagate to other threads unless caught, stored, and rethrown using appropriate library functions; see [propagation] and [futures].
end note
]
When the thrown object is a class object, the constructor selected for the copy-initialization as well as the constructor selected for a copy-initialization considering the thrown object as an lvalue shall be non-deleted and accessible, even if the copy/move operation is elided ([class.copy]).
The destructor is potentially invoked ([class.dtor]).
An exception is considered caught when a handler for that exception becomes active ([except.handle]).
[Note
:
An exception can have active handlers and still be considered uncaught if it is rethrown.
end note
]
If the exception handling mechanism handling an uncaught exception ([except.uncaught]) directly invokes a function that exits via an exception, std​::​terminate is called ([except.terminate]).
[Example
:
struct C {
  C() { }
  C(const C&) {
    if (std::uncaught_exceptions()) {
      throw 0;      // throw during copy to handler's exception-declaration object ([except.handle])
    }
  }
};

int main() {
  try {
    throw C();      // calls std​::​terminate() if construction of the handler's
                    // exception-declaration object is not elided ([class.copy])
  } catch(C) { }
}
end example
]
[Note
:
Consequently, destructors should generally catch exceptions and not let them propagate.
end note
]

18.2 Constructors and destructors [except.ctor]

As control passes from the point where an exception is thrown to a handler, destructors are invoked by a process, specified in this section, called stack unwinding.
The destructor is invoked for each automatic object of class type constructed, but not yet destroyed, since the try block was entered.
If an exception is thrown during the destruction of temporaries or local variables for a return statement ([stmt.return]), the destructor for the returned object (if any) is also invoked.
The objects are destroyed in the reverse order of the completion of their construction.
[Example
:
struct A { };

struct Y { ~Y() noexcept(false) { throw 0; } };

A f() {
  try {
    A a;
    Y y;
    A b;
    return {};      // #1
  } catch (...) {
  }
  return {};        // #2
}
At #1, the returned object of type A is constructed.
Then, the local variable b is destroyed ([stmt.jump]).
Next, the local variable y is destroyed, causing stack unwinding, resulting in the destruction of the returned object, followed by the destruction of the local variable a.
Finally, the returned object is constructed again at #2.
end example
]
If the initialization or destruction of an object other than by delegating constructor is terminated by an exception, the destructor is invoked for each of the object's direct subobjects and, for a complete object, virtual base class subobjects, whose initialization has completed ([dcl.init]) and whose destructor has not yet begun execution, except that in the case of destruction, the variant members of a union-like class are not destroyed.
The subobjects are destroyed in the reverse order of the completion of their construction.
Such destruction is sequenced before entering a handler of the function-try-block of the constructor or destructor, if any.
If the compound-statement of the function-body of a delegating constructor for an object exits via an exception, the object's destructor is invoked.
Such destruction is sequenced before entering a handler of the function-try-block of a delegating constructor for that object, if any.
[Note
:
If the object was allocated by a new-expression ([expr.new]), the matching deallocation function ([basic.stc.dynamic.deallocation]), if any, is called to free the storage occupied by the object.
end note
]

18.3 Handling an exception [except.handle]

The exception-declaration in a handler describes the type(s) of exceptions that can cause that handler to be entered.
The exception-declaration shall not denote an incomplete type, an abstract class type, or an rvalue reference type.
The exception-declaration shall not denote a pointer or reference to an incomplete type, other than void*, const void*, volatile void*, or const volatile void*.
A handler of type “array of T” or function type T is adjusted to be of type “pointer to T.
A handler is a match for an exception object of type E if
  • The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or
  • the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or
  • the handler is of type cv T or const T& where T is a pointer or pointer to member type and E is a pointer or pointer to member type that can be converted to T by one or more of
  • the handler is of type cv T or const T& where T is a pointer or pointer to member type and E is std​::​nullptr_­t.
[Note
:
A throw-expression whose operand is an integer literal with value zero does not match a handler of pointer or pointer to member type.
A handler of reference to array or function type is never a match for any exception object ([expr.throw]).
end note
]
[Example
:
class Matherr { /* ... */ virtual void vf(); };
class Overflow: public Matherr { /* ... */ };
class Underflow: public Matherr { /* ... */ };
class 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
]
The handlers for a try block are tried in order of appearance.
[Note
:
This makes it possible to write handlers that can never be executed, for example by placing a handler for a final derived class after a handler for a corresponding unambiguous public base class.
end note
]
A ... in a handler's exception-declaration functions similarly to ... in a function parameter declaration; it specifies a match for any exception.
If present, a ... handler shall be the last handler for its try block.
If no match is found among the handlers for a try block, the search for a matching handler continues in a dynamically surrounding try block of the same thread.
A handler is considered active when initialization is complete for the 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() is entered due to a throw.
A handler is no longer considered active when the catch clause exits.
The exception with the most recently activated handler that is still active is called the currently handled exception.
If no matching handler is found, the function std​::​terminate() is called; whether or not the stack is unwound before this call to std​::​terminate() is implementation-defined ([except.terminate]).
Referring to any non-static member or base class of an object in the handler for a function-try-block of a constructor or destructor for that object results in undefined behavior.
The scope and lifetime of the parameters of a function or constructor extend into the handlers of a function-try-block.
Exceptions thrown in destructors of objects with static storage duration or in constructors of namespace-scope objects with static storage duration are not caught by a function-try-block on the main function ([basic.start.main]).
Exceptions thrown in destructors of objects with thread storage duration or in constructors of namespace-scope objects with thread storage duration are not caught by a function-try-block on the initial function of the thread.
If a return statement appears in a handler of the function-try-block of a constructor, the program is ill-formed.
The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor.
Otherwise, flowing off the end of the compound-statement of a handler of a function-try-block is equivalent to flowing off the end of the compound-statement of that function (see [stmt.return]).
The variable declared by the exception-declaration, of type cv T or cv T&, is initialized from the exception object, of type E, as follows:
  • if T is a base class of E, the variable is copy-initialized ([dcl.init]) from the corresponding base class subobject of the exception object;
  • otherwise, the variable is copy-initialized ([dcl.init]) from the exception object.
The lifetime of the variable ends when the handler exits, after the destruction of any automatic objects initialized within the handler.
When the handler declares an object, any changes to that object will not affect the exception object.
When the handler declares a reference to an object, any changes to the referenced object are changes to the exception object and will have effect should that object be rethrown.

18.4 Exception specifications [except.spec]

The predicate indicating whether a function cannot exit via an exception is called the exception specification of the function.
If the predicate is false, the function has a potentially-throwing exception specification, otherwise it has a non-throwing exception specification.
The exception specification is either defined implicitly, or defined explicitly by using a noexcept-specifier as a suffix of a function declarator ([dcl.fct]).
noexcept-specifier:
	noexcept ( constant-expression )
	noexcept
	throw ( )
In a noexcept-specifier, the constant-expression, if supplied, shall be a contextually converted constant expression of type bool ([expr.const]); that constant expression is the exception specification of the function type in which the noexcept-specifier appears.
A ( token that follows noexcept is part of the noexcept-specifier and does not commence an initializer ([dcl.init]).
The noexcept-specifier noexcept without a constant-expression is equivalent to the noexcept-specifier noexcept(true).
The noexcept-specifier throw() is deprecated ([depr.except.spec]), and equivalent to the noexcept-specifier noexcept(true).
If a declaration of a function does not have a noexcept-specifier, the declaration has a potentially throwing exception specification unless it is a destructor or a deallocation function or is defaulted on its first declaration, in which cases the exception specfication is as specified below and no other declaration for that function shall have a noexcept-specifier.
In an explicit instantiation ([temp.explicit]) a noexcept-specifier may be specified, but is not required.
If a noexcept-specifier is specified in an explicit instantiation directive, the exception specification shall be the same as the exception specification of all other declarations of that function.
A diagnostic is required only if the exception specifications are not the same within a single translation unit.
If a virtual function has a non-throwing exception specification, all declarations, including the definition, of any function that overrides that virtual function in any derived class shall have a non-throwing exception specification, unless the overriding function is defined as deleted.
[Example
:
struct B {
  virtual void f() noexcept;
  virtual void g();
  virtual void h() noexcept = delete;
};

struct D: B {
  void f();                     // ill-formed
  void g() noexcept;            // OK
  void h() = delete;            // OK
};
The declaration of D​::​f is ill-formed because it has a potentially-throwing exception specification, whereas B​::​f has a non-throwing exception specification.
end example
]
Whenever an exception is thrown and the search for a handler ([except.handle]) encounters the outermost block of a function with a non-throwing exception specification, the function std​::​terminate() is called ([except.terminate]).
[Note
:
An implementation shall not reject an expression merely because, when executed, it throws or might throw an exception from a function with a non-throwing exception specification.
end note
]
[Example
:
extern void f();                // potentially-throwing

void g() noexcept {
  f();                          // valid, even if f throws
  throw 42;                     // valid, effectively a call to std​::​terminate
}
The call to f is well-formed even though, when called, f might throw an exception.
end example
]
An expression e is potentially-throwing if
  • e is a function call ([expr.call]) whose postfix-expression has a function type, or a pointer-to-function type, with a potentially-throwing exception specification, or
  • e implicitly invokes a function (such as an overloaded operator, an allocation function in a new-expression, a constructor for a function argument, or a destructor if e is a full-expression ([intro.execution])) that is potentially-throwing, or
  • e is a throw-expression, or
  • e is a dynamic_­cast expression that casts to a reference type and requires a runtime check ([expr.dynamic.cast]), or
  • e is a typeid expression applied to a (possibly parenthesized) built-in unary * operator applied to a pointer to a polymorphic class type ([expr.typeid]), or
  • any of the immediate subexpressions ([intro.execution]) of e is potentially-throwing.
An implicitly-declared constructor for a class X, or a constructor without a noexcept-specifier that is defaulted on its first declaration, has a potentially-throwing exception specification if and only if any of the following constructs is potentially-throwing:
  • a constructor selected by overload resolution in the implicit definition of the constructor for class X to initialize a potentially constructed subobject, or
  • a subexpression of such an initialization, such as a default argument expression, or,
  • for a default constructor, a default member initializer.
[Note
:
Even though destructors for fully-constructed subobjects are invoked when an exception is thrown during the execution of a constructor ([except.ctor]), their exception specifications do not contribute to the exception specification of the constructor, because an exception thrown from such a destructor would call std​::​terminate rather than escape the constructor ([except.throw], [except.terminate]).
end note
]
The exception specification for an implicitly-declared destructor, or a destructor without a noexcept-specifier, is potentially-throwing if and only if any of the destructors for any of its potentially constructed subojects is potentially throwing.
The exception specification for an implicitly-declared assignment operator, or an assignment-operator without a noexcept-specifier that is defaulted on its first declaration, is potentially-throwing if and only if the invocation of any assignment operator in the implicit definition is potentially-throwing.
A deallocation function ([basic.stc.dynamic.deallocation]) with no explicit noexcept-specifier has a non-throwing exception specification.
[Example
:
struct A {
  A(int = (A(5), 0)) noexcept;
  A(const A&) noexcept;
  A(A&&) noexcept;
  ~A();
};
struct B {
  B() throw();
  B(const B&) = default;        // implicit exception specification is noexcept(true)
  B(B&&, int = (throw Y(), 0)) noexcept;
  ~B() noexcept(false);
};
int n = 7;
struct D : public A, public B {
    int * p = new int[n];
    // D​::​D() potentially-throwing, as the new operator may throw bad_­alloc or bad_­array_­new_­length
    // D​::​D(const D&) non-throwing
    // D​::​D(D&&) potentially-throwing, as the default argument for B's constructor may throw
    // D​::​ D() potentially-throwing
};
Furthermore, if A​::​~A() were virtual, the program would be ill-formed since a function that overrides a virtual function from a base class shall not have a potentially-throwing exception specification if the base class function has a non-throwing exception specification.
end example
]
An exception specification is considered to be needed when:
  • in an expression, the function is the unique lookup result or the selected member of a set of overloaded functions ([basic.lookup], [over.match], [over.over]);
  • the function is odr-used ([basic.def.odr]) or, if it appears in an unevaluated operand, would be odr-used if the expression were potentially-evaluated;
  • the exception specification is compared to that of another declaration (e.g., an explicit specialization or an overriding virtual function);
  • the function is defined; or
  • the exception specification is needed for a defaulted special member function that calls the function.
    [Note
    :
    A defaulted declaration does not require the exception specification of a base member function to be evaluated until the implicit exception specification of the derived function is needed, but an explicit noexcept-specifier needs the implicit exception specification to compare against.
    end note
    ]
The exception specification of a defaulted special member function is evaluated as described above only when needed; similarly, the noexcept-specifier of a specialization of a function template or member function of a class template is instantiated only when needed.

18.5 Special functions [except.special]

The function std​::​terminate() ([except.terminate]) is used by the exception handling mechanism for coping with errors related to the exception handling mechanism itself.
The function std​::​current_­exception() ([propagation]) and the class std​::​nested_­exception ([except.nested]) can be used by a program to capture the currently handled exception.

18.5.1 The std​::​terminate() function [except.terminate]

In some situations exception handling must be abandoned for less subtle error handling techniques.
[Note
:
These situations are:
end note
]
In such cases, std​::​terminate() is called ([exception.terminate]).
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 ([except.handle]) encounters the outermost block of a function with a non-throwing exception specification ([except.spec]), 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().

18.5.2 The std​::​uncaught_­exceptions() function [except.uncaught]

An exception is considered uncaught after completing the initialization of the exception object ([except.throw]) until completing the activation of a handler for the exception ([except.handle]).
This includes stack unwinding.
If an exception is rethrown ([expr.throw], [propagation]), it is considered uncaught from the point of rethrow until the rethrown exception is caught.
The function std​::​uncaught_­exceptions() ([uncaught.exceptions]) returns the number of uncaught exceptions in the current thread.

19 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 new-line character that follows the first token in the sequence.144
A new-line character ends the preprocessing directive even if it occurs within what would otherwise be an invocation of a function-like macro.
A text line shall not begin with a # preprocessing token.
A conditionally-supported-directive shall not begin with any of the directive names appearing in the syntax.
A conditionally-supported-directive is conditionally-supported with implementation-defined semantics.
When in a group that is skipped ([cpp.cond]), the directive syntax is relaxed to allow any sequence of preprocessing tokens to occur between the directive name and the following new-line character.
The only white-space characters that shall appear between preprocessing tokens within a preprocessing directive (from just after the introducing # preprocessing token through just before the terminating new-line character) are space and horizontal-tab (including spaces that have replaced comments or possibly other white-space characters in translation phase 3).
The implementation can process and skip sections of source files conditionally, include other source files, and replace macros.
These capabilities are called preprocessing, because conceptually they occur before translation of the resulting translation unit.
The preprocessing tokens within a preprocessing directive are not subject to macro expansion unless otherwise stated.
[Example
:
In:
#define EMPTY
EMPTY   #   include <file.h>
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
]
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 [cpp.stringize], for example).

19.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 below145 and it may contain zero or more defined-macro-expressions and/or has-include-expressions as unary operator expressions.
A defined-macro-expression evaluates 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.
The third and fourth forms of has-include-expression are considered only if neither of the first or second forms matches, in which case the preprocessing tokens are processed just as in normal text.
The header or source file identified by the parenthesized preprocessing token sequence in each contained has-include-expression is searched for as if that preprocessing token sequence were the pp-tokens in a #include directive, except that no further macro expansion is performed.
If such a directive would not satisfy the syntactic requirements of a #include directive, the program is ill-formed.
The has-include-expression evaluates to 1 if the search for the source file succeeds, and to 0 if the search fails.
The #ifdef and #ifndef directives, and the defined conditional inclusion operator, shall treat __has_­include as if it were the name of a defined macro.
The identifier __has_­include shall not appear in any context not mentioned in this section.
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 ([lex.token]).
Preprocessing directives of the forms
# if		constant-expression new-line group
# elif		constant-expression new-line group
check whether the controlling constant expression evaluates to nonzero.
Prior to evaluation, macro invocations in the list of preprocessing tokens that will become the controlling constant expression are replaced (except for those macro names modified by the defined unary operator), just as in normal text.
If the token defined is generated as a result of this replacement process or use of the defined unary operator does not match one of the two specified forms prior to macro replacement, the behavior is undefined.
After all replacements due to macro expansion and evaluations of defined-macro-expressions and has-include-expressions have been performed, all remaining identifiers and keywords, except for true and false, are replaced with the pp-number 0, and then each preprocessing token is converted into a token.
[Note
:
An alternative token ([lex.digraph]) is not an identifier, even when its spelling consists entirely of letters and underscores.
Therefore it is not subject to this replacement.
end note
]
The resulting tokens comprise the controlling constant expression which is evaluated according to the rules of [expr.const] using arithmetic that has at least the ranges specified in [support.limits].
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 ([cstdint]).
[Note
:
Thus on an implementation where std​::​numeric_­limits<int>​::​max() is 0x7FFF and std​::​numeric_­limits<unsigned int>​::​max() is 0xFFFF, the integer literal 0x8000 is signed and positive within a #if expression even though it is unsigned in translation phase 7 ([lex.phases]).
end note
]
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.
[Note
:
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)
end note
]
Also, whether a single-character character literal may have a negative value is implementation-defined.
Each subexpression with type bool is subjected to integral promotion before processing continues.
Preprocessing directives of the forms
# ifdef		identifier new-line group
# ifndef		identifier new-line group
check whether the identifier is or is not currently defined as a macro name.
Their conditions are equivalent to #if defined identifier and #if !defined identifier respectively.
Each directive's condition is checked in order.
If it evaluates to false (zero), the group that it controls is skipped: directives are processed only through the name that determines the directive in order to keep track of the level of nested conditionals; the rest of the directives' preprocessing tokens are ignored, as are the other preprocessing tokens in the group.
Only the first group whose control condition evaluates to true (nonzero) is processed; any following groups are skipped and their controlling directives are processed as if they were in a group that is skipped.
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.146
[Example
:
This demonstrates a way to include a library optional facility only if it is available:
#if __has_include(<optional>)
#  include <optional>
#  define have_optional 1
#elif __has_include(<experimental/optional>)
#  include <experimental/optional>
#  define have_optional 1
#  define experimental_optional 1
#else
#  define have_optional 0
#endif
end example
]
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.
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.

19.2 Source file inclusion [cpp.include]

A #include directive shall identify a header or source file that can be processed by the implementation.
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.
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.
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 (i.e., 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.147 The method by which a sequence of preprocessing tokens between a < and a > preprocessing token pair or a pair of " characters is combined into a single header name preprocessing token is implementation-defined.
The implementation shall provide unique mappings for sequences consisting of one or more nondigits or digits followed by a period (.) and a single nondigit.
The first character shall not be a digit.
The implementation may ignore distinctions of alphabetical case.
A #include preprocessing directive may appear in a source file that has been read because of a #include directive in another file, up to an implementation-defined nesting limit.
[Note
:
Although an implementation may provide a mechanism for making arbitrary source files available to the < > search, in general programmers should use the < > form for headers provided with the implementation, and the " " form for sources outside the control of the implementation.
For instance:
#include <stdio.h>
#include <unistd.h>
#include "usefullib.h"
#include "myprog.h"
end note
]
[Example
:
This illustrates macro-replaced #include directives:
#if VERSION == 1
    #define INCFILE  "vers1.h"
#elif VERSION == 2
    #define INCFILE  "vers2.h"  // and so on
#else
    #define INCFILE  "versN.h"
#endif
#include INCFILE
end example
]
Note that adjacent string literals are not concatenated into a single string literal (see the translation phases in [lex.phases]); thus, an expansion that results in two string literals is an invalid directive.

19.3 Macro replacement [cpp.replace]

Two replacement lists are identical if and only if the preprocessing tokens in both have the same number, ordering, spelling, and white-space separation, where all white-space separations are considered identical.
An identifier currently defined as an object-like macro (see below) 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 (see below) may be redefined by another #define preprocessing directive provided that the second definition is a function-like macro definition that has the same number and spelling of parameters, and the two replacement lists are identical, otherwise the program is ill-formed.
There shall be white-space between the identifier and the replacement list in the definition of an object-like macro.
If the identifier-list in the macro definition does not end with an ellipsis, the number of arguments (including those arguments consisting of no preprocessing tokens) in an invocation of a function-like macro shall equal the number of parameters in the macro definition.
Otherwise, there shall be more arguments in the invocation than there are parameters in the macro definition (excluding the ...).
There shall exist a ) preprocessing token that terminates the invocation.
The identifier __VA_­ARGS__ shall occur only in the replacement-list of a function-like macro that uses the ellipsis notation in the parameters.
A parameter identifier in a function-like macro shall be uniquely declared within its scope.
The identifier immediately following the define is called the macro name.
There is one name space for macro names.
Any white-space characters preceding or following the replacement list of preprocessing tokens are not considered part of the replacement list for either form of macro.
If a # preprocessing token, followed by an identifier, occurs lexically at the point at which a preprocessing directive could begin, the identifier is not subject to macro replacement.
A preprocessing directive of the form
# define identifier replacement-list new-line
defines an object-like macro that causes each subsequent instance of the macro name148 to be replaced by the replacement list of preprocessing tokens that constitute the remainder of the directive.149
The replacement list is then rescanned for more macro names as specified below.
A preprocessing directive of the form
# define identifier lparen identifier-list ) 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.
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,150 the behavior is undefined.
If there is a ... immediately preceding the ) in the function-like 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 ...).
Since, by macro-replacement time, all character literals and string literals are preprocessing tokens, not sequences possibly containing identifier-like subsequences (see [lex.phases], translation phases), they are never scanned for macro names or parameters.
An alternative token ([lex.digraph]) 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.
A conditionally-supported-directive is a preprocessing directive regardless of whether the implementation supports it.

19.3.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.
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.

19.3.2 The # operator [cpp.stringize]

Each # preprocessing token in the replacement list for a function-like macro shall be followed by a parameter as the next preprocessing token in the replacement list.
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.

19.3.3 The ## operator [cpp.concat]

A ## preprocessing token shall not occur at the beginning or at the end of a replacement list for either form of macro definition.
If, in the replacement list of a function-like macro, a parameter is immediately preceded or followed by a ## preprocessing token, the parameter is replaced by the corresponding argument's preprocessing token sequence; however, if an argument consists of no preprocessing tokens, the parameter is replaced by a placemarker preprocessing token instead.151
For both object-like and function-like macro invocations, before the replacement list is reexamined for more macro names to replace, each instance of a ## preprocessing token in the replacement list (not from an argument) is deleted and the preceding preprocessing token is concatenated with the following preprocessing token.
Placemarker preprocessing tokens are handled specially: concatenation of two placemarkers results in a single placemarker preprocessing token, and concatenation of a placemarker with a non-placemarker preprocessing token results in the non-placemarker preprocessing token.
If the result is not a valid preprocessing token, the behavior is undefined.
The resulting token is available for further macro replacement.
The order of evaluation of ## operators is unspecified.
[Example
:
In the following fragment:
#define hash_hash # ## #
#define mkstr(a) # a
#define in_between(a) mkstr(a)
#define join(c, d) in_between(c hash_hash d)
char p[] = join(x, y);          // equivalent to char p[] = "x ## y";
The expansion produces, at various stages:
join(x, y)
in_between(x hash_hash y)
in_between(x ## y)
mkstr(x ## y)
"x ## y"
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
]
Placemarker preprocessing tokens do not appear in the syntax because they are temporary entities that exist only within translation phase 4.

19.3.4 Rescanning and further replacement [cpp.rescan]

After all parameters in the replacement list have been substituted and # and ## processing has taken place, all placemarker preprocessing tokens are removed.
Then the resulting preprocessing token sequence is rescanned, along with all subsequent preprocessing tokens of the source file, for more macro names to replace.
If the name of the macro being replaced is found during this scan of the replacement list (not including the rest of the source file's preprocessing tokens), it is not replaced.
Furthermore, if any nested replacements encounter the name of the macro being replaced, it is not replaced.
These nonreplaced macro name preprocessing tokens are no longer available for further replacement even if they are later (re)examined in contexts in which that macro name preprocessing token would otherwise have been replaced.
The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one, but all pragma unary operator expressions within it are then processed as specified in [cpp.pragma.op] below.

19.3.5 Scope of macro definitions [cpp.scope]

A macro definition lasts (independent of block structure) until a corresponding #undef directive is encountered or (if none is encountered) until the end of the translation unit.
Macro definitions have no significance after translation phase 4.
A preprocessing directive of the form
# 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.
[Example
:
The simplest use of this facility is to define a “manifest constant”, as in
#define TABSIZE 100
int table[TABSIZE];
end example
]
[Example
:
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.
end example
]
[Example
:
To illustrate the rules for redefinition and reexamination, the sequence
#define x       3
#define f(a)    f(x * (a))
#undef  x
#define x       2
#define g       f
#define z       z[0]
#define h       g(~
#define m(a)    a(w)
#define w       0,1
#define t(a)    a
#define p()     int
#define q(x)    x
#define r(x,y)  x ## y
#define str(x)  # 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", "" };
end example
]
[Example
:
To illustrate the rules for creating character string literals and concatenating tokens, the sequence
#define str(s)      # s
#define xstr(s)     str(s)
#define debug(s, t) printf("x" # s "= %d, x" # t "= %s", \
               x ## s, x ## t)
#define INCFILE(n)  vers ## n
#define glue(a, b)  a ## b
#define xglue(a, b) glue(a, b)
#define HIGHLOW     "hello"
#define LOW         LOW ", world"

debug(1, 2);
fputs(str(strncmp("abc\0d", "abc", '\4')        // this goes away
    == 0) str(: @\n), s);
#include xstr(INCFILE(2).h)
glue(HIGH, LOW);
xglue(HIGH, LOW)
results in
printf("x" "1" "= %d, x" "2" "= %s", x1, x2);
fputs("strncmp(\"abc\\0d\", \"abc\", '\\4') == 0" ": @\n", s);
#include "vers2.h"      (after macro replacement, before file access)
"hello";
"hello" ", world"
or, after concatenation of the character string literals,
printf("x1= %d, x2= %s", x1, x2);
fputs("strncmp(\"abc\\0d\", \"abc\", '\\4') == 0: @\n", s);
#include "vers2.h"      (after macro replacement, before file access)
"hello";
"hello, world"
Space around the # and ## tokens in the macro definition is optional.
end example
]
[Example
:
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, };
end example
]
[Example
:
To demonstrate the redefinition rules, the following sequence is valid.
#define OBJ_LIKE      (1-1)
#define OBJ_LIKE      /* white space */ (1-1) /* other */
#define FUNC_LIKE(a)   ( a )
#define FUNC_LIKE( a )(     /* note the white space */ \
                a /* other stuff on this line
                  */ )
But the following redefinitions are invalid:
#define OBJ_LIKE    (0)         // different token sequence
#define OBJ_LIKE    (1 - 1)     // different white space
#define FUNC_LIKE(b) ( a )      // different parameter usage
#define FUNC_LIKE(b) ( b )      // different parameter spelling
end example
]
[Example
:
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 example
]

19.4 Line control [cpp.line]

The string literal of a #line directive, if present, shall be a character string literal.
The line number of the current source line is one greater than the number of new-line characters read or introduced in translation phase 1 ([lex.phases]) while processing the source file to the current token.
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.
A preprocessing directive of the form
# line digit-sequence " s-char-sequence " 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.
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.

19.5 Error directive [cpp.error]

A preprocessing directive of the form
# error pp-tokens new-line
causes the implementation to produce a diagnostic message that includes the specified sequence of preprocessing tokens, and renders the program ill-formed.

19.6 Pragma directive [cpp.pragma]

A preprocessing directive of the form
# pragma pp-tokens 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.

19.7 Null directive [cpp.null]

A preprocessing directive of the form
# new-line
has no effect.

19.8 Predefined macro names [cpp.predefined]

The following macro names shall be defined by the implementation:
  • __cplusplus
    The integer literal 201703L.152
  • __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).153
  • __LINE__
    The presumed line number (within the current source file) of the current source line (an integer literal).154
  • __STDC_­HOSTED__
    The integer literal 1 if the implementation is a hosted implementation or the integer literal 0 if it is not.
  • __STDCPP_­DEFAULT_­NEW_­ALIGNMENT__
    An integer literal of type std​::​size_­t whose value is the alignment guaranteed by a call to operator new(std​::​size_­t) or operator new[](std​::​size_­t).
    [Note
    :
    Larger alignments will be passed to operator new(std​::​size_­t, std​::​align_­val_­t), etc.
    end note
    ]
  • __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 implementation-defined valid time shall be supplied.
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 literal 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 literal 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 literal 1, if and only if the implementation has strict pointer safety ([basic.stc.dynamic.safety]).
  • __STDCPP_­THREADS__
    Defined, and has the value integer literal 1, if and only if a program can have more than one thread of execution ([intro.multithread]).
The values of the predefined macros (except for __FILE__ and __LINE__) remain constant throughout the translation unit.
If any of the pre-defined macro names in this subclause, or the identifier defined, is the subject of a #define or a #undef preprocessing directive, the behavior is undefined.
Any other predefined macro names shall begin with a leading underscore followed by an uppercase letter or a second underscore.
It is intended that future versions of this International 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.
The presumed source file name can be changed by the #line directive.
The presumed line number can be changed by the #line directive.

19.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
]

20 Library introduction [library]

20.1 General [library.general]

This Clause describes the contents of the C++ standard library, how a well-formed C++ program makes use of the library, and how a conforming implementation may provide the entities in the library.
The following subclauses describe the definitions ([definitions]), method of description ([description]), and organization ([organization]) of the library.
Clause [requirements], Clauses [language.support] through [thread], and Annex [depr] specify the contents of the library, as well as library requirements and constraints on both well-formed C++ programs and conforming implementations.
Detailed specifications for each of the components in the library are in Clauses [language.support][thread], as shown in Table 15.
Table 15 — Library categories
Clause
Category
Language support library
Diagnostics library
General utilities library
Strings library
Localization library
Containers library
Iterators library
Algorithms library
Numerics library
Input/output library
Regular expressions library
Atomic operations library
Thread support library
The language support library (Clause [language.support]) provides components that are required by certain parts of the C++ language, such as memory allocation ([expr.new], [expr.delete]) and exception processing (Clause [except]).
The diagnostics library (Clause [diagnostics]) provides a consistent framework for reporting errors in a C++ program, including predefined exception classes.
The general utilities library (Clause [utilities]) includes components used by other library elements, such as a predefined storage allocator for dynamic storage management ([basic.stc.dynamic]), and components used as infrastructure in C++ programs, such as tuples, function wrappers, and time facilities.
The strings library (Clause [strings]) provides support for manipulating text represented as sequences of type char, sequences of type char16_­t, sequences of type char32_­t, sequences of type wchar_­t, and sequences of any other character-like type.
The localization library (Clause [localization]) provides extended internationalization support for text processing.
The containers (Clause [containers]), iterators (Clause [iterators]), and algorithms (Clause [algorithms]) libraries provide a C++ program with access to a subset of the most widely used algorithms and data structures.
The numerics library (Clause [numerics]) provides numeric algorithms and complex number components that extend support for numeric processing.
The valarray component provides support for n-at-a-time processing, potentially implemented as parallel operations on platforms that support such processing.
The random number component provides facilities for generating pseudo-random numbers.
The input/output library (Clause [input.output]) 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.
The regular expressions library (Clause [re]) provides regular expression matching and searching.
The atomic operations library (Clause [atomics]) allows more fine-grained concurrent access to shared data than is possible with locks.
The thread support library (Clause [thread]) provides components to create and manage threads, including mutual exclusion and interthread communication.

20.2 The C standard library [library.c]

The C++ standard library also makes available the facilities of the C standard library, suitably adjusted to ensure static type safety.
The descriptions of many library functions rely on the C standard library for the semantics of those functions.
In some cases, the signatures specified in this International Standard may be different from the signatures in the C standard library, and additional overloads may be declared in this International Standard, but the behavior and the preconditions (including any preconditions implied by the use of an ISO C restrict qualifier) are the same unless otherwise stated.

20.3 Definitions [definitions]

[Note
:
Clause [intro.defs] defines additional terms used elsewhere in this International Standard.
end note
]

20.3.1 arbitrary-positional stream [defns.arbitrary.stream]

a stream (described in Clause [input.output]) 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
]

20.3.2 character [defns.character]

⟨Clauses [strings], [localization], [input.output], and [re]⟩ 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
]

20.3.3 character container type [defns.character.container]

a class or a type used to represent a character
[Note
:
It is used for one of the template parameters of the string, iostream, and regular expression class templates.
A character container type is a POD ([basic.types]) type.
end note
]

20.3.4 comparison function [defns.comparison]

an operator function ([over.oper]) for any of the equality ([expr.eq]) or relational ([expr.rel]) operators

20.3.5 component [defns.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
]

20.3.6 constant subexpression [defns.const.subexpr]

an expression whose evaluation as subexpression of a conditional-expression CE ([expr.cond]) would not prevent CE from being a core constant expression ([expr.const])

20.3.7 deadlock [defns.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

20.3.8 default behavior [defns.default.behavior.impl]

⟨implementation⟩ any specific behavior provided by the implementation, within the scope of the required behavior

20.3.9 default behavior [defns.default.behavior.func]

⟨specification⟩ a description of replacement function and handler function semantics

20.3.10 direct-non-list-initialization [defns.direct-non-list-init]

a direct-initialization ([dcl.init]) that is not list-initialization ([dcl.init.list])

20.3.11 handler function [defns.handler]

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 [language.support]).
end note
]

20.3.12 iostream class templates [defns.iostream.templates]

templates, defined in Clause [input.output], 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
]

20.3.13 modifier function [defns.modifier]

a class member function ([class.mfct]) other than a constructor, assignment operator, or destructor that alters the state of an object of the class

20.3.14 move assignment [defns.move.assign]

assignment of an rvalue of some object type to a modifiable lvalue of the same type

20.3.15 move construction [defns.move.constr]

direct-initialization of an object of some type with an rvalue of the same type

20.3.16 NTCTS [defns.ntcts]

a sequence of values that have character type that precede the terminating null character type value charT()

20.3.17 observer function [defns.observer]

a class member function ([class.mfct]) 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 ([class.this]).
end note
]

20.3.18 referenceable type [defns.referenceable]

an object type, a function type that does not have cv-qualifiers or a ref-qualifier, or a reference type
[Note
:
The term describes a type to which a reference can be created, including reference types.
end note
]

20.3.19 replacement function [defns.replacement]

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 ([lex.phases]) and resolving the definitions of all translation units ([basic.link]).
end note
]

20.3.20 repositional stream [defns.repositional.stream]

a stream (described in Clause [input.output]) that can seek to a position that was previously encountered

20.3.21 required behavior [defns.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
]

20.3.22 reserved function [defns.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
]

20.3.23 stable algorithm [defns.stable]

an algorithm that preserves, as appropriate to the particular algorithm, the order of elements
[Note
:
Requirements for stable algorithms are given in [algorithm.stable].
end note
]

20.3.24 traits class [defns.traits]

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

20.3.25 valid but unspecified state [defns.valid]

a value of an object 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<int> 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
]

20.4 Method of description (Informative) [description]

This subclause describes the conventions used to specify the C++ standard library.
[structure] describes the structure of the normative Clauses [language.support] through [thread] and Annex [depr].
[conventions] describes other editorial conventions.

20.4.1 Structure of each clause [structure]

20.4.1.1 Elements [structure.elements]

Each library clause contains the following elements, as applicable:155
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.

20.4.1.2 Summary [structure.summary]

The Summary provides a synopsis of the category, and introduces the first-level subclauses.
Each subclause also provides a summary, listing the headers specified in the subclause and the library entities provided in each header.
Paragraphs labeled “Note(s):” or “Example(s):” are informative, other paragraphs are normative.
The contents of the summary and the detailed specifications include:

20.4.1.3 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
The string and iostream components use an explicit representation of operations required of template arguments.
They use a class template char_­traits to define these constraints.
Interface convention requirements are stated as generally as possible.
Instead of stating “class X has to define a member function operator++()”, the interface requires “for any object x of class X, ++x is defined”.
That is, whether the operator is a member is unspecified.
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 [algorithms]) that uses the well-defined expression requirements is described in terms of the valid expressions for its template type parameters.
Template argument requirements are sometimes referenced by name.
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.156
Although in some cases the code given is unambiguously the optimum implementation.

20.4.1.4 Detailed specifications [structure.specifications]

The detailed specifications each contain the following elements:
  • name and brief description
  • synopsis (class definition or function declaration, as appropriate)
  • restrictions on template arguments, if any
  • description of class invariants
  • description of function semantics
Descriptions of class member functions follow the order (as appropriate):157
  • constructor(s) and destructor
  • copying, moving & assignment functions
  • comparison functions
  • modifier functions
  • observer functions
  • operators and other non-member functions
Descriptions of function semantics contain the following elements (as appropriate):158
  • Requires: the preconditions for calling the function
  • Effects: the actions performed by the function
  • Synchronization: the synchronization operations ([intro.multithread]) 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
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:, Synchronization:, Postconditions:, Returns:, Throws:, Complexity:, Remarks:, and Error conditions: 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 return statements in the code sequence.
If F's semantics contains a Throws:, Postconditions:, or Complexity: element, then that supersedes any occurrences of that element in the code sequence.
For non-reserved replacement and handler functions, Clause [language.support] specifies two behaviors for the functions in question: their required and default behavior.
The default behavior describes a function definition provided by the implementation.
The required behavior describes the semantics of a function definition provided by either the implementation or a C++ program.
Where no distinction is explicitly made in the description, the behavior described is the required behavior.
If the formulation of a complexity requirement calls for a negative number of operations, the actual requirement is zero operations.159
Complexity requirements specified in the library clauses are upper bounds, and implementations that provide better complexity guarantees satisfy the requirements.
Error conditions specify conditions where a function may fail.
The conditions are listed, together with a suitable explanation, as the enum class errc constants ([syserr]).
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.
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.
This simplifies the presentation of complexity requirements in some cases.

20.4.1.5 C library [structure.see.also]

Paragraphs labeled “See also:” contain cross-references to the relevant portions of this International Standard and the ISO C standard.

20.4.2 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 ([type.descriptions]), and member functions ([functions.within.classes]).

20.4.2.1 Type descriptions [type.descriptions]

20.4.2.1.1 General [type.descriptions.general]

The Requirements subclauses may describe names that are used to specify constraints on template arguments.160
These names are used in library Clauses to describe the types that may be supplied as arguments by a C++ program when instantiating template components from the library.
Certain types defined in Clause [input.output] are used to describe implementation-defined types.
They are based on other types, but with added constraints.
Examples from [utility.requirements] include: EqualityComparable, LessThanComparable, CopyConstructible.
Examples from [iterator.requirements] include: InputIterator, ForwardIterator.

20.4.2.1.2 Exposition-only types [expos.only.types]

Several types defined in Clauses [language.support] through [thread] and Annex [depr] that are used as function parameter or return types are defined for the purpose of exposition only in order to capture their language linkage.
The declarations of such types are followed by a comment ending in exposition only.
[Example
:
namespace std {
  extern "C" using some-handler = int(int, void*, double);  // exposition only
}
The type placeholder some-handler can now be used to specify a function that takes a callback parameter with C language linkage.
end example
]

20.4.2.1.3 Enumerated types [enumerated.types]

Several types defined in Clause [input.output] are enumerated types.
Each enumerated type may be implemented as an enumeration or as a synonym for an enumeration.161
The enumerated type enumerated can be written:
enum enumerated { , , , , ..... };

inline const ();
inline const ();
inline const ();
inline const ();
  .....
Here, the names , , etc.
 represent enumerated elements for this particular enumerated type.
All such elements have distinct values.
Such as an integer type, with constant integer values ([basic.fundamental]).

20.4.2.1.4 Bitmask types [bitmask.types]

Several types defined in Clauses [language.support] through [thread] and Annex [depr] 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 ([template.bitset]).
The bitmask type bitmask can be written:
// For exposition only.
// int_­type is an integral type capable of representing all values of the bitmask type.
enum bitmask : int_type {
   = 1 << 0,  = 1 << 1,  = 1 << 2,  = 1 << 3, .....
};

inline constexpr ();
inline constexpr ();
inline constexpr ();
inline constexpr ();
  .....

constexpr bitmask operator&(bitmask X, bitmask Y) {
  return static_cast<bitmask>(
    static_cast<int_type>(X) & static_cast<int_type>(Y));
}
constexpr bitmask operator|(bitmask X, bitmask Y) {
  return static_cast<bitmask>(
    static_cast<int_type>(X) | static_cast<int_type>(Y));
}
constexpr bitmask operator^(bitmask X, bitmask Y){
  return static_cast<bitmask>(
    static_cast<int_type>(X) ^ static_cast<int_type>(Y));
}
constexpr bitmask operator~(bitmask X){
  return static_cast<bitmask>(~static_cast<int_type>(X));
}
bitmask& operator&=(bitmask& X, bitmask Y){
  X = X & Y; return X;
}
bitmask& operator|=(bitmask& X, bitmask Y) {
  X = X | Y; return X;
}
bitmask& operator^=(bitmask& X, bitmask Y) {
  X = X ^ Y; return X;
}
Here, the names , , etc.
 represent bitmask elements for this particular bitmask type.
All such elements have distinct, nonzero values such that, for any pair and where , & is nonzero and & is zero.
Additionally, the value 0 is used to represent an empty bitmask, in which no bitmask elements are set.
The following terms apply to objects and values of bitmask types:
  • To set a value Y in an object X is to evaluate the expression X |= Y.
  • To clear a value Y in an object X is to evaluate the expression X &= ~Y.
  • The value Y is set in the object X if the expression X & Y is nonzero.

20.4.2.1.5 Character sequences [character.seq]

The C standard library makes widespread use of characters and character sequences that follow a few uniform conventions:
  • A letter is any of the 26 lowercase or 26 uppercase letters in the basic execution character set.
  • The decimal-point character is the (single-byte) character used by functions that convert between a (single-byte) character sequence and a value of one of the floating-point types.
    It is used in the character sequence to denote the beginning of a fractional part.
    It is represented in Clauses [language.support] through [thread] and Annex [depr] by a period, '.', which is also its value in the "C" locale, but may change during program execution by a call to setlocale(int, const char*),162 or by a change to a locale object, as described in Clauses [locales] and [input.output].
  • A character sequence is an array object ([dcl.array]) A that can be declared as T A[N], where T is any of the types char, unsigned char, or signed char ([basic.fundamental]), optionally qualified by any combination of const or volatile.
    The initial elements of the array have defined contents up to and including an element determined by some predicate.
    A character sequence can be designated by a pointer value S that points to its first element.
declared in <clocale> ([c.locales]).

20.4.2.1.5.1 Byte strings [byte.strings]

A null-terminated byte string, or ntbs, is a character sequence whose highest-addressed element with defined content has the value zero (the terminating null character); no other element in the sequence has the value zero.
The length of an ntbs is the number of elements that precede the terminating null character.
An empty ntbs has a length of zero.
The value of an ntbs is the sequence of values of the elements up to and including the terminating null character.
A static ntbs is an ntbs with static storage duration.164
Many of the objects manipulated by function signatures declared in <cstring> ([c.strings]) are character sequences or ntbss.
The size of some of these character sequences is limited by a length value, maintained separately from the character sequence.
A string literal, such as "abc", is a static ntbs.

20.4.2.1.5.2 Multibyte strings [multibyte.strings]

A null-terminated multibyte string, or ntmbs, is an ntbs that constitutes a sequence of valid multibyte characters, beginning and ending in the initial shift state.165
A static ntmbs is an ntmbs with static storage duration.
An ntbs that contains characters only from the basic execution character set is also an ntmbs.
Each multibyte character then consists of a single byte.

20.4.2.2 Functions within classes [functions.within.classes]

For the sake of exposition, Clauses [language.support] through [thread] and Annex [depr] do not describe copy/move constructors, assignment operators, or (non-virtual) destructors with the same apparent semantics as those that can be generated by default ([class.ctor], [class.dtor], [class.copy]).
It is unspecified whether the implementation provides explicit definitions for such member function signatures, or for virtual destructors that can be generated by default.
For the sake of exposition, the library clauses sometimes annotate constructors with EXPLICIT.
Such a constructor is conditionally declared as either explicit or non-explicit ([class.conv.ctor]).
[Note
:
This is typically implemented by declaring two such constructors, of which at most one participates in overload resolution.
end note
]

20.4.2.3 Private members [objects.within.classes]

Clauses [language.support] through [thread] and Annex [depr] do not specify the representation of classes, and intentionally omit specification of class members ([class.mem]).
An implementation may define static or non-static class members, or both, as needed to implement the semantics of the member functions specified in Clauses [language.support] through [thread] and Annex [depr].
For the sake of exposition, some subclauses provide representative declarations, and semantic requirements, for private members of classes that meet the external specifications of the classes.
The declarations for such members are followed by a comment that ends with exposition only, as in:
streambuf* sb;  // exposition only
An implementation may use any technique that provides equivalent observable behavior.

20.5 Library-wide requirements [requirements]

This subclause specifies requirements that apply to the entire C++ standard library.
Clauses [language.support] through [thread] and Annex [depr] specify the requirements of individual entities within the library.
Requirements specified in terms of interactions between threads do not apply to programs having only a single thread of execution.
Within this subclause, [organization] describes the library's contents and organization, [using] describes how well-formed C++ programs gain access to library entities, [utility.requirements] describes constraints on types and functions used with the C++ standard library, [constraints] describes constraints on well-formed C++ programs, and [conforming] describes constraints on conforming implementations.

20.5.1 Library contents and organization [organization]

[contents] describes the entities and macros defined in the C++ standard library.
[headers] lists the standard library headers and some constraints on those headers.
[compliance] lists requirements for a freestanding implementation of the C++ standard library.

20.5.1.1 Library contents [contents]

The C++ standard library provides definitions for the entities and macros described in the synopses of the C++ standard library headers ([headers]).
All library entities except operator new and operator delete are defined within the namespace std or namespaces nested within namespace std.166
It is unspecified whether names declared in a specific namespace are declared directly in that namespace or in an inline namespace inside that namespace.167
Whenever a name x defined in the standard library is mentioned, the name x is assumed to be fully qualified as ​::​std​::​x, unless explicitly described otherwise.
For example, if the Effects: section for library function F is described as calling library function G, the function ​::​std​::​G is meant.
The C standard library headers (Annex [depr.c.headers]) also define names within the global namespace, while the C++ headers for C library facilities ([headers]) may also define names within the global namespace.
This gives implementers freedom to use inline namespaces to support multiple configurations of the library.

20.5.1.2 Headers [headers]

Each element of the C++ standard library is declared or defined (as appropriate) in a header.168
The C++ standard library provides the C++ library headers, shown in Table 16.
Table 16 — C++ library headers
<algorithm>
<future>
<numeric>
<strstream>
<any>
<initializer_­list>
<optional>
<system_­error>
<array>
<iomanip>
<ostream>
<thread>
<atomic>
<ios>
<queue>
<tuple>
<bitset>
<iosfwd>
<random>
<type_­traits>
<chrono>
<iostream>
<ratio>
<typeindex>
<codecvt>
<istream>
<regex>
<typeinfo>
<complex>
<iterator>
<scoped_­allocator>
<unordered_­map>
<condition_­variable>
<limits>
<set>
<unordered_­set>
<deque>
<list>
<shared_­mutex>
<utility>
<exception>
<locale>
<sstream>
<valarray>
<execution>
<map>
<stack>
<variant>
<filesystem>
<memory>
<stdexcept>
<vector>
<forward_­list>
<memory_­resource>
<streambuf>
<fstream>
<mutex>
<string>
<functional>
<new>
<string_­view>
The facilities of the C standard library are provided in the additional headers shown in Table 17.169
Table 17 — C++ headers for C library facilities
<cassert>
<cinttypes>
<csignal>
<cstdio>
<cwchar>
<ccomplex>
<ciso646>
<cstdalign>
<cstdlib>
<cwctype>
<cctype>
<climits>
<cstdarg>
<cstring>
<cerrno>
<clocale>
<cstdbool>
<ctgmath>
<cfenv>
<cmath>
<cstddef>
<ctime>
<cfloat>
<csetjmp>
<cstdint>
<cuchar>
Except as noted in Clauses [library] through [thread] and Annex [depr], the contents of each header cname is the same as that of the corresponding header name.h as specified in the C standard library (Clause [intro.refs]).
In the C++ standard library, however, the declarations (except for names which are defined as macros in C) are within namespace scope ([basic.scope.namespace]) of the namespace std.
It is unspecified whether these names (including any overloads added in Clauses [language.support] through [thread] and Annex [depr]) are first declared within the global namespace scope and are then injected into namespace std by explicit using-declarations.
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
]
Names that are defined as functions in C shall be defined as functions in the C++ standard library.170
Identifiers that are keywords or operators in C++ shall not be defined as macros in C++ standard library headers.171
[depr.c.headers], C standard library headers, describes the effects of using the name.h (C header) form in a C++ program.172
Annex K of the C standard describes a large number of functions, with associated types and macros, which “promote safer, more secure programming” than many of the traditional C library functions.
The names of the functions have a suffix of _­s; most of them provide the same service as the C library function with the unsuffixed name, but generally take an additional argument whose value is the size of the result array.
If any C++ header is included, it is implementation-defined whether any of these names is declared in the global namespace.
(None of them is declared in namespace std.)
Table 18 lists the Annex K names that may be declared in some header.
These names are also subject to the restrictions of [macro.names].
Table 18 — C standard Annex K names
abort_­handler_­s
mbstowcs_­s
strncat_­s
vswscanf_­s
asctime_­s
memcpy_­s
strncpy_­s
vwprintf_­s
bsearch_­s
memmove_­s
strtok_­s
vwscanf_­s
constraint_­handler_­t
memset_­s
swprintf_­s
wcrtomb_­s
ctime_­s
printf_­s
swscanf_­s
wcscat_­s
errno_­t
qsort_­s
tmpfile_­s
wcscpy_­s
fopen_­s
RSIZE_­MAX
TMP_­MAX_­S
wcsncat_­s
fprintf_­s
rsize_­t
tmpnam_­s
wcsncpy_­s
freopen_­s
scanf_­s
vfprintf_­s
wcsnlen_­s
fscanf_­s
set_­constraint_­handler_­s
vfscanf_­s
wcsrtombs_­s
fwprintf_­s
snprintf_­s
vfwprintf_­s
wcstok_­s
fwscanf_­s
snwprintf_­s
vfwscanf_­s
wcstombs_­s
getenv_­s
sprintf_­s
vprintf_­s
wctomb_­s
gets_­s
sscanf_­s
vscanf_­s
wmemcpy_­s
gmtime_­s
strcat_­s
vsnprintf_­s
wmemmove_­s
ignore_­handler_­s
strcpy_­s
vsnwprintf_­s
wprintf_­s
L_­tmpnam_­s
strerror_­s
vsprintf_­s
wscanf_­s
localtime_­s
strerrorlen_­s
vsscanf_­s
mbsrtowcs_­s
strlen_­s
vswprintf_­s
A header is not necessarily a source file, nor are the sequences delimited by < and > in header names necessarily valid source file names ([cpp.include]).
It is intentional that there is no C++ header for any of these C headers: <stdatomic.h>, <stdnoreturn.h>, <threads.h>.
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.
In particular, including the standard header <iso646.h> or <ciso646> has no effect.
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.

20.5.1.3 Freestanding implementations [compliance]

Two kinds of implementations are defined: hosted and freestanding ([intro.compliance]).
For a hosted implementation, this International Standard describes the set of available headers.
A freestanding implementation has an implementation-defined set of headers.
This set shall include at least the headers shown in Table 19.
Table 19 — C++ headers for freestanding implementations
Subclause
Header(s)
<ciso646>
Types
<cstddef>
Implementation properties
<cfloat> <limits> <climits>
Integer types
<cstdint>
Start and termination
<cstdlib>
Dynamic memory management
<new>
Type identification
<typeinfo>
Exception handling
<exception>
Initializer lists
<initializer_­list>
Other runtime support
<cstdarg>
Type traits
<type_­traits>
Atomics
<atomic>
Deprecated headers
<cstdalign> <cstdbool>
The supplied version of the header <cstdlib> shall declare at least the functions abort, atexit, at_­quick_­exit, exit, and quick_­exit ([support.start.term]).
The other headers listed in this table shall meet the same requirements as for a hosted implementation.

20.5.2 Using the library [using]

20.5.2.1 Overview [using.overview]

This section describes how a C++ program gains access to the facilities of the C++ standard library.
[using.headers] describes effects during translation phase 4, while [using.linkage] describes effects during phase 8 ([lex.phases]).

20.5.2.2 Headers [using.headers]

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 ([cpp.include]).
A translation unit may include library headers in any order (Clause [lex]).
Each may be included more than once, with no effect different from being included exactly once, except that the effect of including either <cassert> or <assert.h> depends each time on the lexically current definition of NDEBUG.173
A translation unit shall include a header only outside of any 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.
No diagnostic is required.
This is the same as the C standard library.

20.5.2.3 Linkage [using.linkage]

Entities in the C++ standard library have external linkage ([basic.link]).
Unless otherwise specified, objects and functions have the default extern "C++" linkage ([dcl.link]).
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.174
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 ([replacement.functions]), runtime changes ([handler.functions]).
The only reliable way to declare an object or function signature from the C standard library is by including the header that declares it, notwithstanding the latitude granted in 7.
1.
4 of the C Standard.

20.5.3 Requirements on types and expressions [utility.requirements]

[utility.arg.requirements] describes requirements on types and expressions used to instantiate templates defined in the C++ standard library.
[swappable.requirements] describes the requirements on swappable types and swappable expressions.
[nullablepointer.requirements] describes the requirements on pointer-like types that support null values.
[hash.requirements] describes the requirements on hash function objects.
[allocator.requirements] describes the requirements on storage allocators.

20.5.3.1 Template argument requirements [utility.arg.requirements]

The template definitions in the C++ standard library refer to various named requirements whose details are set out in Tables 2027.
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.
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 ([dcl.init]) if one of those signatures is called using the default argument ([dcl.fct.default]).
Table 20EqualityComparable requirements
Expression
Return type
Requirement
a == b
convertible to bool
== 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 21LessThanComparable requirements
Expression
Return type
Requirement
a < b
convertible to bool
< is a strict weak ordering relation ([alg.sorting])
Table 22DefaultConstructible requirements
Expression
Post-condition
T t;
object t is default-initialized
T u{};
object u is value-initialized or aggregate-initialized
T()
T{}
an object of type T is value-initialized or aggregate-initialized
Table 23MoveConstructible requirements
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 24CopyConstructible requirements (in addition to MoveConstructible)
Expression
Post-condition
T u = v;
the value of v is unchanged and is equivalent to u
T(v)
the value of v is unchanged and is equivalent to T(v)
Table 25MoveAssignable requirements
Expression
Return type
Return value
Post-condition
t = rv
T&
t
If t and rv do not refer to the same object, 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, whether or not t and rv refer to the same object.
The operations listed in those requirements must work as specified whether rv has been moved from or not.
end note
]
Table 26CopyAssignable requirements (in addition to MoveAssignable)
Expression
Return type
Return value
Post-condition
t = v
T&
t
t is equivalent to v, the value of v is unchanged
Table 27Destructible requirements
Expression
Post-condition
u.~T()
All resources owned by u are reclaimed, no exception is propagated.

20.5.3.2 Swappable requirements [swappable.requirements]

This subclause provides definitions for swappable types and expressions.
In these definitions, let t denote an expression of type T, and let u denote an expression of type U.
An object t is swappable with an object u if and only if:
  • the expressions swap(t, u) and swap(u, t) are valid when evaluated in the context described below, and
  • these expressions have the following effects:
    • the object referred to by t has the value originally held by u and
    • the object referred to by u has the value originally held by t.
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 ([over.match]) on a candidate set that includes:
[Note
:
If T and U are both fundamental types or arrays of fundamental types and the declarations from the header <utility> 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 <utility> to ensure an appropriate evaluation context.
end note
]
An rvalue or lvalue t is swappable if and only if t is swappable with any rvalue or lvalue, respectively, of type T.
A type X satisfying any of the iterator requirements ([iterator.requirements]) satisfies the requirements of ValueSwappable if, for any dereferenceable object x of type X, *x is swappable.
[Example
:
User code can ensure that the evaluation of swap calls is performed in an appropriate context under the various conditions as follows:
#include <utility>

// Requires: std​::​forward<T>(t) shall be swappable with std​::​forward<U>(u).
template <class T, class U>
void value_swap(T&& t, U&& u) {
  using std::swap;
  swap(std::forward<T>(t), std::forward<U>(u)); // OK: uses “swappable with” conditions
                                                // for rvalues and lvalues
}

// Requires: lvalues of T shall be swappable.
template <class T>
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);                     // OK: uses context equivalent to swappable
                                                // conditions for fundamental types
  }
  void swap(Proxy p, A& x) { swap(x, p); }      // satisfy symmetry constraint
}

int main() {
  int i = 1, j = 2;
  lv_swap(i, j);
  assert(i == 2 && j == 1);

  N::A a1 = { 5 }, a2 = { -5 };
  value_swap(a1, proxy(a2));
  assert(a1.m == -5 && a2.m == 5);
}
end example
]

20.5.3.3 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 ([swappable.requirements]),
  • the expressions shown in Table 28 are valid and have the indicated semantics, and
  • P satisfies all the other requirements of this subclause.
A value-initialized object of type P produces the null value of the type.
The null value shall be equivalent only to itself.
A default-initialized object of type P may have an indeterminate value.
[Note
:
Operations involving indeterminate values may cause undefined behavior.
end note
]
An object p of type P can be contextually converted to bool (Clause [conv]).
The effect shall be as if p != nullptr had been evaluated in place of p.
No operation which is part of the NullablePointer requirements shall exit via an exception.
In Table 28, 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 28NullablePointer requirements
Expression
Return type
Operational semantics
P u(np);
Postconditions: u == nullptr
P u = np;
P(np)
Postconditions: P(np) == nullptr
t = np
P&
Postconditions: t == nullptr
a != b
contextually convertible to bool
!(a == b)
a == np
contextually convertible to bool
a == P()
np == a
a != np
contextually convertible to bool
!(a == np)
np != a

20.5.3.4 Hash requirements [hash.requirements]

A type H meets the Hash requirements if:
Given Key is an argument type for function objects of type H, in Table 29 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.
Table 29Hash requirements
Expression
Return type
Requirement
h(k)
size_­t
The value returned shall depend only on the argument k for the duration of the program.
[Note
:
Thus all evaluations of the expression h(k) with the same value for k yield the same result for a given execution of the program.
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
]
h(u)
size_­t
Shall not modify u.

20.5.3.5 Allocator requirements [allocator.requirements]

The library describes a standard set of requirements for allocators, which are class-type objects that encapsulate the information about an allocation model.
This information includes the knowledge of pointer types, the type of their difference, the type of the size of objects in this allocation model, as well as the memory allocation and deallocation primitives for it.
All of the string types (Clause [strings]), containers (Clause [containers]) (except array), string buffers and string streams (Clause [input.output]), and match_­results (Clause [re]) are parameterized in terms of allocators.
The class template allocator_­traits ([allocator.traits]) supplies a uniform interface to all allocator types.
Table 30 describes the types manipulated through allocators.
Table 31 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 31 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 30 and 31, the use of move and forward always refers to std​::​move and std​::​forward, respectively.
Table 30 — Descriptive variable definitions
Variable
Definition
T, U, C
any cv-unqualified object type ([basic.types])
X
an Allocator class for type T
Y
the corresponding Allocator class for type U
XX
the type allocator_­traits<X>
YY
the type allocator_­traits<Y>
a, a1, a2
lvalues of type X
u
the name of a variable being declared
b
a value of type Y
c
a pointer of type C* through which indirection is valid
p
a value of type XX​::​pointer, obtained by calling a1.allocate, where a1 == a
q
a value of type XX​::​const_­pointer obtained by conversion from a value p.
w
a value of type XX​::​void_­pointer obtained by conversion from a value p
x
a value of type XX​::​const_­void_­pointer obtained by conversion from a value q or a value w
y
a value of type XX​::​const_­void_­pointer obtained by conversion from a result value of YY​::​allocate, or else a value of type (possibly const) std​::​nullptr_­t.
n
a value of type XX​::​size_­type.
Args
a template parameter pack
args
a function parameter pack with the pattern Args&&
Table 31 — Allocator requirements
Expression
Return type
Assertion/note
Default
pre-/post-condition
X​::​pointer
T*
X​::​const_­pointer
X​::​pointer is convertible to X​::​const_­pointer
pointer_­traits<X​::​​pointer>​::​​rebind<const T>
X​::​void_­pointer
Y​::​void_­pointer
X​::​pointer is convertible to X​::​void_­pointer.
X​::​void_­pointer and Y​::​void_­pointer are the same type.
pointer_­traits<X​::​​pointer>​::​​rebind<void>
X​::​const_­void_­pointer
Y​::​const_­void_­pointer
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.
pointer_­traits<X​::​​pointer>​::​​rebind<const void>
X​::​value_­type
Identical to T
X​::​size_­type
unsigned integer type
a type that can represent the size of the largest object in the allocation model.
make_­unsigned_­t<X​::​​difference_­type>
X​::​difference_­type
signed integer type
a type that can represent the difference between any two pointers in the allocation model.
pointer_­traits<X​::​​pointer>​::​​difference_­type
typename X​::​template rebind<U>​::​other
Y
For all U (including T), Y​::​template rebind<T>​::​other is X.
See Note A, below.
*p
T&
*q
const T&
*q refers to the same object as *p
p->m
type of T​::​m
Requires: (*p).m is well-defined.
equivalent to (*p).m
q->m
type of T​::​m
Requires: (*q).m is well-defined.
equivalent to (*q).m
static_­cast<​X​::​pointer​>(w)
X​::​pointer
static_­cast<X​::​pointer>(w) == p
static_­cast<​X​::​const_­pointer​>(x)
X​::​const_­pointer
static_­cast< X​::​const_­pointer​>(x) == q
pointer_­traits<​X​::​pointer​>​::​pointer_­to(r)
X​::​pointer
a.allocate(n)
X​::​pointer
Memory is allocated for n objects of type T but objects are not constructed.
allocate may throw an appropriate exception.175
[Note
:
If n == 0, the return value is unspecified.
end note
]
a.allocate(n, y)
X​::​pointer
Same as a.allocate(n).
The use of y is unspecified, but it is intended as an aid to locality.
a.allocate(n)
a.deallocate(p,n)
(not used)
Requires: p shall be a value returned by an earlier call to allocate that has not been invalidated by an intervening call to deallocate.
n shall match the value passed to allocate to obtain this memory.

Throws: Nothing.
a.max_­size()
X​::​size_­type
the largest value that can meaningfully be passed to X​::​allocate()
numeric_­limits<size_­type>​::​max() / sizeof​(value_­type)
a1 == a2
bool
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.
a1 != a2
bool
same as !(a1 == a2)
a == b
bool
same as a == Y​::​rebind<T>​::​other(b)
a != b
bool
same as !(a == b)
X u(a);
X u = a;
Shall not exit via an exception.

Postconditions: u == a
X u(b);
Shall not exit via an exception.

Postconditions: Y(u) == b, u == X(b)
X u(std​::​move(a));
X u = std​::​move(a);
Shall not exit via an exception.

Postconditions: u is equal to the prior value of a.
X u(std​::​move(b));
Shall not exit via an exception.

Postconditions: u is equal to the prior value of X(b).
a.construct(c, args)
(not used)
Effects: Constructs an object of type C at c
​::​new ((void*)c) C(forward<​Args>​(args)...)
a.destroy(c)
(not used)
Effects: Destroys the object at c
c->~C()
a.select_­on_­container_­copy_­construction()
X
Typically returns either a or X()
return a;
X​::​propagate_­on_­container_­copy_­assignment
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.
See Note B, below.
false_­type
X​::​propagate_­on_­container_­move_­assignment
Identical to or derived from true_­type or false_­type
true_­type only if an allocator of type X should be moved when the client container is move-assigned.
See Note B, below.
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 swapped when the client container is swapped.
See Note B, below.
false_­type
X​::​is_­always_­equal
Identical to or derived from true_­type or false_­type
true_­type only if the expression a1 == a2 is guaranteed to be true for any two (possibly const) values a1, a2 of type X.
is_­empty<X>​::​​type
Note A: The member class template rebind in the table above is effectively a typedef template.
[Note
:
In general, if the name Allocator is bound to SomeAllocator<T>, then Allocator​::​rebind<U>​::​other is the same type as SomeAllocator<U>, where SomeAllocator<T>​::​value_­type is T and SomeAllocator<U>​::​​value_­type is U.
end note
]
If Allocator is a class template instantiation of the form SomeAllocator<T, Args>, where Args is zero or more type arguments, and Allocator does not supply a rebind member template, the standard allocator_­traits template uses SomeAllocator<U, Args> in place of Allocator​::​​rebind<U>​::​other by default.
For allocator types that are not template instantiations of the above form, no default is provided.
Note B: If X​::​propagate_­on_­container_­copy_­assignment​::​value is true, X shall satisfy the CopyAssignable requirements (Table 26) and the copy operation shall not throw exceptions.
If X​::​propagate_­on_­container_­move_­assignment​::​value is true, X shall satisfy the MoveAssignable requirements (Table 25) and the move operation shall not throw exceptions.
If X​::​propagate_­on_­container_­swap​::​value is true, lvalues of type X shall be swappable ([swappable.requirements]) and the swap operation shall not throw exceptions.
An allocator type X shall satisfy the requirements of CopyConstructible ([utility.arg.requirements]).
The X​::​pointer, X​::​const_­pointer, X​::​void_­pointer, and X​::​const_­void_­pointer types shall satisfy the requirements of NullablePointer ([nullablepointer.requirements]).
No constructor, comparison function, copy operation, move operation, or swap operation on these pointer types shall exit via an exception.
X​::​pointer and X​::​const_­pointer shall also satisfy the requirements for a random access iterator ([random.access.iterators]) and of a contiguous iterator ([iterator.requirements.general]).
Let x1 and x2 denote objects of (possibly different) types X​::​void_­pointer, X​::​const_­void_­pointer, X​::​pointer, or X​::​const_­pointer.
Then, x1 and x2 are equivalently-valued pointer values, if and only if both x1 and x2 can be explicitly converted to the two corresponding objects px1 and px2 of type X​::​const_­pointer, using a sequence of static_­casts using only these four types, and the expression px1 == px2 evaluates to true.
Let w1 and w2 denote objects of type X​::​void_­pointer.
Then for the expressions
w1 == w2
w1 != w2
either or both objects may be replaced by an equivalently-valued object of type X​::​const_­void_­pointer with no change in semantics.
Let p1 and p2 denote objects of type X​::​pointer.
Then for the expressions
p1 == p2
p1 != p2
p1 < p2
p1 <= p2
p1 >= p2
p1 > p2
p1 - p2
either or both objects may be replaced by an equivalently-valued object of type X​::​const_­pointer with no change in semantics.
An allocator may constrain the types on which it can be instantiated and the arguments for which its construct or destroy members may be called.
If a type cannot be used with a particular allocator, the allocator class or the call to construct or destroy may fail to instantiate.
[Example
:
The following is an allocator class template supporting the minimal interface that satisfies the requirements of Table 31:
template <class Tp>
struct SimpleAllocator {
  typedef Tp value_type;
  SimpleAllocator(ctor args);

  template <class T> SimpleAllocator(const SimpleAllocator<T>& other);

  Tp* allocate(std::size_t n);
  void deallocate(Tp* p, std::size_t n);
};

template <class T, class U>
bool operator==(const SimpleAllocator<T>&, const SimpleAllocator<U>&);
template <class T, class U>
bool operator!=(const SimpleAllocator<T>&, const SimpleAllocator<U>&);
end example
]
If the alignment associated with a specific over-aligned type is not supported by an allocator, instantiation of the allocator for that type may fail.
The allocator also may silently ignore the requested alignment.
[Note
:
Additionally, the member function allocate for that type may fail by throwing an object of type bad_­alloc.
end note
]
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.

20.5.3.5.1 Allocator completeness requirements [allocator.requirements.completeness]

If X is an allocator class for type T, X additionally satisfies the allocator completeness requirements if, whether or not T is a complete type:
  • X is a complete type, and
  • all the member types of allocator_­traits<X> ([allocator.traits]) other than value_­type are complete types.

20.5.4 Constraints on programs [constraints]

20.5.4.1 Overview [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 ([namespace.std]), its use of various reserved names ([reserved.names]), its use of headers ([alt.headers]), its use of standard library classes as base classes ([derived.classes]), its definitions of replacement functions ([replacement.functions]), and its installation of handler functions during execution ([handler.functions]).

20.5.4.2 Namespace use [namespace.constraints]

20.5.4.2.1 Namespace std [namespace.std]

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified.
A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.176
The behavior of a C++ program is undefined if it declares
  • an explicit specialization of any member function of a standard library class template, or
  • an explicit specialization of any member function template of a standard library class or class template, or
  • an explicit or partial specialization of any member class template of a standard library class or class template, or
  • a deduction guide for any standard library 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.
A translation unit shall not declare namespace std to be an inline namespace ([namespace.def]).
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 this International Standard.

20.5.4.2.2 Namespace posix [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.

20.5.4.2.3 Namespaces for future standardization [namespace.future]

Top level namespaces with a name starting with std and followed by a non-empty sequence of digits are reserved for future standardization.
The behavior of a C++ program is undefined if it adds declarations or definitions to such a namespace.
[Example
:
The top level namespace std2 is reserved for use by future revisions of this International Standard.
end example
]

20.5.4.3 Reserved names [reserved.names]

The C++ standard library reserves the following kinds of names:
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.

20.5.4.3.1 Zombie names [zombie.names]

In namespace std, the following names are reserved for previous standardization:

20.5.4.3.2 Macro names [macro.names]

A translation unit that includes a standard library header shall not #define or #undef names declared in any standard library header.
A translation unit shall not #define or #undef names lexically identical to keywords, to the identifiers listed in Table 4, or to the attribute-tokens described in [dcl.attr].

20.5.4.3.3 External linkage [extern.names]

Each name declared as an object with external linkage in a header is reserved to the implementation to designate that library object with external linkage,177 both in namespace std and in the global namespace.
Each global function signature declared with external linkage in a header is reserved to the implementation to designate that function signature with external linkage.178
Each name from the C standard library declared with external linkage is reserved to the implementation for use as a name with extern "C" linkage, both in namespace std and in the global namespace.
Each function signature from the C standard library declared with external linkage is reserved to the implementation for use as a function signature with both extern "C" and extern "C++" linkage,179 or as a name of namespace scope in the global namespace.
The list of such reserved names includes errno, declared or defined in <cerrno>.
The list of such reserved function signatures with external linkage includes setjmp(jmp_­buf), declared or defined in <csetjmp>, and va_­end(va_­list), declared or defined in <cstdarg>.
The function signatures declared in <cuchar>, <cwchar>, and <cwctype> are always reserved, notwithstanding the restrictions imposed in subclause 4.
5.
1 of Amendment 1 to the C Standard for these headers.

20.5.4.3.4 Types [extern.types]

For each type T from the C standard library,180 the types ​::​T and std​::​T are reserved to the implementation and, when defined, ​::​T shall be identical to std​::​T.
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.

20.5.4.3.5 User-defined literal suffixes [usrlit.suffix]

Literal suffix identifiers ([over.literal]) that do not start with an underscore are reserved for future standardization.

20.5.4.4 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 ([cpp.include]), the behavior is undefined.

20.5.4.5 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 ([class.virtual]).

20.5.4.6 Replacement functions [replacement.functions]

Clauses [language.support] through [thread] and Annex [depr] 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 ([definitions]).
A C++ program may provide the definition for any of the following dynamic memory allocation function signatures declared in header <new> ([basic.stc.dynamic], [support.dynamic]):
operator new(std::size_t)
operator new(std::size_t, std::align_val_t)
operator new(std::size_t, const std::nothrow_t&)
operator new(std::size_t, std::align_val_t, const std::nothrow_t&)
operator delete(void*)
operator delete(void*, std::size_t)
operator delete(void*, std::align_val_t)
operator delete(void*, std::size_t, std::align_val_t)
operator delete(void*, const std::nothrow_t&)
operator delete(void*, std::align_val_t, const std::nothrow_t&)
operator new[](std::size_t)
operator new[](std::size_t, std::align_val_t)
operator new[](std::size_t, const std::nothrow_t&)
operator new[](std::size_t, std::align_val_t, const std::nothrow_t&)
operator delete[](void*)
operator delete[](void*, std::size_t)
operator delete[](void*, std::align_val_t)
operator delete[](void*, std::size_t, std::align_val_t)
operator delete[](void*, const std::nothrow_t&)
operator delete[](void*, std::align_val_t, const std::nothrow_t&)
The program's definitions are used instead of the default versions supplied by the implementation ([support.dynamic]).
Such replacement occurs prior to program startup ([basic.def.odr], [basic.start]).
The program's declarations shall not be specified as inline.
No diagnostic is required.

20.5.4.7 Handler functions [handler.functions]

The C++ standard library provides a default version of the following handler function (Clause [language.support]):
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): See also subclauses [alloc.errors], Storage allocation errors, and [support.exception], Exception handling.
A C++ program can get a pointer to the current handler function by calling the following functions:
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.

20.5.4.8 Other functions [res.on.functions]

In certain cases (replacement functions, handler functions, operations on types used to instantiate standard library template components), the C++ standard library depends on components supplied by a C++ program.
If these components do not meet their requirements, this International Standard places no requirements on the implementation.
In particular, the effects are undefined in the following cases:
  • for replacement functions ([new.delete]), if the installed replacement function does not implement the semantics of the applicable Required behavior: paragraph.
  • for handler functions ([new.handler], [terminate.handler]), 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 ([allocator.requirements], [container.requirements], [iterator.requirements], [algorithms.requirements], [numeric.requirements]).
    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 ([basic.types]) is used as a template argument when instantiating a template component, unless specifically allowed for that component.

20.5.4.9 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 ([temp.deduct.call]) 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 std​::​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
    ]

20.5.4.10 Library object access [res.on.objects]

The behavior of a program is undefined if calls to standard library functions from different threads may introduce a data race.
The conditions under which this may occur are specified in [res.on.data.races].
[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
]
If an object of a standard library type is accessed, and the beginning of the object's lifetime ([basic.life]) does not happen before the access, or the access does not happen before the end of the object's lifetime, the behavior is undefined unless otherwise specified.
[Note
:
This applies even to objects such as mutexes intended for thread synchronization.
end note
]

20.5.4.11 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.

20.5.5 Conforming implementations [conforming]

20.5.5.1 Overview [conforming.overview]

This section describes the constraints upon, and latitude of, implementations of the C++ standard library.
An implementation's use of headers is discussed in [res.on.headers], its use of macros in [res.on.macro.definitions], non-member functions in [global.functions], member functions in [member.functions], data race avoidance in [res.on.data.races], access specifiers in [protection.within.classes], class derivation in [derivation], and exceptions in [res.on.exception.handling].

20.5.5.2 Headers [res.on.headers]

A C++ header may include other C++ headers.
A C++ header shall provide the declarations and definitions that appear in its synopsis.
A C++ header shown in its synopsis as including other C++ headers shall provide the declarations and definitions that appear in the synopses of those other headers.
Certain types and macros are defined in more than one header.
Every such entity shall be defined such that any header that defines it may be included after any other header that also defines it ([basic.def.odr]).
The C standard library headers ([depr.c.headers]) shall include only their corresponding C++ standard library header, as described in [headers].

20.5.5.3 Restrictions on macro definitions [res.on.macro.definitions]

The names and global function signatures described in [contents] are reserved to the implementation.
All object-like macros defined by the C standard library and described in this Clause as expanding to integral constant expressions are also suitable for use in #if preprocessing directives, unless explicitly stated otherwise.

20.5.5.4 Non-member functions [global.functions]

It is unspecified whether any non-member functions in the C++ standard library are defined as inline ([dcl.inline]).
A call to a non-member function signature described in Clauses [language.support] through [thread] and Annex [depr] shall behave as if the implementation declared no additional non-member function signatures.181
An implementation shall not declare a non-member function signature with additional default arguments.
Unless otherwise specified, calls made by functions in the standard library to non-operator, non-member functions do not use functions from another namespace which are found through argument-dependent name lookup ([basic.lookup.argdep]).
[Note
:
The phrase “unless otherwise specified” applies to cases such as the swappable with requirements ([swappable.requirements]).
The exception for overloaded operators allows argument-dependent lookup in cases like that of ostream_­iterator​::​operator= ([ostream.iterator.ops]):
Effects:
*out_stream << value;
if (delim != 0)
  *out_stream << delim;
return *this;
end note
]
A valid C++ program always calls the expected library non-member function.
An implementation may also define additional non-member functions that would otherwise not be called by a valid C++ program.

20.5.5.5 Member functions [member.functions]

It is unspecified whether any member functions in the C++ standard library are defined as inline ([dcl.inline]).
For a non-virtual member function described in the C++ standard library, an implementation may declare a different set of member function signatures, provided that any call to the member function that would select an overload from the set of declarations described in this International Standard behaves as if that overload were selected.
[Note
:
For instance, an implementation may add parameters with default values, or replace a member function with default arguments with two or more member functions with equivalent behavior, or add additional signatures for a member function name.
end note
]

20.5.5.6 Constexpr functions and constructors [constexpr.functions]

This International Standard explicitly requires that certain standard library functions are constexpr ([dcl.constexpr]).
An implementation shall not declare any standard library function signature as constexpr except for those where it is explicitly required.
Within any header that provides any non-defining declarations of constexpr functions or constructors an implementation shall provide corresponding definitions.

20.5.5.7 Requirements for stable algorithms [algorithm.stable]

When the requirements for an algorithm state that it is “stable” without further elaboration, it means:
  • For the sort algorithms the relative order of equivalent elements is preserved.
  • For the remove and copy algorithms the relative order of the elements that are not removed is preserved.
  • For the merge algorithms, for equivalent elements in the original two ranges, the elements from the first range (preserving their original order) precede the elements from the second range (preserving their original order).

20.5.5.8 Reentrancy [reentrancy]

Except where explicitly specified in this International Standard, it is implementation-defined which functions in the C++ standard library may be recursively reentered.

20.5.5.9 Data race avoidance [res.on.data.races]

This section specifies requirements that implementations shall meet to prevent data races ([intro.multithread]).
Every standard library function shall meet each requirement unless otherwise specified.
Implementations may prevent data races in cases other than those specified below.
A C++ standard library function shall not directly or indirectly access objects ([intro.multithread]) accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function's arguments, including this.
A C++ standard library function shall not directly or indirectly modify objects ([intro.multithread]) accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function's non-const arguments, including this.
[Note
:
This means, for example, that implementations can't use a static object for internal purposes without synchronization because it could cause a data race even in programs that do not explicitly share objects between threads.
end note
]
A C++ standard library function shall not access objects indirectly accessible via its arguments or via elements of its container arguments except by invoking functions required by its specification on those container elements.
Operations on iterators obtained by calling a standard library container or string member function may access the underlying container, but shall not modify it.
[Note
:
In particular, container operations that invalidate iterators conflict with operations on iterators associated with that container.
end note
]
Implementations may share their own internal objects between threads if the objects are not visible to users and are protected against data races.
Unless otherwise specified, C++ standard library functions shall perform all operations solely within the current thread if those operations have effects that are visible ([intro.multithread]) to users.
[Note
:
This allows implementations to parallelize operations if there are no visible side effects.
end note
]

20.5.5.10 Protection within classes [protection.within.classes]

It is unspecified whether any function signature or class described in Clauses [language.support] through [thread] and Annex [depr] is a friend of another class in the C++ standard library.

20.5.5.11 Derived classes [derivation]

An implementation may derive any class in the C++ standard library from a class with a name reserved to the implementation.
Certain classes defined in the C++ standard library are required to be derived from other classes in the C++ standard library.
An implementation may derive such a class directly from the required base or indirectly through a hierarchy of base classes with names reserved to the implementation.
In any case:
  • Every base class described as virtual shall be virtual;
  • Every base class not specified as virtual shall not be virtual;
  • Unless explicitly stated otherwise, types with distinct names shall be distinct types.182
All types specified in the C++ standard library shall be non-final types unless otherwise specified.
There is an implicit exception to this rule for types that are described as synonyms for basic integral types, such as size_­t ([support.types]) and streamoff ([stream.types]).

20.5.5.12 Restrictions on exception handling [res.on.exception.handling]

Any of the functions defined in the C++ standard library can report a failure by throwing an exception of a type described in its Throws: paragraph, or of a type derived from a type named in the Throws: paragraph that would be caught by an exception handler for the base type.
Functions from the C standard library shall not throw exceptions183 except when such a function calls a program-supplied function that throws an exception.184
Destructor operations defined in the C++ standard library shall not throw exceptions.
Every destructor in the C++ standard library shall behave as if it had a non-throwing exception specification.
Functions defined in the C++ standard library that do not have a Throws: paragraph but do have a potentially-throwing exception specification may throw implementation-defined exceptions.185
Implementations should report errors by throwing exceptions of or derived from the standard exception classes ([bad.alloc], [support.exception], [std.exceptions]).
An implementation may strengthen the exception specification for a non-virtual function by adding a non-throwing exception specification.
That is, the C library functions can all be treated as if they are marked noexcept.
This allows implementations to make performance optimizations based on the absence of exceptions at runtime.
The functions qsort() and bsearch() ([alg.c.library]) meet this condition.
In particular, they can report a failure to allocate storage by throwing an exception of type bad_­alloc, or a class derived from bad_­alloc ([bad.alloc]).

20.5.5.13 Restrictions on storage of pointers [res.on.pointer.storage]

Objects constructed by the standard library that may hold a user-supplied pointer value or an integer of type std​::​intptr_­t shall store such values in a traceable pointer location ([basic.stc.dynamic.safety]).
[Note
:
Other libraries are strongly encouraged to do the same, since not doing so may result in accidental use of pointers that are not safely derived.
Libraries that store pointers outside the user's address space should make it appear that they are stored and retrieved from a traceable pointer location.
end note
]

20.5.5.14 Value of error codes [value.error.codes]

Certain functions in the C++ standard library report errors via a std​::​error_­code ([syserr.errcode.overview]) object.
That object's category() member shall return std​::​system_­category() for errors originating from the operating system, or a reference to an implementation-defined error_­category object for errors originating elsewhere.
The implementation shall define the possible values of value() for each of these error categories.
[Example
:
For operating systems that are based on POSIX, implementations are encouraged to define the std​::​system_­category() values as identical to the POSIX errno values, with additional values as defined by the operating system's documentation.
Implementations for operating systems that are not based on POSIX are encouraged to define values identical to the operating system's values.
For errors that do not originate from the operating system, the implementation may provide enums for the associated values.
end example
]

20.5.5.15 Moved-from state of library types [lib.types.movedfrom]

Objects of types defined in the C++ standard library may be moved from ([class.copy]).
Move operations may be explicitly specified or implicitly generated.
Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state.

21 Language support library [language.support]

21.1 General [support.general]

This Clause describes the function signatures that are called implicitly, and the types of objects generated implicitly, during the execution of some C++ programs.
It also describes the headers that declare these function signatures and define any related types.
The following subclauses describe common type definitions used throughout the library, characteristics of the predefined types, functions supporting start and termination of a C++ program, support for dynamic memory management, support for dynamic type identification, support for exception processing, support for initializer lists, and other runtime support, as summarized in Table 32.
Table 32 — Language support library summary
Subclause
Header(s)
Common definitions
<cstddef>
<cstdlib>
Implementation properties
<limits>
<climits>
<cfloat>
Integer types
<cstdint>
Start and termination
<cstdlib>
Dynamic memory management
<new>
Type identification
<typeinfo>
Exception handling
<exception>
Initializer lists
<initializer_­list>
Other runtime support
<csignal>
<csetjmp>
<cstdarg>
<cstdlib>

21.2 Common definitions [support.types]

21.2.1 Header <cstddef> synopsis [cstddef.syn]

namespace std {
  using ptrdiff_t = see below;
  using size_t = see below;
  using max_align_t = see below;
  using nullptr_t = decltype(nullptr);

  enum class byte : unsigned char {};

  // [support.types.byteops], byte type operations
  template <class IntType>
    constexpr byte& operator<<=(byte& b, IntType shift) noexcept;
  template <class IntType>
    constexpr byte operator<<(byte b, IntType shift) noexcept;
  template <class IntType>
    constexpr byte& operator>>=(byte& b, IntType shift) noexcept;
  template <class IntType>
    constexpr byte operator>>(byte b, IntType shift) noexcept;
  constexpr byte& operator|=(byte& l, byte r) noexcept;
  constexpr byte operator|(byte l, byte r) noexcept;
  constexpr byte& operator&=(byte& l, byte r) noexcept;
  constexpr byte operator&(byte l, byte r) noexcept;
  constexpr byte& operator^=(byte& l, byte r) noexcept;
  constexpr byte operator^(byte l, byte r) noexcept;
  constexpr byte operator~(byte b) noexcept;
  template <class IntType>
    constexpr IntType to_integer(byte b) noexcept;
}

#define NULL see below
#define offsetof(P, D) see below
The contents and meaning of the header <cstddef> are the same as the C standard library header <stddef.h>, except that it does not declare the type wchar_­t, that it also declares the type byte and its associated operations ([support.types.byteops]), and as noted in [support.types.nullptr] and [support.types.layout].
See also: ISO C 7.
19

21.2.2 Header <cstdlib> synopsis [cstdlib.syn]

namespace std {
  using size_t = see below;
  using div_t = see below;
  using ldiv_t = see below;
  using lldiv_t = see below;
}

#define NULL see below
#define EXIT_FAILURE see below
#define EXIT_SUCCESS see below
#define RAND_MAX see below
#define MB_CUR_MAX see below

namespace std {
  // Exposition-only function type aliases
  extern "C" using c-atexit-handler = void();                        // exposition only
  extern "C++" using atexit-handler = void();                        // exposition only
  extern "C" using c-compare-pred = int(const void*, const void*);   // exposition only
  extern "C++" using compare-pred = int(const void*, const void*);   // exposition only

  // [support.start.term], start and termination
  [[noreturn]] void abort() noexcept;
  int atexit(c-atexit-handler* func) noexcept;
  int atexit(atexit-handler* func) noexcept;
  int at_quick_exit(c-atexit-handler* func) noexcept;
  int at_quick_exit(atexit-handler* func) noexcept;
  [[noreturn]] void exit(int status);
  [[noreturn]] void _Exit(int status) noexcept;
  [[noreturn]] void quick_exit(int status) noexcept;

  char* getenv(const char* name);
  int system(const char* string);

  // [c.malloc], C library memory allocation
  void* aligned_alloc(size_t alignment, size_t size);
  void* calloc(size_t nmemb, size_t size);
  void free(void* ptr);
  void* malloc(size_t size);
  void* realloc(void* ptr, size_t size);

  double atof(const char* nptr);
  int atoi(const char* nptr);
  long int atol(const char* nptr);
  long long int atoll(const char* nptr);
  double strtod(const char* nptr, char** endptr);
  float strtof(const char* nptr, char** endptr);
  long double strtold(const char* nptr, char** endptr);
  long int strtol(const char* nptr, char** endptr, int base);
  long long int strtoll(const char* nptr, char** endptr, int base);
  unsigned long int strtoul(const char* nptr, char** endptr, int base);
  unsigned long long int strtoull(const char* nptr, char** endptr, int base);

  // [c.mb.wcs], multibyte / wide string and character conversion functions
  int mblen(const char* s, size_t n);
  int mbtowc(wchar_t* pwc, const char* s, size_t n);
  int wctomb(char* s, wchar_t wchar);
  size_t mbstowcs(wchar_t* pwcs, const char* s, size_t n);
  size_t wcstombs(char* s, const wchar_t* pwcs, size_t n);

  // [alg.c.library], C standard library algorithms
  void* bsearch(const void* key, const void* base, size_t nmemb, size_t size,
                c-compare-pred* compar);
  void* bsearch(const void* key, const void* base, size_t nmemb, size_t size,
                compare-pred* compar);
  void qsort(void* base, size_t nmemb, size_t size, c-compare-pred* compar);
  void qsort(void* base, size_t nmemb, size_t size, compare-pred* compar);

  // [c.math.rand], low-quality random number generation
  int rand();
  void srand(unsigned int seed);

  // [c.math.abs], absolute values
  int abs(int j);
  long int abs(long int j);
  long long int abs(long long int j);
  float abs(float j);
  double abs(double j);
  long double abs(long double j);

  long int labs(long int j);
  long long int llabs(long long int j);

  div_t div(int numer, int denom);
  ldiv_t div(long int numer, long int denom);             // see [library.c]
  lldiv_t div(long long int numer, long long int denom);  // see [library.c]
  ldiv_t ldiv(long int numer, long int denom);
  lldiv_t lldiv(long long int numer, long long int denom);
}
The contents and meaning of the header <cstdlib> are the same as the C standard library header <stdlib.h>, except that it does not declare the type wchar_­t, and except as noted in [support.types.nullptr], [support.types.layout], [support.start.term], [c.malloc], [c.mb.wcs], [alg.c.library], [c.math.rand], and [c.math.abs].
[Note
:
Several functions have additional overloads in this International Standard, but they have the same behavior as in the C standard library ([library.c]).
end note
]
See also: ISO C 7.
22

21.2.3 Null pointers [support.types.nullptr]

The type nullptr_­t is a synonym for the type of a nullptr expression, and it has the characteristics described in [basic.fundamental] and [conv.ptr].
[Note
:
Although nullptr's address cannot be taken, the address of another nullptr_­t object that is an lvalue can be taken.
end note
]
The macro NULL is an implementation-defined null pointer constant.186
Possible definitions include 0 and 0L, but not (void*)0.

21.2.4 Sizes, alignments, and offsets [support.types.layout]

The macro offsetof(type, member-designator) has the same semantics as the corresponding macro in the C standard library header <stddef.h>, but accepts a restricted set of type arguments in this International Standard.
Use of the offsetof macro with a type other than a standard-layout class (Clause [class]) is conditionally-supported.187
The expression offsetof(type, member-designator) is never type-dependent ([temp.dep.expr]) and it is value-dependent ([temp.dep.constexpr]) if and only if type is dependent.
The result of applying the offsetof macro to a static data member or a function member is undefined.
No operation invoked by the offsetof macro shall throw an exception and noexcept(offsetof(type, member-designator)) shall be true.
The type ptrdiff_­t is an implementation-defined signed integer type that can hold the difference of two subscripts in an array object, as described in [expr.add].
The type size_­t is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object.
[Note
:
It is recommended that implementations choose types for ptrdiff_­t and size_­t whose integer conversion ranks ([conv.rank]) are no greater than that of signed long int unless a larger size is necessary to contain all the possible values.
end note
]
The type max_­align_­t is a POD type whose alignment requirement is at least as great as that of every scalar type, and whose alignment requirement is supported in every context.
See also: Alignment ([basic.align]), Sizeof ([expr.sizeof]), Additive operators ([expr.add]), Free store ([class.free]), and ISO C 7.
19.
Note that offsetof is required to work as specified even if unary operator& is overloaded for any of the types involved.

21.2.5 byte type operations [support.types.byteops]

template <class IntType> constexpr byte& operator<<=(byte& b, IntType shift) noexcept;
Remarks: This function shall not participate in overload resolution unless is_­integral_­v<IntType> is true.
Effects: Equivalent to: return b = byte(static_­cast<unsigned char>(b) << shift);
template <class IntType> constexpr byte operator<<(byte b, IntType shift) noexcept;
Remarks: This function shall not participate in overload resolution unless is_­integral_­v<IntType> is true.
Effects: Equivalent to: return byte(static_­cast<unsigned char>(b) << shift);
template <class IntType> constexpr byte& operator>>=(byte& b, IntType shift) noexcept;
Remarks: This function shall not participate in overload resolution unless is_­integral_­v<IntType> is true.
Effects: Equivalent to: return b = byte(static_­cast<unsigned char>(b) >> shift);
template <class IntType> constexpr byte operator>>(byte b, IntType shift) noexcept;
Remarks: This function shall not participate in overload resolution unless is_­integral_­v<IntType> is true.
Effects: Equivalent to: return byte(static_­cast<unsigned char>(b) >> shift);
constexpr byte& operator|=(byte& l, byte r) noexcept;
Effects: Equivalent to:
return l = byte(static_cast<unsigned char>(l) | static_cast<unsigned char>(r));
constexpr byte operator|(byte l, byte r) noexcept;
Effects: Equivalent to:
return byte(static_cast<unsigned char>(l) | static_cast<unsigned char>(r));
constexpr byte& operator&=(byte& l, byte r) noexcept;
Effects: Equivalent to:
return l = byte(static_cast<unsigned char>(l) & static_cast<unsigned char>(r));
constexpr byte operator&(byte l, byte r) noexcept;
Effects: Equivalent to:
return byte(static_cast<unsigned char>(l) & static_cast<unsigned char>(r));
constexpr byte& operator^=(byte& l, byte r) noexcept;
Effects: Equivalent to:
return l = byte(static_cast<unsigned char>(l) ^ static_cast<unsigned char>(r));
constexpr byte operator^(byte l, byte r) noexcept;
Effects: Equivalent to:
return byte(static_cast<unsigned char>(l) ^ static_cast<unsigned char>(r));
constexpr byte operator~(byte b) noexcept;
Effects: Equivalent to: return byte(~static_­cast<unsigned char>(b));
template <class IntType> constexpr IntType to_integer(byte b) noexcept;
Remarks: This function shall not participate in overload resolution unless is_­integral_­v<IntType> is true.
Effects: Equivalent to: return IntType(b);

21.3 Implementation properties [support.limits]

21.3.1 General [support.limits.general]

The headers <limits> ([limits.syn]), <climits> ([climits.syn]), and <cfloat> ([cfloat.syn]) supply characteristics of implementation-dependent arithmetic types ([basic.fundamental]).

21.3.2 Header <limits> synopsis [limits.syn]

namespace std {
  // [fp.style], floating-point type properties
  enum float_round_style;
  enum float_denorm_style;

  // [numeric.limits], class template numeric_­limits
  template<class T> class numeric_limits;

  template<> class numeric_limits<bool>;

  template<> class numeric_limits<char>;
  template<> class numeric_limits<signed char>;
  template<> class numeric_limits<unsigned char>;
  template<> class numeric_limits<char16_t>;
  template<> class numeric_limits<char32_t>;
  template<> class numeric_limits<wchar_t>;

  template<> class numeric_limits<short>;
  template<> class numeric_limits<int>;
  template<> class numeric_limits<long>;
  template<> class numeric_limits<long long>;
  template<> class numeric_limits<unsigned short>;
  template<> class numeric_limits<unsigned int>;
  template<> class numeric_limits<unsigned long>;
  template<> class numeric_limits<unsigned long long>;

  template<> class numeric_limits<float>;
  template<> class numeric_limits<double>;
  template<> class numeric_limits<long double>;
}

21.3.3 Floating-point type properties [fp.style]

21.3.3.1 Type float_­round_­style [round.style]

namespace std {
  enum float_round_style {
    round_indeterminate       = -1,
    round_toward_zero         =  0,
    round_to_nearest          =  1,
    round_toward_infinity     =  2,
    round_toward_neg_infinity =  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

21.3.3.2 Type float_­denorm_­style [denorm.style]

namespace std {
  enum float_denorm_style {
    denorm_indeterminate = -1,
    denorm_absent = 0,
    denorm_present = 1
  };
}
The presence or absence of subnormal numbers (variable number of exponent bits) is characterized by the values:
  • denorm_­indeterminate if it cannot be determined whether or not the type allows subnormal values
  • denorm_­absent if the type does not allow subnormal values
  • denorm_­present if the type does allow subnormal values

21.3.4 Class template numeric_­limits [numeric.limits]

The numeric_­limits class template provides a C++ program with information about various properties of the implementation's representation of the arithmetic types.
namespace std {
  template<class T> 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 constexpr int  digits = 0;
    static constexpr int  digits10 = 0;
    static constexpr int  max_digits10 = 0;
    static constexpr bool is_signed = false;
    static constexpr bool is_integer = false;
    static constexpr bool is_exact = false;
    static constexpr int  radix = 0;
    static constexpr T epsilon() noexcept { return T(); }
    static constexpr T round_error() noexcept { return T(); }

    static constexpr int  min_exponent = 0;
    static constexpr int  min_exponent10 = 0;
    static constexpr int  max_exponent = 0;
    static constexpr int  max_exponent10 = 0;

    static constexpr bool has_infinity = false;
    static constexpr bool has_quiet_NaN = false;
    static constexpr bool has_signaling_NaN = false;
    static constexpr float_denorm_style has_denorm = denorm_absent;
    static constexpr bool has_denorm_loss = false;
    static constexpr T infinity() noexcept { return T(); }
    static constexpr T quiet_NaN() noexcept { return T(); }
    static constexpr T signaling_NaN() noexcept { return T(); }
    static constexpr T denorm_min() noexcept { return T(); }

    static constexpr bool is_iec559 = false;
    static constexpr bool is_bounded = false;
    static constexpr bool is_modulo = false;

    static constexpr bool traps = false;
    static constexpr bool tinyness_before = false;
    static constexpr float_round_style round_style = round_toward_zero;
  };

  template<class T> class numeric_limits<const T>;
  template<class T> class numeric_limits<volatile T>;
  template<class T> class numeric_limits<const volatile T>;
}
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.
The default numeric_­limits<T> template shall have all members, but with 0 or false values.
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.
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.
Non-arithmetic standard types, such as complex<T> ([complex]), shall not have specializations.

21.3.4.1 numeric_­limits members [numeric.limits.members]

Each member function defined in this subclause is signal-safe ([csignal.syn]).
static constexpr T min() noexcept;
Minimum finite value.188
For floating types with subnormal numbers, returns the minimum positive normalized value.
Meaningful for all specializations in which is_­bounded != false, or is_­bounded == false && is_­signed == false.
static constexpr T max() noexcept;
Maximum finite value.189
Meaningful for all specializations in which is_­bounded != false.
static constexpr T lowest() noexcept;
A finite value x such that there is no other finite value y where y < x.190
Meaningful for all specializations in which is_­bounded != false.
static constexpr int digits;
Number of radix digits that can be represented without change.
For integer types, the number of non-sign bits in the representation.
For floating-point types, the number of radix digits in the mantissa.191
static constexpr int digits10;
Number of base 10 digits that can be represented without change.192
Meaningful for all specializations in which is_­bounded != false.
static constexpr int max_digits10;
Number of base 10 digits required to ensure that values which differ are always differentiated.
Meaningful for all floating-point types.
static constexpr bool is_signed;
true if the type is signed.
Meaningful for all specializations.
static constexpr bool is_integer;
true if the type is integer.
Meaningful for all specializations.
static constexpr bool is_exact;
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.
Meaningful for all specializations.
static constexpr int radix;
For floating types, specifies the base or radix of the exponent representation (often 2).193
For integer types, specifies the base of the representation.194
Meaningful for all specializations.
static constexpr T epsilon() noexcept;
Machine epsilon: the difference between 1 and the least value greater than 1 that is representable.195
Meaningful for all floating-point types.
static constexpr T round_error() noexcept;
Measure of the maximum rounding error.196
static constexpr int min_exponent;
Minimum negative integer such that radix raised to the power of one less than that integer is a normalized floating-point number.197
Meaningful for all floating-point types.
static constexpr int min_exponent10;
Minimum negative integer such that 10 raised to that power is in the range of normalized floating-point numbers.198
Meaningful for all floating-point types.
static constexpr int max_exponent;
Maximum positive integer such that radix raised to the power one less than that integer is a representable finite floating-point number.199
Meaningful for all floating-point types.
static constexpr int max_exponent10;
Maximum positive integer such that 10 raised to that power is in the range of representable finite floating-point numbers.200
Meaningful for all floating-point types.
static constexpr bool has_infinity;
true if the type has a representation for positive infinity.
Meaningful for all floating-point types.
Shall be true for all specializations in which is_­iec559 != false.
static constexpr bool has_quiet_NaN;
true if the type has a representation for a quiet (non-signaling) “Not a Number”.201
Meaningful for all floating-point types.
Shall be true for all specializations in which is_­iec559 != false.
static constexpr bool has_signaling_NaN;
true if the type has a representation for a signaling “Not a Number”.202
Meaningful for all floating-point types.
Shall be true for all specializations in which is_­iec559 != false.
static constexpr float_denorm_style has_denorm;
denorm_­present if the type allows subnormal values (variable number of exponent bits)203, denorm_­absent if the type does not allow subnormal values, and denorm_­indeterminate if it is indeterminate at compile time whether the type allows subnormal values.
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.204
static constexpr T infinity() noexcept;
Representation of positive infinity, if available.205
Meaningful for all specializations for which has_­infinity != false.
Required in specializations for which is_­iec559 != false.
static constexpr T quiet_NaN() noexcept;
Representation of a quiet “Not a Number”, if available.206
Meaningful for all specializations for which has_­quiet_­NaN != false.
Required in specializations for which is_­iec559 != false.
static constexpr T signaling_NaN() noexcept;
Representation of a signaling “Not a Number”, if available.207
Meaningful for all specializations for which has_­signaling_­NaN != false.
Required in specializations for which is_­iec559 != false.
static constexpr T denorm_min() noexcept;
Minimum positive subnormal value.208
Meaningful for all floating-point types.
In specializations for which has_­denorm == false, returns the minimum positive normalized value.
static constexpr bool is_iec559;
true if and only if the type adheres to ISO/IEC/IEEE 60559.209
Meaningful for all floating-point types.
static constexpr bool is_bounded;
true if the set of values representable by the type is finite.210
[Note
:
All fundamental types ([basic.fundamental]) are bounded.
This member would be false for arbitrary precision types.
end note
]
Meaningful for all specializations.
static constexpr bool is_modulo;
true if the type is modulo.211
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.
[Example
:
is_­modulo is false for signed integer types ([basic.fundamental]) unless an implementation, as an extension to this International Standard, defines signed integer overflow to wrap.
end example
]
Meaningful for all specializations.
static constexpr bool traps;
true if, at program startup, there exists a value of the type that would cause an arithmetic operation using that value to trap.212
Meaningful for all specializations.
static constexpr bool tinyness_before;
true if tinyness is detected before rounding.213
Meaningful for all floating-point types.
static constexpr float_round_style round_style;
The rounding style for the type.214
Meaningful for all floating-point types.
Specializations for integer types shall return round_­toward_­zero.
Equivalent to CHAR_­MIN, SHRT_­MIN, FLT_­MIN, DBL_­MIN, etc.
Equivalent to CHAR_­MAX, SHRT_­MAX, FLT_­MAX, DBL_­MAX, etc.
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.
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.
Rounding error is described in LIA-1 Section 5.
2.
4 and Annex C Rationale Section C.
5.
2.
4 — Rounding and rounding constants.
Equivalent to FLT_­MIN_­EXP, DBL_­MIN_­EXP, LDBL_­MIN_­EXP.
Equivalent to FLT_­MIN_­10_­EXP, DBL_­MIN_­10_­EXP, LDBL_­MIN_­10_­EXP.
Equivalent to FLT_­MAX_­EXP, DBL_­MAX_­EXP, LDBL_­MAX_­EXP.
Equivalent to FLT_­MAX_­10_­EXP, DBL_­MAX_­10_­EXP, LDBL_­MAX_­10_­EXP.
Required by LIA-1.
Required by LIA-1.
Required by LIA-1.
See ISO/IEC/IEEE 60559.
Required by LIA-1.
Required by LIA-1.
Required by LIA-1.
Required by LIA-1.
ISO/IEC/IEEE 60559:2011 is the same as IEEE 754-2008.
Required by LIA-1.
Required by LIA-1.
Required by LIA-1.
Refer to ISO/IEC/IEEE 60559.
Required by LIA-1.
Equivalent to FLT_­ROUNDS.
Required by LIA-1.

21.3.4.2 numeric_­limits specializations [numeric.special]

All members shall be provided for all specializations.
However, many values are only required to be meaningful under certain conditions (for example, epsilon() is only meaningful if is_­integer is false).
Any value that is not “meaningful” shall be set to 0 or false.
[Example
:
namespace std {
  template<> class numeric_limits<float> {
  public:
    static constexpr bool is_specialized = true;

    static constexpr float min() noexcept { return 1.17549435E-38F; }
    static constexpr float max() noexcept { return 3.40282347E+38F; }
    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;
    static constexpr float epsilon() noexcept     { return 1.19209290E-07F; }
    static constexpr float round_error() noexcept { return 0.5F; }

    static constexpr int min_exponent   = -125;
    static constexpr int min_exponent10 = - 37;
    static constexpr int max_exponent   = +128;
    static constexpr int max_exponent10 = + 38;

    static constexpr bool has_infinity             = true;
    static constexpr bool has_quiet_NaN            = true;
    static constexpr bool has_signaling_NaN        = true;
    static constexpr float_denorm_style has_denorm = denorm_absent;
    static constexpr bool has_denorm_loss          = false;

    static constexpr float infinity()      noexcept { return value; }
    static constexpr float quiet_NaN()     noexcept { return value; }
    static constexpr float signaling_NaN() noexcept { return value; }
    static constexpr float denorm_min()    noexcept { return min(); }

    static constexpr bool is_iec559  = true;
    static constexpr bool is_bounded = true;
    static constexpr bool is_modulo  = false;
    static constexpr bool traps      = true;
    static constexpr bool tinyness_before = true;

    static constexpr float_round_style round_style = round_to_nearest;
  };
}
end example
]
The specialization for bool shall be provided as follows:
namespace std {
   template<> class numeric_limits<bool> {
   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  digits = 1;
     static constexpr int  digits10 = 0;
     static constexpr int  max_digits10 = 0;

     static constexpr bool is_signed = false;
     static constexpr bool is_integer = true;
     static constexpr bool is_exact = true;
     static constexpr int  radix = 2;
     static constexpr bool epsilon() noexcept { return 0; }
     static constexpr bool round_error() noexcept { return 0; }

     static constexpr int  min_exponent = 0;
     static constexpr int  min_exponent10 = 0;
     static constexpr int  max_exponent = 0;
     static constexpr int  max_exponent10 = 0;

     static constexpr bool has_infinity = false;
     static constexpr bool has_quiet_NaN = false;
     static constexpr bool has_signaling_NaN = false;
     static constexpr float_denorm_style has_denorm = denorm_absent;
     static constexpr bool has_denorm_loss = false;
     static constexpr bool infinity() noexcept { return 0; }
     static constexpr bool quiet_NaN() noexcept { return 0; }
     static constexpr bool signaling_NaN() noexcept { return 0; }
     static constexpr bool denorm_min() noexcept { return 0; }

     static constexpr bool is_iec559 = false;
     static constexpr bool is_bounded = true;
     static constexpr bool is_modulo = false;

     static constexpr bool traps = false;
     static constexpr bool tinyness_before = false;
     static constexpr float_round_style round_style = round_toward_zero;
   };
}

21.3.5 Header <climits> synopsis [climits.syn]

#define CHAR_BIT see below
#define SCHAR_MIN see below
#define SCHAR_MAX see below
#define UCHAR_MAX see below
#define CHAR_MIN see below
#define CHAR_MAX see below
#define MB_LEN_MAX see below
#define SHRT_MIN see below
#define SHRT_MAX see below
#define USHRT_MAX see below
#define INT_MIN see below
#define INT_MAX see below
#define UINT_MAX see below
#define LONG_MIN see below
#define LONG_MAX see below
#define ULONG_MAX see below
#define LLONG_MIN see below
#define LLONG_MAX see below
#define ULLONG_MAX see below
The header <climits> defines all macros the same as the C standard library header <limits.h>.
[Note
:
The types of the constants defined by macros in <climits> are not required to match the types to which the macros refer.
end note
]
See also: ISO C 5.
2.
4.
2.
1

21.3.6 Header <cfloat> synopsis [cfloat.syn]

#define FLT_ROUNDS see below
#define FLT_EVAL_METHOD see below
#define FLT_HAS_SUBNORM see below
#define DBL_HAS_SUBNORM see below
#define LDBL_HAS_SUBNORM see below
#define FLT_RADIX see below
#define FLT_MANT_DIG see below
#define DBL_MANT_DIG see below
#define LDBL_MANT_DIG see below
#define FLT_DECIMAL_DIG see below
#define DBL_DECIMAL_DIG see below
#define LDBL_DECIMAL_DIG see below
#define DECIMAL_DIG see below
#define FLT_DIG see below
#define DBL_DIG see below
#define LDBL_DIG see below
#define FLT_MIN_EXP see below
#define DBL_MIN_EXP see below
#define LDBL_MIN_EXP see below
#define FLT_MIN_10_EXP see below
#define DBL_MIN_10_EXP see below
#define LDBL_MIN_10_EXP see below
#define FLT_MAX_EXP see below
#define DBL_MAX_EXP see below
#define LDBL_MAX_EXP see below
#define FLT_MAX_10_EXP see below
#define DBL_MAX_10_EXP see below
#define LDBL_MAX_10_EXP see below
#define FLT_MAX see below
#define DBL_MAX see below
#define LDBL_MAX see below
#define FLT_EPSILON see below
#define DBL_EPSILON see below
#define LDBL_EPSILON see below
#define FLT_MIN see below
#define DBL_MIN see below
#define LDBL_MIN see below
#define FLT_TRUE_MIN see below
#define DBL_TRUE_MIN see below
#define LDBL_TRUE_MIN see below
The header <cfloat> defines all macros the same as the C standard library header <float.h>.
See also: ISO C 5.
2.
4.
2.
2

21.4 Integer types [cstdint]

21.4.1 Header <cstdint> synopsis [cstdint.syn]

namespace std {
  using int8_t         = signed integer type;  // optional
  using int16_t        = signed integer type;  // optional
  using int32_t        = signed integer type;  // optional
  using int64_t        = signed integer type;  // optional

  using int_fast8_t    = signed integer type;
  using int_fast16_t   = signed integer type;
  using int_fast32_t   = signed integer type;
  using int_fast64_t   = signed integer type;

  using int_least8_t   = signed integer type;
  using int_least16_t  = signed integer type;
  using int_least32_t  = signed integer type;
  using int_least64_t  = signed integer type;

  using intmax_t       = signed integer type;
  using intptr_t       = signed integer type;   // optional

  using uint8_t        = unsigned integer type; // optional
  using uint16_t       = unsigned integer type; // optional
  using uint32_t       = unsigned integer type; // optional
  using uint64_t       = unsigned integer type; // optional

  using uint_fast8_t   = unsigned integer type;
  using uint_fast16_t  = unsigned integer type;
  using uint_fast32_t  = unsigned integer type;
  using uint_fast64_t  = unsigned integer type;

  using uint_least8_t  = unsigned integer type;
  using uint_least16_t = unsigned integer type;
  using uint_least32_t = unsigned integer type;
  using uint_least64_t = unsigned integer type;

  using uintmax_t      = unsigned integer type;
  using uintptr_t      = unsigned integer type; // 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
The header defines all types and macros the same as the C standard library header <stdint.h>.
See also: ISO C 7.
20.

21.5 Start and termination [support.start.term]

[Note
:
The header <cstdlib> ([cstdlib.syn]) declares the functions described in this subclause.
end note
]
[[noreturn]] void _Exit(int status) noexcept;
Effects: This function has the semantics specified in the C standard library.
Remarks: The program is terminated without executing destructors for objects of automatic, thread, or static storage duration and without calling functions passed to atexit() ([basic.start.term]).
The function _­Exit is signal-safe ([csignal.syn]).
[[noreturn]] void abort() noexcept;
Effects: This function has the semantics specified in the C standard library.
Remarks: The program is terminated without executing destructors for objects of automatic, thread, or static storage duration and without calling functions passed to atexit() ([basic.start.term]).
The function abort is signal-safe ([csignal.syn]).
int atexit(c-atexit-handler* f) noexcept; int atexit(atexit-handler* f) noexcept;
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 ([intro.multithread]) a call to exit() will succeed.
[Note
:
The atexit() functions do not introduce a data race ([res.on.data.races]).
end note
]
Implementation limits: The implementation shall support the registration of at least 32 functions.
Returns: The atexit() function returns zero if the registration succeeds, nonzero if it fails.
[[noreturn]] void exit(int status);
Effects:
  • 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.215
    See [basic.start.term] for the order of destructions and calls.
    (Automatic objects are not destroyed as a result of calling exit().)216
    If control leaves a registered function called by exit because the function does not provide a handler for a thrown exception, std​::​terminate() shall be called ([except.terminate]).
  • Next, all open C streams (as mediated by the function signatures declared in <cstdio>) 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.217
int at_quick_exit(c-atexit-handler* f) noexcept; int at_quick_exit(atexit-handler* f) noexcept;
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 ([intro.multithread]) all calls to quick_­exit will succeed.
[Note
:
The at_­quick_­exit() functions do not introduce a data race ([res.on.data.races]).
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
]
Implementation limits: The implementation shall support the registration of at least 32 functions.
Returns: Zero if the registration succeeds, nonzero if it fails.
[[noreturn]] void quick_exit(int status) noexcept;
Effects: Functions registered by calls to at_­quick_­exit are called in the reverse order of their registration, except that a function shall be called after any previously registered functions that had already been called at the time it was registered.
Objects shall not be destroyed as a result of calling quick_­exit.
If control leaves a registered function called by quick_­exit because the function does not provide a handler for a thrown exception, std​::​terminate() shall be called.
[Note
:
A function registered via at_­quick_­exit is invoked by the thread that calls quick_­exit, which can be 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.
end note
]
Remarks: The function quick_­exit is signal-safe ([csignal.syn]) when the functions registered with at_­quick_­exit are.
22.
4.
A function is called for every time it is registered.
Objects with automatic storage duration are all destroyed in a program whose main function ([basic.start.main]) contains no automatic objects and executes the call to exit().
Control can be transferred directly to such a main function by throwing an exception that is caught in main.
The macros EXIT_­FAILURE and EXIT_­SUCCESS are defined in <cstdlib>.

21.6 Dynamic memory management [support.dynamic]

The header <new> defines several functions that manage the allocation of dynamic storage in a program.
It also defines components for reporting storage management errors.

21.6.1 Header <new> synopsis [new.syn]

namespace std {
  class bad_alloc;
  class bad_array_new_length;
  enum class align_val_t : size_t {};
  struct nothrow_t { explicit nothrow_t() = default; };
  extern const nothrow_t nothrow;
  using new_handler = void (*)();
  new_handler get_new_handler() noexcept;
  new_handler set_new_handler(new_handler new_p) noexcept;

  // [ptr.launder], pointer optimization barrier
  template <class T> constexpr T* launder(T* p) noexcept;

  // [hardware.interference], hardware interference size
  inline constexpr size_t hardware_destructive_interference_size = implementation-defined;
  inline constexpr size_t hardware_constructive_interference_size = implementation-defined;
}

void* operator new(std::size_t size);
void* operator new(std::size_t size, std::align_val_t alignment);
void* operator new(std::size_t size, const std::nothrow_t&) noexcept;
void* operator new(std::size_t size, std::align_val_t alignment,
                   const std::nothrow_t&) noexcept;
void  operator delete(void* ptr) noexcept;
void  operator delete(void* ptr, std::size_t size) noexcept;
void  operator delete(void* ptr, std::align_val_t alignment) noexcept;
void  operator delete(void* ptr, std::size_t size, std::align_val_t alignment) noexcept;
void  operator delete(void* ptr, const std::nothrow_t&) noexcept;
void  operator delete(void* ptr, std::align_val_t alignment,
                      const std::nothrow_t&) noexcept;
void* operator new[](std::size_t size);
void* operator new[](std::size_t size, std::align_val_t alignment);
void* operator new[](std::size_t size, const std::nothrow_t&) noexcept;
void* operator new[](std::size_t size, std::align_val_t alignment,
                     const std::nothrow_t&) noexcept;
void  operator delete[](void* ptr) noexcept;
void  operator delete[](void* ptr, std::size_t size) noexcept;
void  operator delete[](void* ptr, std::align_val_t alignment) noexcept;
void  operator delete[](void* ptr, std::size_t size, std::align_val_t alignment) noexcept;
void  operator delete[](void* ptr, const std::nothrow_t&) noexcept;
void  operator delete[](void* ptr, std::align_val_t alignment,
                        const std::nothrow_t&) noexcept;

void* operator new  (std::size_t size, void* ptr) noexcept;
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: [intro.memory], [basic.stc.dynamic], [expr.new], [expr.delete], [class.free], [memory].

21.6.2 Storage allocation and deallocation [new.delete]

Except where otherwise specified, the provisions of [basic.stc.dynamic] apply to the library versions of operator new and operator delete.
If the value of an alignment argument passed to any of these functions is not a valid alignment value, the behavior is undefined.

21.6.2.1 Single-object forms [new.delete.single]

void* operator new(std::size_t size); void* operator new(std::size_t size, std::align_val_t alignment);
Effects: The allocation functions ([basic.stc.dynamic.allocation]) called by a new-expression to allocate size bytes of storage.
The second form is called for a type with new-extended alignment, and allocates storage with the specified alignment.
The first form is called otherwise, and allocates storage suitably aligned to represent any object of that size provided the object's type does not have new-extended alignment.
Replaceable: A C++ program may define functions with either of these function signatures, and thereby displace the default versions defined by the C++ standard library.
Required behavior: Return a non-null pointer to suitably aligned storage ([basic.stc.dynamic]), or else throw a bad_­alloc exception.
This requirement is binding on any replacement versions of these functions.
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 C standard library functions malloc or aligned_­alloc is unspecified.
  • Returns a pointer to the allocated storage if the attempt is successful.
    Otherwise, if the current new_­handler ([get.new.handler]) is a null pointer value, throws bad_­alloc.
  • Otherwise, the function calls the current new_­handler function ([new.handler]).
    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; void* operator new(std::size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept;
Effects: Same as above, except that these are 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.
Replaceable: A C++ program may define functions with either of these function signatures, and thereby displace the default versions defined by the C++ standard library.
Required behavior: Return a non-null pointer to suitably aligned storage ([basic.stc.dynamic]), or else return a null pointer.
Each of these nothrow versions of operator new returns a pointer obtained as if acquired from the (possibly replaced) corresponding non-placement function.
This requirement is binding on any replacement versions of these functions.
Default behavior: Calls operator new(size), or operator new(size, alignment), respectively.
If the call returns normally, returns the result of that call.
Otherwise, returns a null pointer.
[Example
:
T* p1 = new T;                  // throws bad_­alloc if it fails
T* p2 = new(nothrow) T;         // returns nullptr if it fails
end example
]
void operator delete(void* ptr) noexcept; void operator delete(void* ptr, std::size_t size) noexcept; void operator delete(void* ptr, std::align_val_t alignment) noexcept; void operator delete(void* ptr, std::size_t size, std::align_val_t alignment) noexcept;
Effects: The deallocation functions ([basic.stc.dynamic.deallocation]) called by a delete-expression to render the value of ptr invalid.
Replaceable: A C++ program may define functions with any of these function signatures, and thereby displace the default versions defined by the C++ standard library.
If a function without a size parameter is defined, the program should also define the corresponding function with a size parameter.
If a function with a size parameter is defined, the program shall also define the corresponding version without the size parameter.
[Note
:
The default behavior below may change in the future, which will require replacing both deallocation functions when replacing the allocation function.
end note
]
Requires: ptr shall be a null pointer or its value shall represent the address of a block of memory allocated by an earlier call to a (possibly replaced) operator new(std​::​size_­t) or operator new(std​::​size_­t, std​::​align_­val_­t) which has not been invalidated by an intervening call to operator delete.
Requires: If an implementation has strict pointer safety ([basic.stc.dynamic.safety]) then ptr shall be a safely-derived pointer.
Requires: If the alignment parameter is not present, ptr shall have been returned by an allocation function without an alignment parameter.
If present, the alignment argument shall equal the alignment argument passed to the allocation function that returned ptr.
If present, the size argument shall equal the size argument passed to the allocation function that returned ptr.
Required behavior: A call to an operator delete with a size parameter may be changed to a call to the corresponding operator delete without a size parameter, without affecting memory allocation.
[Note
:
A conforming implementation is for operator delete(void* ptr, std​::​size_­t size) to simply call operator delete(ptr).
end note
]
Default behavior: The functions that have a size parameter forward their other parameters to the corresponding function without a size parameter.
[Note
:
See the note in the above Replaceable: paragraph.
end note
]
Default behavior: If ptr is null, does nothing.
Otherwise, reclaims the storage allocated by the earlier call to operator new.
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 aligned_­alloc, calloc, malloc, or realloc, declared in <cstdlib>.
void operator delete(void* ptr, const std::nothrow_t&) noexcept; void operator delete(void* ptr, std::align_val_t alignment, const std::nothrow_t&) noexcept;
Effects: The deallocation functions ([basic.stc.dynamic.deallocation]) 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.
Replaceable: A C++ program may define functions with either of these function signatures, and thereby displace the default versions defined by the C++ standard library.
Requires: ptr shall be a null pointer or its value shall represent the address of a block of memory allocated by an earlier call to a (possibly replaced) operator new(std​::​size_­t) or operator new(std​::​size_­t, std​::​align_­val_­t) which has not been invalidated by an intervening call to operator delete.
Requires: If an implementation has strict pointer safety ([basic.stc.dynamic.safety]) then ptr shall be a safely-derived pointer.
Requires: If the alignment parameter is not present, ptr shall have been returned by an allocation function without an alignment parameter.
If present, the alignment argument shall equal the alignment argument passed to the allocation function that returned ptr.
Default behavior: Calls operator delete(ptr), or operator delete(ptr, alignment), respectively.

21.6.2.2 Array forms [new.delete.array]

void* operator new[](std::size_t size); void* operator new[](std::size_t size, std::align_val_t alignment);
Effects: The allocation functions ([basic.stc.dynamic.allocation]) called by the array form of a new-expression to allocate size bytes of storage.
The second form is called for a type with new-extended alignment, and allocates storage with the specified alignment.
The first form is called otherwise, and allocates storage suitably aligned to represent any array object of that size or smaller, provided the object's type does not have new-extended alignment.218
Replaceable: A C++ program may define functions with either of these function signatures, and thereby displace the default versions defined by the C++ standard library.
Required behavior: Same as for the corresponding single-object forms.
This requirement is binding on any replacement versions of these functions.
Default behavior: Returns operator new(size), or operator new(size, alignment), respectively.
void* operator new[](std::size_t size, const std::nothrow_t&) noexcept; void* operator new[](std::size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept;
Effects: Same as above, except that these are 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.
Replaceable: A C++ program may define functions with either of these function signatures, and thereby displace the default versions defined by the C++ standard library.
Required behavior: Return a non-null pointer to suitably aligned storage ([basic.stc.dynamic]), or else return a null pointer.
Each of these nothrow versions of operator new[] returns a pointer obtained as if acquired from the (possibly replaced) corresponding non-placement function.
This requirement is binding on any replacement versions of these functions.
Default behavior: Calls operator new[](size), or operator new[](size, alignment), respectively.
If the call returns normally, returns the result of that call.
Otherwise, returns a null pointer.
void operator delete[](void* ptr) noexcept; void operator delete[](void* ptr, std::size_t size) noexcept; void operator delete[](void* ptr, std::align_val_t alignment) noexcept; void operator delete[](void* ptr, std::size_t size, std::align_val_t alignment) noexcept;
Effects: The deallocation functions ([basic.stc.dynamic.deallocation]) called by the array form of a delete-expression to render the value of ptr invalid.
Replaceable: A C++ program may define functions with any of these function signatures, and thereby displace the default versions defined by the C++ standard library.
If a function without a size parameter is defined, the program should also define the corresponding function with a size parameter.
If a function with a size parameter is defined, the program shall also define the corresponding version without the size parameter.
[Note
:
The default behavior below may change in the future, which will require replacing both deallocation functions when replacing the allocation function.
end note
]
Requires: ptr shall be a null pointer or its value shall represent the address of a block of memory allocated by an earlier call to a (possibly replaced) operator new[](std​::​size_­t) or operator new[](std​::​size_­t, std​::​align_­val_­t) which has not been invalidated by an intervening call to operator delete[].
Requires: If an implementation has strict pointer safety ([basic.stc.dynamic.safety]) then ptr shall be a safely-derived pointer.
Requires: If the alignment parameter is not present, ptr shall have been returned by an allocation function without an alignment parameter.
If present, the alignment argument shall equal the alignment argument passed to the allocation function that returned ptr.
If present, the size argument shall equal the size argument passed to the allocation function that returned ptr.
Required behavior: A call to an operator delete[] with a size parameter may be changed to a call to the corresponding operator delete[] without a size parameter, without affecting memory allocation.
[Note
:
A conforming implementation is for operator delete[](void* ptr, std​::​size_­t size) to simply call operator delete[](ptr).
end note
]
Default behavior: The functions that have a size parameter forward their other parameters to the corresponding function without a size parameter.
The functions that do not have a size parameter forward their parameters to the corresponding operator delete (single-object) function.
void operator delete[](void* ptr, const std::nothrow_t&) noexcept; void operator delete[](void* ptr, std::align_val_t alignment, const std::nothrow_t&) noexcept;
Effects: The deallocation functions ([basic.stc.dynamic.deallocation]) 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.
Replaceable: A C++ program may define functions with either of these function signatures, and thereby displace the default versions defined by the C++ standard library.
Requires: ptr shall be a null pointer or its value shall represent the address of a block of memory allocated by an earlier call to a (possibly replaced) operator new[](std​::​size_­t) or operator new[](std​::​size_­t, std​::​align_­val_­t) which has not been invalidated by an intervening call to operator delete[].
Requires: If an implementation has strict pointer safety ([basic.stc.dynamic.safety]) then ptr shall be a safely-derived pointer.
Requires: If the alignment parameter is not present, ptr shall have been returned by an allocation function without an alignment parameter.
If present, the alignment argument shall equal the alignment argument passed to the allocation function that returned ptr.
Default behavior: Calls operator delete[](ptr), or operator delete[](ptr, alignment), respectively.
It is not the direct responsibility of operator new[] or operator delete[] 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[] to obtain space to store supplemental information.

21.6.2.3 Non-allocating forms [new.delete.placement]

These functions are reserved; a C++ program may not define functions that displace the versions in the C++ standard library ([constraints]).
The provisions of [basic.stc.dynamic] do not apply to these reserved placement forms of operator new and operator delete.
void* operator new(std::size_t size, void* ptr) noexcept;
Returns: ptr.
Remarks: Intentionally performs no other action.
[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;
Returns: ptr.
Remarks: Intentionally performs no other action.
void operator delete(void* ptr, void*) noexcept;
Effects: Intentionally performs no action.
Requires: If an implementation has strict pointer safety ([basic.stc.dynamic.safety]) then ptr shall be a safely-derived pointer.
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 ([expr.new]).
void operator delete[](void* ptr, void*) noexcept;
Effects: Intentionally performs no action.
Requires: If an implementation has strict pointer safety ([basic.stc.dynamic.safety]) then ptr shall be a safely-derived pointer.
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 ([expr.new]).

21.6.2.4 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, the C standard library functions aligned_­alloc, calloc, and malloc, the library versions of operator delete, user replacement versions of operator delete, the C standard library function free, and the C standard library function realloc shall not introduce a data race ([res.on.data.races]).
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 ([intro.multithread]) the next allocation (if any) in this order.

21.6.3 Storage allocation errors [alloc.errors]

21.6.3.1 Class bad_­alloc [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;
    const char* what() const noexcept override;
  };
}
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;
Effects: Constructs an object of class bad_­alloc.
bad_alloc(const bad_alloc&) noexcept; bad_alloc& operator=(const bad_alloc&) noexcept;
Effects: Copies an object of class bad_­alloc.
const char* what() const noexcept override;
Returns: An implementation-defined ntbs.
Remarks: The message may be a null-terminated multibyte string ([multibyte.strings]), suitable for conversion and display as a wstring ([string.classes], [locale.codecvt]).

21.6.3.2 Class bad_­array_­new_­length [new.badlength]

namespace std {
  class bad_array_new_length : public bad_alloc {
  public:
    bad_array_new_length() noexcept;
    const char* what() const noexcept override;
  };
}
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 ([expr.new]).
bad_array_new_length() noexcept;
Effects: constructs an object of class bad_­array_­new_­length.
const char* what() const noexcept override;
Returns: An implementation-defined ntbs.
Remarks: The message may be a null-terminated multibyte string ([multibyte.strings]), suitable for conversion and display as a wstring ([string.classes], [locale.codecvt]).

21.6.3.3 Type new_­handler [new.handler]

using new_handler = void (*)();
The type of a handler function to be called by operator new() or operator new[]() ([new.delete]) when they cannot satisfy a request for additional storage.
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.

21.6.3.4 set_­new_­handler [set.new.handler]

new_handler set_new_handler(new_handler new_p) noexcept;
Effects: Establishes the function designated by new_­p as the current new_­handler.
Returns: The previous new_­handler.
Remarks: The initial new_­handler is a null pointer.

21.6.3.5 get_­new_­handler [get.new.handler]

new_handler get_new_handler() noexcept;
Returns: The current new_­handler.
[Note
:
This may be a null pointer value.
end note
]

21.6.4 Pointer optimization barrier [ptr.launder]

template <class T> constexpr T* launder(T* p) noexcept;
Requires: p represents the address A of a byte in memory.
An object X that is within its lifetime ([basic.life]) and whose type is similar ([conv.qual]) to T is located at the address A.
All bytes of storage that would be reachable through the result are reachable through p (see below).
Returns: A value of type T * that points to X.
Remarks: An invocation of this function may be used in a core constant expression whenever the value of its argument may be used in a core constant expression.
A byte of storage is reachable through a pointer value that points to an object Y if it is within the storage occupied by Y, an object that is pointer-interconvertible with Y, or the immediately-enclosing array object if Y is an array element.
The program is ill-formed if T is a function type or cv void.
[Note
:
If a new object is created in storage occupied by an existing object of the same type, a pointer to the original object can be used to refer to the new object unless the type contains const or reference members; in the latter cases, this function can be used to obtain a usable pointer to the new object.
end note
]
[Example
:
struct X { const int n; };
X *p = new X{3};
const int a = p->n;
new (p) X{5};                       // p does not point to new object ([basic.life]) because X​::​n is const
const int b = p->n;                 // undefined behavior
const int c = std::launder(p)->n;   // OK
end example
]

21.6.5 Hardware interference size [hardware.interference]

inline constexpr size_t hardware_destructive_interference_size = implementation-defined;
This number is the minimum recommended offset between two concurrently-accessed objects to avoid additional performance degradation due to contention introduced by the implementation.
It shall be at least alignof(max_­align_­t).
[Example
:
struct keep_apart {
  alignas(hardware_destructive_interference_size) atomic<int> cat;
  alignas(hardware_destructive_interference_size) atomic<int> dog;
};
end example
]
inline constexpr size_t hardware_constructive_interference_size = implementation-defined;
This number is the maximum recommended size of contiguous memory occupied by two objects accessed with temporal locality by concurrent threads.
It shall be at least alignof(max_­align_­t).
[Example
:
struct together {
  atomic<int> dog;
  int puppy;
};
struct kennel {
  // Other data members...
  alignas(sizeof(together)) together pack;
  // Other data members...
};
static_assert(sizeof(together) <= hardware_constructive_interference_size);
end example
]

21.7 Type identification [support.rtti]

The header <typeinfo> defines a type associated with type information generated by the implementation.
It also defines two types for reporting dynamic type identification errors.

21.7.1 Header <typeinfo> synopsis [typeinfo.syn]

namespace std {
  class type_info;
  class bad_cast;
  class bad_typeid;
}
See also: [expr.dynamic.cast], [expr.typeid].

21.7.2 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
  };
}
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;
Effects: Compares the current object with rhs.
Returns: true if the two values describe the same type.
bool operator!=(const type_info& rhs) const noexcept;
Returns: !(*this == rhs).
bool before(const type_info& rhs) const noexcept;
Effects: Compares the current object with rhs.
Returns: true if *this precedes rhs in the implementation's collation order.
size_t hash_code() const noexcept;
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.
Remarks: An implementation should return different values for two type_­info objects which do not compare equal.
const char* name() const noexcept;
Returns: An implementation-defined ntbs.
Remarks: The message may be a null-terminated multibyte string ([multibyte.strings]), suitable for conversion and display as a wstring ([string.classes], [locale.codecvt])

21.7.3 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;
    const char* what() const noexcept override;
  };
}
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 ([expr.dynamic.cast]).
bad_cast() noexcept;
Effects: Constructs an object of class bad_­cast.
bad_cast(const bad_cast&) noexcept; bad_cast& operator=(const bad_cast&) noexcept;
Effects: Copies an object of class bad_­cast.
const char* what() const noexcept override;
Returns: An implementation-defined ntbs.
Remarks: The message may be a null-terminated multibyte string ([multibyte.strings]), suitable for conversion and display as a wstring ([string.classes], [locale.codecvt])

21.7.4 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;
    const char* what() const noexcept override;
  };
}
The class bad_­typeid defines the type of objects thrown as exceptions by the implementation to report a null pointer in a typeid expression ([expr.typeid]).
bad_typeid() noexcept;
Effects: Constructs an object of class bad_­typeid.
bad_typeid(const bad_typeid&) noexcept; bad_typeid& operator=(const bad_typeid&) noexcept;
Effects: Copies an object of class bad_­typeid.
const char* what() const noexcept override;
Returns: An implementation-defined ntbs.
Remarks: The message may be a null-terminated multibyte string ([multibyte.strings]), suitable for conversion and display as a wstring ([string.classes], [locale.codecvt])

21.8 Exception handling [support.exception]

The header <exception> defines several types and functions related to the handling of exceptions in a C++ program.

21.8.1 Header <exception> synopsis [exception.syn]

namespace std {
  class exception;
  class bad_exception;
  class nested_exception;

  using terminate_handler = void (*)();
  terminate_handler get_terminate() noexcept;
  terminate_handler set_terminate(terminate_handler f) noexcept;
  [[noreturn]] void terminate() noexcept;

  int uncaught_exceptions() noexcept;

  using exception_ptr = unspecified;

  exception_ptr current_exception() noexcept;
  [[noreturn]] void rethrow_exception(exception_ptr p);
  template<class E> exception_ptr make_exception_ptr(E e) noexcept;

  template <class T> [[noreturn]] void throw_with_nested(T&& t);
  template <class E> void rethrow_if_nested(const E& e);
}
See also: [except.special].

21.8.2 Class exception [exception]

namespace std {
  class exception {
  public:
    exception() noexcept;
    exception(const exception&) noexcept;
    exception& operator=(const exception&) noexcept;
    virtual ~exception();
    virtual const char* what() const noexcept;
  };
}
The class exception defines the base class for the types of objects thrown as exceptions by C++ standard library components, and certain expressions, to report errors detected during program execution.
Each standard library class T that derives from class exception shall have a publicly accessible copy constructor and a publicly accessible copy assignment operator that do not exit with an exception.
These member functions shall meet the following postcondition: If two objects lhs and rhs both have dynamic type T and lhs is a copy of rhs, then strcmp(lhs.what(), rhs.what()) shall equal 0.
exception() noexcept;
Effects: Constructs an object of class exception.
exception(const exception& rhs) noexcept; exception& operator=(const exception& rhs) noexcept;
Effects: Copies an exception object.
Postconditions: If *this and rhs both have dynamic type exception then the value of the expression strcmp(what(), rhs.what()) shall equal 0.
virtual ~exception();
Effects: Destroys an object of class exception.
virtual const char* what() const noexcept;
Returns: An implementation-defined ntbs.
Remarks: The message may be a null-terminated multibyte string ([multibyte.strings]), suitable for conversion and display as a wstring ([string.classes], [locale.codecvt]).
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.

21.8.3 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;
    const char* what() const noexcept override;
  };
}
The class bad_­exception defines the type of the object referenced by the exception_­ptr returned from a call to current_­exception ([propagation]) when the currently active exception object fails to copy.
bad_exception() noexcept;
Effects: Constructs an object of class bad_­exception.
bad_exception(const bad_exception&) noexcept; bad_exception& operator=(const bad_exception&) noexcept;
Effects: Copies an object of class bad_­exception.
const char* what() const noexcept override;
Returns: An implementation-defined ntbs.
Remarks: The message may be a null-terminated multibyte string ([multibyte.strings]), suitable for conversion and display as a wstring ([string.classes], [locale.codecvt]).

21.8.4 Abnormal termination [exception.terminate]

21.8.4.1 Type terminate_­handler [terminate.handler]

using terminate_handler = void (*)();
The type of a handler function to be called by std​::​terminate() when terminating exception processing.
Required behavior: A terminate_­handler shall terminate execution of the program without returning to the caller.
Default behavior: The implementation's default terminate_­handler calls abort().

21.8.4.2 set_­terminate [set.terminate]

terminate_handler set_terminate(terminate_handler f) noexcept;
Effects: Establishes the function designated by f as the current handler function for terminating exception processing.
Remarks: It is unspecified whether a null pointer value designates the default terminate_­handler.
Returns: The previous terminate_­handler.

21.8.4.3 get_­terminate [get.terminate]

terminate_handler get_terminate() noexcept;
Returns: The current terminate_­handler.
[Note
:
This may be a null pointer value.
end note
]

21.8.4.4 terminate [terminate]

[[noreturn]] void terminate() noexcept;
Remarks: Called by the implementation when exception handling must be abandoned for any of several reasons ([except.terminate]).
May also be called directly by the program.
Effects: Calls a terminate_­handler function.
It is unspecified which terminate_­handler function will be called if an exception is active during a call to set_­terminate.
Otherwise calls the current terminate_­handler function.
[Note
:
A default terminate_­handler is always considered a callable handler in this context.
end note
]

21.8.5 uncaught_­exceptions [uncaught.exceptions]

int uncaught_exceptions() noexcept;
Returns: The number of uncaught exceptions ([except.uncaught]).
Remarks: When uncaught_­exceptions() > 0, throwing an exception can result in a call of
std​::​terminate() ([except.terminate]).

21.8.6 Exception propagation [propagation]

using exception_ptr = unspecified;
The type exception_­ptr can be used to refer to an exception object.
exception_­ptr shall satisfy the requirements of NullablePointer ([nullablepointer.requirements]).
Two non-null values of type exception_­ptr are equivalent and compare equal if and only if they refer to the same exception.
The default constructor of exception_­ptr produces the null value of the type.
exception_­ptr shall not be implicitly convertible to any arithmetic, enumeration, or pointer type.
[Note
:
An implementation might use a reference-counted smart pointer as exception_­ptr.
end note
]
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;
Returns: An exception_­ptr object that refers to the currently handled exception ([except.handle]) 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);
Requires: p shall not be a null pointer.
Throws: The exception object to which p refers.
template<class E> exception_ptr make_exception_ptr(E e) noexcept;
Effects: Creates an exception_­ptr object that refers to a copy of e, as if:
try {
  throw e;
} catch(...) {
  return current_exception();
}
[Note
:
This function is provided for convenience and efficiency reasons.
end note
]

21.8.7 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;
  };

  template<class T> [[noreturn]] void throw_with_nested(T&& t);
  template <class E> void rethrow_if_nested(const E& e);
}
The class nested_­exception is designed for use as a mixin through multiple inheritance.
It captures the currently handled exception and stores it for later use.
[Note
:
nested_­exception has a virtual destructor to make it a polymorphic class.
Its presence can be tested for with dynamic_­cast.
end note
]
nested_exception() noexcept;
Effects: The constructor calls current_­exception() and stores the returned value.
[[noreturn]] void rethrow_nested() const;
Effects: If nested_­ptr() returns a null pointer, the function calls std​::​terminate().
Otherwise, it throws the stored exception captured by *this.
exception_ptr nested_ptr() const noexcept;
Returns: The stored exception captured by this nested_­exception object.
template <class T> [[noreturn]] void throw_with_nested(T&& t);
Let U be decay_­t<T>.
Requires: U shall be CopyConstructible.
Throws: If is_­class_­v<U> && !is_­final_­v<U> && !is_­base_­of_­v<nested_­exception, U> is true, an exception of unspecified type that is publicly derived from both U and nested_­exception and constructed from std​::​forward<T>(t), otherwise std​::​forward<T>(t).
template <class E> void rethrow_if_nested(const E& e);
Effects: If E is not a polymorphic class type, or if nested_­exception is an inaccessible or ambiguous base class of E, there is no effect.
Otherwise, performs:
if (auto p = dynamic_cast<const nested_exception*>(addressof(e)))
  p->rethrow_nested();

21.9 Initializer lists [support.initlist]

The header <initializer_­list> defines a class template and several support functions related to list-initialization (see [dcl.init.list]).
All functions specified in this subclause are signal-safe ([csignal.syn]).

21.9.1 Header <initializer_­list> synopsis [initializer_list.syn]

namespace std {
  template<class E> class initializer_list {
  public:
    using value_type      = E;
    using reference       = const E&;
    using const_reference = const E&;
    using size_type       = size_t;

    using iterator        = const E*;
    using const_iterator  = const E*;

    constexpr initializer_list() noexcept;

    constexpr size_t size() const noexcept;     // number of elements
    constexpr const E* begin() const noexcept;  // first element
    constexpr const E* end() const noexcept;    // one past the last element
  };

  // [support.initlist.range], initializer list range access
  template<class E> constexpr const E* begin(initializer_list<E> il) noexcept;
  template<class E> constexpr const E* end(initializer_list<E> il) noexcept;
}
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 [dcl.init.list].
Copying an initializer list does not copy the underlying elements.
end note
]
If an explicit specialization or partial specialization of initializer_­list is declared, the program is ill-formed.

21.9.2 Initializer list constructors [support.initlist.cons]

constexpr initializer_list() noexcept;
Effects: Constructs an empty initializer_­list object.
Postconditions: size() == 0.

21.9.3 Initializer list access [support.initlist.access]

constexpr const E* begin() const noexcept;
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.
constexpr const E* end() const noexcept;
Returns: begin() + size().
constexpr size_t size() const noexcept;
Returns: The number of elements in the array.
Complexity: Constant time.

21.9.4 Initializer list range access [support.initlist.range]

template<class E> constexpr const E* begin(initializer_list<E> il) noexcept;
Returns: il.begin().
template<class E> constexpr const E* end(initializer_list<E> il) noexcept;
Returns: il.end().

21.10 Other runtime support [support.runtime]

Headers <csetjmp> (nonlocal jumps), <csignal> (signal handling), <cstdarg> (variable arguments), and <cstdlib> (runtime environment getenv, system), provide further compatibility with C code.
Calls to the function getenv ([cstdlib.syn]) shall not introduce a data race ([res.on.data.races]) provided that nothing modifies the environment.
[Note
:
Calls to the POSIX functions setenv and putenv modify the environment.
end note
]
A call to the setlocale function ([c.locales]) 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.

21.10.1 Header <cstdarg> synopsis [cstdarg.syn]

namespace std {
  using va_list = see below;
}

#define va_arg(V, P) see below
#define va_copy(VDST, VSRC) see below
#define va_end(V) see below
#define va_start(V, P) see below
The contents of the header <cstdarg> are the same as the C standard library header <stdarg.h>, with the following changes: The restrictions that ISO C places on the second parameter to the va_­start macro in header <stdarg.h> are different in this International Standard.
The parameter parmN is the rightmost parameter in the variable parameter list of the function definition (the one just before the ...).219
If the parameter parmN is a pack expansion ([temp.variadic]) or an entity resulting from a lambda capture ([expr.prim.lambda]), the program is ill-formed, no diagnostic required.
If the parameter parmN is of a reference type, or of 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 7.
16.
1.
1.
Note that va_­start is required to work as specified even if unary operator& is overloaded for the type of parmN.

21.10.2 Header <csetjmp> synopsis [csetjmp.syn]

namespace std {
  using jmp_buf = see below;
  [[noreturn]] void longjmp(jmp_buf env, int val);
}

#define setjmp(env) see below
The contents of the header <csetjmp> are the same as the C standard library header <setjmp.h>.
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.
13.

21.10.3 Header <csignal> synopsis [csignal.syn]

namespace std {
  using sig_atomic_t = see below;

  // [support.signal], signal handlers
  extern "C" using signal-handler = void(int);  // exposition only
  signal-handler* signal(int sig, signal-handler* func);

  int raise(int sig);
}

#define SIG_DFL see below
#define SIG_ERR see below
#define SIG_IGN see below
#define SIGABRT see below
#define SIGFPE see below
#define SIGILL see below
#define SIGINT see below
#define SIGSEGV see below
#define SIGTERM see below
The contents of the header <csignal> are the same as the C standard library header <signal.h>.

21.10.4 Signal handlers [support.signal]

A call to the function signal synchronizes with any resulting invocation of the signal handler so installed.
A plain lock-free atomic operation is an invocation of a function f from Clause [atomics], such that:
  • f is the function atomic_­is_­lock_­free(), or
  • f is the member function is_­lock_­free(), or
  • f is a non-static member function invoked on an object A, such that A.is_­lock_­free() yields true, or
  • f is a non-member function, and for every pointer-to-atomic argument A passed to f, atomic_­is_­lock_­free(A) yields true.
An evaluation is signal-safe unless it includes one of the following:
  • a call to any standard library function, except for plain lock-free atomic operations and functions explicitly identified as signal-safe.
    [Note
    :
    This implicitly excludes the use of new and delete expressions that rely on a library-provided memory allocator.
    end note
    ]
  • an access to an object with thread storage duration;
  • a dynamic_­cast expression;
  • throwing of an exception;
  • control entering a try-block or function-try-block;
  • initialization of a variable with static storage duration requiring dynamic initialization ([basic.start.dynamic], [stmt.dcl])220; or
  • waiting for the completion of the initialization of a variable with static storage duration ([stmt.dcl]).
A signal handler invocation has undefined behavior if it includes an evaluation that is not signal-safe.
The function signal is signal-safe if it is invoked with the first argument equal to the signal number corresponding to the signal that caused the invocation of the handler.
See also: ISO C 7.
14.
Such initialization might occur because it is the first odr-use ([basic.def.odr]) of that variable.

22 Diagnostics library [diagnostics]

22.1 General [diagnostics.general]

This Clause describes components that C++ programs may use to detect and report error conditions.
The following subclauses describe components for reporting several kinds of exceptional conditions, documenting program assertions, and a global variable for error number codes, as summarized in Table 33.
Table 33 — Diagnostics library summary
Subclause
Header(s)
Exception classes
<stdexcept>
Assertions
<cassert>
Error numbers
<cerrno>
System error support
<system_­error>

22.2 Exception classes [std.exceptions]

The C++ standard library provides classes to be used to report certain errors ([res.on.exception.handling]) in C++ programs.
In the error model reflected in these classes, errors are divided into two broad categories: logic errors and runtime errors.
The distinguishing characteristic of logic errors is that they are due to errors in the internal logic of the program.
In theory, they are preventable.
By contrast, runtime errors are due to events beyond the scope of the program.
They cannot be easily predicted in advance.
The header <stdexcept> defines several types of predefined exceptions for reporting errors in a C++ program.
These exceptions are related by inheritance.

22.2.1 Header <stdexcept> synopsis [stdexcept.syn]

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;
}

22.2.2 Class logic_­error [logic.error]

namespace std {
  class logic_error : public exception {
  public:
    explicit logic_error(const string& what_arg);
    explicit logic_error(const char* what_arg);
  };
}
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);
Effects: Constructs an object of class logic_­error.
Postconditions: strcmp(what(), what_­arg.c_­str()) == 0.
logic_error(const char* what_arg);
Effects: Constructs an object of class logic_­error.
Postconditions: strcmp(what(), what_­arg) == 0.

22.2.3 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);
  };
}
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);
Effects: Constructs an object of class domain_­error.
Postconditions: strcmp(what(), what_­arg.c_­str()) == 0.
domain_error(const char* what_arg);
Effects: Constructs an object of class domain_­error.
Postconditions: strcmp(what(), what_­arg) == 0.

22.2.4 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);
  };
}
The class invalid_­argument defines the type of objects thrown as exceptions to report an invalid argument.
invalid_argument(const string& what_arg);
Effects: Constructs an object of class invalid_­argument.
Postconditions: strcmp(what(), what_­arg.c_­str()) == 0.
invalid_argument(const char* what_arg);
Effects: Constructs an object of class invalid_­argument.
Postconditions: strcmp(what(), what_­arg) == 0.

22.2.5 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);
  };
}
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);
Effects: Constructs an object of class length_­error.
Postconditions: strcmp(what(), what_­arg.c_­str()) == 0.
length_error(const char* what_arg);
Effects: Constructs an object of class length_­error.
Postconditions: strcmp(what(), what_­arg) == 0.

22.2.6 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);
  };
}
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);
Effects: Constructs an object of class out_­of_­range.
Postconditions: strcmp(what(), what_­arg.c_­str()) == 0.
out_of_range(const char* what_arg);
Effects: Constructs an object of class out_­of_­range.
Postconditions: strcmp(what(), what_­arg) == 0.

22.2.7 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);
  };
}
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);
Effects: Constructs an object of class runtime_­error.
Postconditions: strcmp(what(), what_­arg.c_­str()) == 0.
runtime_error(const char* what_arg);
Effects: Constructs an object of class runtime_­error.
Postconditions: strcmp(what(), what_­arg) == 0.

22.2.8 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);
  };
}
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);
Effects: Constructs an object of class range_­error.
Postconditions: strcmp(what(), what_­arg.c_­str()) == 0.
range_error(const char* what_arg);
Effects: Constructs an object of class range_­error.
Postconditions: strcmp(what(), what_­arg) == 0.

22.2.9 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);
  };
}
The class overflow_­error defines the type of objects thrown as exceptions to report an arithmetic overflow error.