Doc No: N1804=05-0064 Date: 2005-04-27 Reply to: Pete Becker Dinkumware, Ltd. petebecker@acm.org Working Draft, Standard for Programming Language C++ Note: this is an early draft. It's known to be incomplet and incorrekt, and it has lots of ba d matting. for ii Draft Contents Contents iii List of Tables xi 1 General 1 1.1 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Normative references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.3 Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.4 Implementation compliance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.5 Structure of this International Standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.6 Syntax notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.7 The C++ memory model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.8 The C++ object model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.9 Program execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.10 Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2 Lexical conventions 11 2.1 Phases of translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2 Character sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 2.3 Trigraph sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.4 Preprocessing tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.5 Alternative tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.6 Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.7 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.8 Header names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.9 Preprocessing numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.10 Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.11 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2.12 Operators and punctuators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2.13 Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 3 Basic concepts 23 3.1 Declarations and definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 3.2 One definition rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 CONTENTS CONTENTS iv 3.3 Declarative regions and scopes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 3.4 Name lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.5 Program and linkage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 3.6 Start and termination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 3.7 Storage duration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 3.8 Object Lifetime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 3.9 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 3.10 Lvalues and rvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 4 Standard conversions 65 4.1 Lvalue-to-rvalue conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 4.2 Array-to-pointer conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 4.3 Function-to-pointer conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 4.4 Qualification conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 4.5 Integral promotions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 4.6 Floating point promotion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 4.7 Integral conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 4.8 Floating point conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 4.9 Floating-integral conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 4.10 Pointer conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 4.11 Pointer to member conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 4.12 Boolean conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 5 Expressions 71 5.1 Primary expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 5.2 Postfix expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 5.3 Unary expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 5.4 Explicit type conversion (cast notation) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 5.5 Pointer-to-member operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 5.6 Multiplicative operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 5.7 Additive operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 5.8 Shift operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 5.9 Relational operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 5.10 Equality operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 5.11 Bitwise AND operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 5.12 Bitwise exclusive OR operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 5.13 Bitwise inclusive OR operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 5.14 Logical AND operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 5.15 Logical OR operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 5.16 Conditional operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 5.17 Assignment and compound assignment operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 5.18 Comma operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 5.19 Constant expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 6 Statements 105 6.1 Labeled statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Draft v CONTENTS CONTENTS 6.2 Expression statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 6.3 Compound statement or block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 6.4 Selection statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 6.5 Iteration statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 6.6 Jump statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 6.7 Declaration statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 6.8 Ambiguity resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 7 Declarations 115 7.1 Specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 7.2 Enumeration declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 7.3 Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 7.4 The asm declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 7.5 Linkage specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 8 Declarators 145 8.1 Type names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 8.2 Ambiguity resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 8.3 Meaning of declarators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 8.4 Function definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 8.5 Initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 9 Classes 171 9.1 Class names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 9.2 Class members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 9.3 Member functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 9.4 Static members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 9.5 Unions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 9.6 Bit-fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 9.7 Nested class declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 9.8 Local class declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 9.9 Nested type names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 10 Derived classes 187 10.1 Multiple base classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 10.2 Member name lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 10.3 Virtual functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 10.4 Abstract classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 11 Member access control 201 11.1 Access specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 11.2 Accessibility of base classes and base class members . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 11.3 Access declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 11.4 Friends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 11.5 Protected member access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 11.6 Access to virtual functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 Draft CONTENTS CONTENTS vi 11.7 Multiple access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 11.8 Nested classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 12 Special member functions 215 12.1 Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 12.2 Temporary objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 12.3 Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 12.4 Destructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 12.5 Free store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 12.6 Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 12.7 Construction and destruction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 12.8 Copying class objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 13 Overloading 241 13.1 Overloadable declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 13.2 Declaration matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 13.3 Overload resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 13.4 Address of overloaded function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 13.5 Overloaded operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 13.6 Built-in operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 14 Templates 271 14.1 Template parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 14.2 Names of template specializations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 14.3 Template arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 14.4 Type equivalence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 14.5 Template declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 14.6 Name resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 14.7 Template instantiation and specialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 14.8 Function template specializations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 15 Exception handling 341 15.1 Throwing an exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 15.2 Constructors and destructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 15.3 Handling an exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 15.4 Exception specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 15.5 Special functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 15.6 Exceptions and access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 16 Preprocessing directives 353 16.1 Conditional inclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 16.2 Source file inclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 16.3 Macro replacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 16.4 Line control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 16.5 Error directive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 16.6 Pragma directive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 Draft vii CONTENTS CONTENTS 16.7 Null directive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 16.8 Predefined macro names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 17 Library introduction 363 17.1 Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 17.2 Additional definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 17.3 Method of description (Informative) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 17.4 Library-wide requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 18 Language support library 381 18.1 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 18.2 Implementation properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382 18.3 Start and termination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 18.4 Dynamic memory management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 18.5 Type identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 18.6 Exception handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 18.7 Other runtime support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 19 Diagnostics library 407 19.1 Exception classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 19.2 Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 19.3 Error numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 20 General utilities library 413 20.1 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 20.2 Utility components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417 20.3 Function objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 20.4 Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429 20.5 Date and time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437 21 Strings library 439 21.1 Character traits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439 21.2 String classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444 21.3 Class template basic_string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446 21.4 Null-terminated sequence utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472 22 Localization library 477 22.1 Locales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477 22.2 Standard locale categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487 22.3 C Library Locales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528 23 Containers library 531 23.1 Container requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531 23.2 Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540 23.3 Associative containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565 24 Iterators library 589 Draft CONTENTS CONTENTS viii 24.1 Iterator requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589 24.2 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594 24.3 Iterator primitives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597 24.4 Predefined iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600 24.5 Stream iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611 25 Algorithms library 619 25.1 Non-modifying sequence operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629 25.2 Mutating sequence operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632 25.3 Sorting and related operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 640 25.4 C library algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652 26 Numerics library 655 26.1 Numeric type requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655 26.2 Complex numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656 26.3 Numeric arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664 26.4 Generalized numeric operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686 26.5 C Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689 27 Input/output library 693 27.1 Iostreams requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693 27.2 Forward declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693 27.3 Standard iostream objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 696 27.4 Iostreams base classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698 27.5 Stream buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 716 27.6 Formatting and manipulators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726 27.7 String-based streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751 27.8 File-based streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760 A Grammar summary 773 A.1 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773 A.2 Lexical conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773 A.3 Basic concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777 A.4 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777 A.5 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 780 A.6 Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781 A.7 Declarators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 784 A.8 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785 A.9 Derived classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786 A.10 Special member functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786 A.11 Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787 A.12 Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787 A.13 Exception handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 788 A.14 Preprocessing directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 788 B Implementation quantities 791 Draft ix CONTENTS CONTENTS C Compatibility 793 C.1 C++ and ISO C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793 C.2 Standard C library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803 D Compatibility features 809 D.1 Increment operator with bool operand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809 D.2 static keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809 D.3 Access declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809 D.4 Implicit conversion from const strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809 D.5 Standard C library headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809 D.6 Old iostreams members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810 D.7 char* streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811 E Universal-character-names 823 Index 825 Draft CONTENTS CONTENTS x Draft List of Tables 1 trigraph sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2 alternative tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 3 keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 4 alternative representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 5 escape sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 6 relations on const and volatile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 7 simple-type-specifiers and the types they specify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 8 relationship between operator and function call notation . . . . . . . . . . . . . . . . . . . . . . . . . . 250 9 conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 10 Library Categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 11 C++ Library Headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 12 C++ Headers for C Library Facilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 13 C++ Headers for Freestanding Implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 14 Language support library summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 15 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382 16 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 17 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 18 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 19 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 20 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 21 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 22 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 23 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 24 Diagnostics library summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 25 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 26 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 27 General utilities library summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 LIST OF TABLES LIST OF TABLES xii 28 EqualityComparable requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 29 LessThanComparable requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414 30 CopyConstructible requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414 31 Swappable requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414 32 Descriptive variable definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 33 Allocator requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 34 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436 35 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436 36 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437 37 Strings library summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439 38 Traits requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440 39 basic_string(const Allocator&) effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451 40 basic_string(basic_string, size_type, size_type, const Allocator&) effects . . . . . 452 41 basic_string(const charT*, size_type, const Allocator&) effects . . . . . . . . . . . . . 452 42 basic_string(const charT*, const Allocator&) effects . . . . . . . . . . . . . . . . . . . . . 453 43 basic_string(size_t, charT, const Allocator&) effects . . . . . . . . . . . . . . . . . . . . 453 44 operator=(const basic_string&) effects . . . . . . . . . . . . 453 45 compare() results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466 46 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472 47 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472 48 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472 49 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473 50 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473 51 Localization library summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477 52 Locale Category Facets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 53 Required Specializations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482 54 do_in/do_out result values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497 55 do_unshift result values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498 56 Integer Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501 57 Length Modifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502 58 Integer Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506 59 Floating-point Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506 60 Length Modifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506 61 Numeric conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506 62 Fill padding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507 63 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529 64 Containers library summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531 65 Assignable requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531 66 Container requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532 67 Reversible container requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534 68 Sequence requirements (in addition to container) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535 69 Optional sequence operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537 70 Associative container requirements (in addition to container) . . . . . . . . . . . . . . . . . . . . . . . 538 Draft xiii LIST OF TABLES LIST OF TABLES 71 Iterators library summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589 72 Relations among iterator categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589 73 Input iterator requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591 74 Output iterator requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591 75 Forward iterator requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592 76 Bidirectional iterator requirements (in addition to forward iterator) . . . . . . . . . . . . . . . . . . . . 593 77 Random access iterator requirements (in addition to bidirectional iterator) . . . . . . . . . . . . . . . . 594 78 Algorithms library summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619 79 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652 80 Numerics library summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655 81 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689 82 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689 83 Input/output library summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693 84 fmtflags effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703 85 fmtflags constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703 86 iostate effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703 87 openmode effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703 88 seekdir effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 704 89 Position type requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 709 90 basic_ios::init() effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711 91 seekoff positioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755 92 newoff values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755 93 File open modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763 94 seekoff effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766 95 Header synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 771 96 Standard Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803 97 Standard Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804 98 Standard Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804 99 Standard Structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804 100 Standard Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805 101 C Headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809 102 strstreambuf(streamsize) effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813 103 strstreambuf(void* (*)(size_t), void (*)(void*)) effects . . . . . . . . . . . . . . . . . . 814 104 strstreambuf(charT*, streamsize, charT*) effects . . . . . . . . . . . . . . . . . . . . . . . . 814 105 seekoff positioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 817 106 newoff values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 817 Draft LIST OF TABLES LIST OF TABLES xiv Draft Chapter 1 General [intro] 1.1 Scope [intro.scope] 1 This International Standard specifies requirements for implementations of the C++ programming language. The first such requirement is that they implement the language, and so this International Standard also defines C++. Other requirements and relaxations of the first requirement appear at various places within this International Standard. 2 C++ is a general purpose programming language based on the C programming language as described in ISO/IEC 9899:1990 Programming languages - C (1.2). In addition to the facilities provided by C, C++ provides additional data types, classes, templates, exceptions, namespaces, inline functions, operator overloading, function name overloading, references, free store management operators, and additional library facilities. 1.2 Normative references [intro.refs] 1 The following standards contain provisions which, through reference in this text, constitute provisions of this Interna- tional Standard. At the time of publication, the editions indicated were valid. All standards are subject to revision, and parties to agreements based on this International Standard are encouraged to investigate the possibility of applying the most recent editions of the standards indicated below. Members of IEC and ISO maintain registers of currently valid International Standards. -- ISO/IEC 2382 (all parts), Information technology - Vocabulary -- ISO/IEC 9899:1990, Programming languages - C -- ISO/IEC 9899/Amd.1:1995, Programming languages - C, AMENDMENT 1: C Integrity -- ISO/IEC 10646-1:1993 Information technology - Universal Multiple-Octet Coded Character Set (UCS) - Part 1: Architecture and Basic Multilingual Plane 2 The library described in clause 7 of ISO/IEC 9899:1990 and clause 7 of ISO/IEC 9899/Amd.1:1995 is hereinafter called the Standard C Library.1) 1.3 Definitions [intro.defs] 1 For the purposes of this International Standard, the definitions given in ISO/IEC 2382 and the following definitions apply. 17.1 defines additional terms that are used only in clauses 17 through 27 and Annex D. 1) With the qualifications noted in clauses 17 through 27, and in C.2, the Standard C library is a subset of the Standard C++ library. 1.3 Definitions General 2 2 Terms that are used only in a small portion of this International Standard are defined where they are used and italicized where they are defined. 1.3.1 argument [defns.argument] an expression in the comma-separated list bounded by the parentheses in a function call expression, a sequence of preprocessing tokens in the comma-separated list bounded by the parentheses in a function-like macro invocation, the operand of throw, or an expression, type-id or template-name in the comma-separated list bounded by the angle brackets in a template instantiation. Also known as an actual argument or actual parameter. 1.3.2 conditionally-supported [defns.cond.supp] a 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 ] 1.3.3 diagnostic message [defns.diagnostic] a message belonging to an implementation-defined subset of the implementation's output messages. 1.3.4 dynamic type [defns.dynamic.type] the type of the most derived object (1.8) to which the lvalue denoted by an lvalue expression refers. [ Example: if a pointer (8.3.1) p whose static type is "pointer to class B" is pointing to an object of class D, derived from B (clause 10), the dynamic type of the expression *p is "D." References (8.3.2) are treated similarly. -- end example ] The dynamic type of an rvalue expression is its static type. 1.3.5 ill-formed program [defns.ill.formed] input to a C++ implementation that is not a well-formed program (1.3.15). 1.3.6 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. 1.3.7 implementation limits [defns.impl.limits] restrictions imposed upon programs by the implementation. 1.3.8 locale-specific behavior [defns.locale.specific] behavior that depends on local conventions of nationality, culture, and language that each implementation documents. 1.3.9 multibyte character [defns.multibyte] a sequence of one or more bytes representing a member of the extended character set of either the source or the execution environment. The extended character set is a superset of the basic character set (2.2). 1.3.10 parameter [defns.parameter] an 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; an identifier from the comma-separated list bounded Draft 3 General 1.4 Implementation compliance by the parentheses immediately following the macro name in a function-like macro definition; or a template-parameter. Parameters are also known as formal arguments or formal parameters. 1.3.11 signature [defns.signature] the information about a function that participates in overload resolution (13.3): its parameter-type-list (8.3.5) and, if the function is a class member, the cv- qualifiers (if any) on the function itself and the class in which the member function is declared.2) The signature of a function template specialization includes the types of its template arguments (14.5.5.1). 1.3.12 static type [defns.static.type] the type of an expression (3.9), which type results from analysis of the program without considering execution semantics. 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. 1.3.13 undefined behavior [defns.undefined] behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements. Undefined behavior may also be expected when this International Standard omits the description of any explicit definition of behavior. [ Note: 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 trans- lation or execution (with the issuance of a diagnostic message). Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed. -- end note ] 1.3.14 unspecified behavior [defns.unspecified] behavior, for a well-formed program construct and correct data, that depends on the implementation. The implementa- tion is not required to document which behavior occurs. [ Note: usually, the range of possible behaviors is delineated by this International Standard. -- end note ] 1.3.15 well-formed program [defns.well.formed] a C++ program constructed according to the syntax rules, diagnosable semantic rules, and the One Definition Rule (3.2). 1.4 Implementation compliance [intro.compliance] 1 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." 2 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 execute3) that program. 2) Function signatures do not include return type, because that does not participate in overload resolution. 3) "Correct execution" can include undefined behavior, depending on the data being processed; see 1.3 and 1.9. Draft 1.5 Structure of this International Standard General 4 -- If a program contains a violation of any diagnosable rule or an occurrence of a construct described in this Standard as "conditionally-supported" when the implementation does not support that construct, a conforming implemen- tation shall issue at least one diagnostic message, except that -- 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. 3 For classes and class templates, the library clauses specify partial definitions. Private members (clause 11) are not specified, but each implementation shall supply them to complete the definitions according to the description in the library clauses. 4 For functions, function templates, objects, and values, the library clauses specify declarations. Implementations shall supply definitions consistent with the descriptions in the library clauses. 5 The names defined in the library have namespace scope (7.3). A C++ translation unit (2.1) obtains access to these names by including the appropriate standard library header (16.2). 6 The templates, classes, functions, and objects in the library have external linkage (3.5). The implementation provides definitions for standard library entities, as necessary, while combining translation units to form a complete C++ program (2.1). 7 Two kinds of implementations are defined: hosted and freestanding. 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 (17.4.1.3). 8 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. 9 Each implementation shall include documentation that identifies all conditionally-supported constructs that it does not support and defines all locale-specific characteristics.4) 1.5 Structure of this International Standard [intro.structure] 1 Clauses 2 through 16 describe the C++ programming language. That description includes detailed syntactic specifications in a form described in 1.6. For convenience, Annex A repeats all such syntactic specifications. 2 Clauses 17 through 27 and Annex D (the library clauses) describe the Standard C++ library, which provides definitions for the following kinds of entities: macros (16.3), values (clause 3), types (8.1, 8.3), templates (clause 14), classes (clause 9), functions (8.3.5), and objects (clause 7). 3 Annex B recommends lower bounds on the capacity of conforming implementations. 4 Annex C 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 D describes those features. 5 Finally, Annex E says what characters are valid in universal-character names in C++ identifiers (2.10). 4) This documentation also defines implementation-defined behavior; see 1.9. Draft 5 General 1.6 Syntax notation 6 Throughout this International Standard, each example is introduced by "[ Example:" and terminated by " -- end exam- ple ]". Each note is introduced by "[ Note:" and terminated by " -- end note ]". Examples and notes may be nested. 1.6 Syntax notation [syntax] 1 In the syntax notation used in this International Standard, 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 presented on one line, marked by the phrase "one of." An optional terminal or nonterminal symbol is indicated by the subscript "opt ", so { expression opt } indicates an optional expression enclosed in braces. 2 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. expression-list is a sequence of expressions separated by commas). 1.7 The C++ memory model [intro.memory] 1 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 and is composed of a contiguous sequence of bits, 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. 2 [ Note: the representation of types is described in 3.9. -- end note ] 1.8 The C++ object model [intro.object] 1 The constructs in a C++ program create, destroy, refer to, access, and manipulate objects. An object is a region of storage. [ Note: A function is not an object, regardless of whether or not it occupies storage in the way that objects do. -- end note ] An object is created by a definition (3.1), by a new-expression (5.3.4) or by the implementation (12.2) when needed. The properties of an object are determined when the object is created. An object can have a name (clause 3). An object has a storage duration (3.7) which influences its lifetime (3.8). An object has a type (3.9). The term object type refers to the type with which the object is created. Some objects are polymorphic (10.3); 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 5) used to access them. 2 Objects can contain other objects, called subobjects. A subobject can be a member subobject (9.2), a base class subobject (clause 10), or an array element. An object that is not a subobject of any other object is called a complete object. 3 For every object x, there is some object called the complete object of x, determined as follows: -- If x is a complete object, then x is the complete object of x. Draft 1.9 Program execution General 6 -- Otherwise, the complete object of x is the complete object of the (unique) object that contains x. 4 If a complete object, a data member (9.2), 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 is called a most derived object. 5 Unless it is a bit-field (9.6), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class subobjects may have zero size. An object of POD5) type (3.9) shall occupy contiguous bytes of storage. 6 [ Note: C++ provides a variety of built-in types and several ways of composing new types from existing types (3.9). -- end note ] 1.9 Program execution [intro.execution] 1 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) 2 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). 3 Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, order of evaluation of arguments to a function). 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 sequence for a given program and a given input. 4 Certain other operations are described in this International Standard as undefined (for example, the effect of derefer- encing the null pointer). [ Note: this International Standard imposes no requirements on the behavior of programs that contain undefined behavior. -- end note ] 5 A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible execution sequences of the corresponding instance of the abstract machine with the same program and the same input. However, if any such execution sequence 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). 6 The observable behavior of the abstract machine is its sequence of reads and writes to volatile data and calls to library I/O functions.8) 5) The acronym POD stands for "plain old data." 6) 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. 7) This documentation also includes conditonally-supported constructs and locale-specific behavior. See 1.4. 8) An implementation can offer additional library I/O functions as an extension. Implementations that do so should treat calls to those functions as Draft 7 General 1.9 Program execution 7 Accessing an object designated by a volatile lvalue (3.10), 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 might produce side effects. At certain specified points in the execution se- quence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place.9) 8 Once the execution of a function begins, no expressions from the calling function are evaluated until execution of the called function has completed.10) 9 When the processing of the abstract machine is interrupted by receipt of a signal, the values of objects with type other than volatile std::sig_atomic_t are unspecified, and the value of any object not of volatile std::sig_- atomic_t that is modified by the handler becomes undefined. 10 An instance of each object with automatic storage duration (3.7.2) 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). 11 The least requirements on a conforming implementation are: -- At sequence points, volatile objects are stable in the sense that previous evaluations are complete and subsequent evaluations have not yet occurred. -- 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 messages actually appear prior to a program waiting for input. What constitutes an interactive device is implementation- defined. [ Note: more stringent correspondences between abstract and actual semantics may be defined by each implementation. -- end note ] 12 A full-expression is an expression that is not a subexpression of another expression. 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. [ Example: struct S { S ( int i ): I ( i ) { } int & v () { return I ; } private : int I ; }; S s1 (1); / / full-expression is call of S::S(int) S s2 = 2; / / full-expression is call of S::S(int) "observable behavior" as well. 9) Note that some aspects of sequencing in the abstract machine are unspecified; the preceding restriction upon side effects applies to that particular execution sequence in which the actual code is generated. Also note that when a call to a library I/O function returns, the side effect is considered complete, even though some external actions implied by the call (such as the I/O itself) may not have completed yet. 10) In other words, function executions do not "interleave" with each other. Draft 1.9 Program execution General 8 void f () { 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 { } } -- end example ] 13 [ 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 argument expressions (8.3.6) are considered to be created in the expression that calls the function, not the expression that defines the default argument. -- end note ] 14 [ Note: operators can be regrouped according to the usual mathematical rules only where the operators really are asso- ciative or commutative.11) 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 over- flows 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 ] 15 There is a sequence point at the completion of evaluation of each full-expression12) . 16 When calling a function (whether or not the function is inline), there is a sequence point after the evaluation of all function arguments (if any) which takes place before execution of any expressions or statements in the function body. 11)Overloaded operators are never assumed to be associative or commutative. 12)As specified in 12.2, after the "end-of-full-expression" sequence point, 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. Draft 9 General 1.10 Acknowledgments There is also a sequence point after the copying of a returned value and before the execution of any expressions outside the function13) . 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 5.3.4. For another example, invocation of a conversion function (12.3.2) can arise in contexts in which no function call syntax appears. -- end example ] The sequence points at function-entry and function-exit (as described above) are features of the function calls as evaluated, whatever the syntax of the expression that calls the function might be. 17 In the evaluation of each of the expressions a && b a || b a ? b : c a , b using the built-in meaning of the operators in these expressions (5.14, 5.15, 5.16, 5.18), there is a sequence point after the evaluation of the first expression14) . 1.10 Acknowledgments [intro.ack] 1 The C++ programming language as described in this International Standard is based on the language as described in Chapter R (Reference Manual) of Stroustrup: The C++ Programming Language (second edition, Addison-Wesley Pub- lishing Company, ISBN 0-201-53992-6, copyright c 1991 AT&T). That, in turn, is based on the C programming lan- guage as described in Appendix A of Kernighan and Ritchie: The C Programming Language (Prentice-Hall, 1978, ISBN 0-13-110163-3, copyright c 1978 AT&T). 2 Portions of the library clauses of this International Standard 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 c 1995 P.J. Plauger). 3 All rights in these originals are reserved. 13) The sequence point at the function return is not explicitly specified in ISO C, and can be considered redundant with sequence points at full- expressions, but the extra clarity is important in C++ . In C++ , there are more ways in which a called function can terminate its execution, such as the throw of an exception. 14) The operators indicated in this paragraph are the built-in operators, as described in clause 5. When one of these operators is overloaded (clause 13) in a valid context, thus designating a user-defined operator function, the expression designates a function invocation, and the operands form an argument list, without an implied sequence point between them. Draft 1.10 Acknowledgments General 10 Draft Chapter 2 Lexical conventions [lex] 1 The text of the program is kept in units called source files in this International Standard. A source file together with all the headers (17.4.1.2) and source files included (16.2) via the preprocessing directive #include, less any source lines skipped by any of the conditional inclusion (16.1) preprocessing directives, is called a translation unit. [ Note: a C++ program need not all be translated at the same time. -- end note ] 2 [ Note: previously translated translation units and instantiation units can be preserved individually or in libraries. The separate translation units of a program communicate (3.5) by (for example) calls to functions whose identifiers have ex- ternal 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 (3.5). -- end note ] 2.1 Phases of translation [lex.phases] 1 The precedence among the syntax rules of translation is specified by the following phases.15) 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. Trigraph sequences (2.3) are replaced by corresponding single-character internal representations. Any source file character not in the basic source character set (2.2) 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 (i.e. using the \uXXXX notation), are handled equivalently.) 2. Each instance of a new-line character and an immediately preceding backslash character is deleted, splicing phys- ical source lines to form logical source lines. If, as a result, a character sequence that matches the syntax of a universal-character-name is produced, the behavior is undefined. If a source file that is not empty does not end in a new-line character, or ends in a new-line character immediately preceded by a backslash character, the behavior is undefined. 3. The source file is decomposed into preprocessing tokens (2.4) and sequences of white-space characters (including comments). A source file shall not end in a partial preprocessing token or partial comment.16) 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 implementation-defined. 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 ] 15) Implementations must behave as if these separate phases occur, although in practice different phases might be folded together. 16) 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. 2.2 Character sets Lexical conventions 12 4. Preprocessing directives are executed and macro invocations are expanded. If a character sequence that matches the syntax of a universal-character-name is produced by token concatenation (16.3.3), 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. 5. Each source character set member, escape sequence, or universal-character-name in character literals and string literals is converted to a member of the execution character set (2.13.2, 2.13.4). 6. Adjacent ordinary string literal tokens are concatenated. Adjacent wide string literal tokens are concatenated. 7. White-space characters separating tokens are no longer significant. Each preprocessing token is converted into a token. (2.6). The resulting tokens are syntactically and semantically analyzed and translated. [ 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. 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 (14.7.2). -- 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. All external object and function references are resolved. Library components are linked to satisfy external refer- ences to functions and objects 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. 2.2 Character sets [lex.charset] 1 The basic source character set consists of 96 characters: the space character, the control characters representing hori- zontal tab, vertical tab, form feed, and new-line, plus the following 91 graphical characters:17) 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 _ { } [ ] # ( ) < > % : ; . ? * + - / ^ & | ! = , \ " ' 2 The universal-character-name construct provides a way to name other characters. hex-quad: hexadecimal-digit hexadecimal-digit hexadecimal-digit hexadecimal-digit 17) 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. Draft 13 Lexical conventions 2.3 Trigraph sequences 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 is less than 0x20 or in the range 0x7F-0x9F (inclusive), or if the universal character name designates a character in the basic source character set, then the program is ill-formed. 3 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 representation has all zero bits. 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 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 are implementation-defined, and any additional members are locale-specific. 2.3 Trigraph sequences [lex.trigraph] 1 Before any other processing takes place, each occurrence of one of the following sequences of three characters ("trigraph sequences") is replaced by the single character indicated in Table 1. Table 1: trigraph sequences trigraph replacement trigraph replacement trigraph replacement ??= # ??( [ ??< { ??/ \ ??) ] ??> } ??' ^ ??! | ??- 2 [ Example: ??= define arraycheck (a , b ) a ??( b ??) ??!??! b ??( a ??) becomes # define arraycheck (a , b ) a [ b ] || b [ a ] -- end example ] 3 No other trigraph sequence exists. Each ? that does not begin one of the trigraphs listed above is not changed. Draft 2.4 Preprocessing tokens Lexical conventions 14 2.4 Preprocessing tokens [lex.pptoken] preprocessing-token: header-name identifier pp-number character-literal string-literal preprocessing-op-or-punc each non-white-space character that cannot be one of the above 1 Each preprocessing token that is converted to a token (2.6) shall have the lexical form of a keyword, an identifier, a literal, an operator, or a punctuator. 2 A preprocessing token is the minimal lexical element of the language in translation phases 3 through 6. The cate- gories of preprocessing token are: header names, identifiers, preprocessing numbers, character literals, string literals, preprocessing-op-or-punc, 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 (2.7), or white-space characters (space, horizontal tab, new-line, vertical tab, and form-feed), or both. As described in clause 16, 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. 3 If the input stream has been parsed into preprocessing tokens up to a given character, 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. 4 [ Example: The program fragment 1Ex is parsed as a preprocessing number token (one that is not a valid floating or integer literal token), even though a parse as the pair of preprocessing tokens 1 and Ex might produce a valid expression (for example, if Ex 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 ] 5 [ Example: The program fragment x+++++y is parsed as x ++ ++ + y, which, if x and y are of built-in types, violates a constraint on increment operators, even though the parse x ++ + ++ y might yield a correct expression. -- end example ] 2.5 Alternative tokens [lex.digraph] 1 Alternative token representations are provided for some operators and punctuators.18) 2 In all respects of the language, each alternative token behaves the same, respectively, as its primary token, except for its Draft 15 Lexical conventions 2.6 Tokens Table 2: alternative tokens alternative primary alternative primary alternative primary <% { and && and_eq &= %> } bitor | or_eq |= <: [ or || xor_eq ^= :> ] xor ^ not ! %: # compl not_eq != %:%: ## bitand & spelling.19) The set of alternative tokens is defined in Table 2. 2.6 Tokens [lex.token] token: identifier keyword literal operator punctuator 1 There are five kinds of tokens: identifiers, keywords, literals,20) 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 ] 2.7 Comments [lex.comment] 1 The characters /* start a comment, which terminates with the characters */. These comments do not nest. The characters // start a comment, which terminates with 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 ] 2.8 Header names [lex.header] header-name: < h-char-sequence > " q-char-sequence " h-char-sequence: h-char h-char-sequence h-char 18) 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". 19) Thus the "stringized" values (16.3.2) of [ and <: will be different, maintaining the source spelling, but the tokens can otherwise be freely interchanged. 20) Literals include strings and character and numeric literals. Draft 2.9 Preprocessing numbers Lexical conventions 16 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 " 1 Header name preprocessing tokens shall only appear within a #include preprocessing directive (16.2). 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 16.2. 2 If either of the characters ' or \, or either of the character sequences /* or // appears in a q-char-sequence or a h-char-sequence, or the character " appears in a h-char-sequence, the behavior is undefined.21) 2.9 Preprocessing numbers [lex.ppnumber] pp-number: digit . digit pp-number digit pp-number nondigit pp-number e sign pp-number E sign pp-number . 1 Preprocessing number tokens lexically include all integral literal tokens (2.13.1) and all floating literal tokens (2.13.3). 2 A preprocessing number does not have a type or a value; it acquires both after a successful conversion (as part of translation phase 7, 2.1) to an integral literal token or a floating literal token. 2.10 Identifiers [lex.name] identifier: nondigit identifier nondigit identifier digit nondigit: one of universal-character-name 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 1 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 Annex E. Upper- and lower-case letters are different. All characters are significant.22) 21) Thus, sequences of characters that resemble escape sequences cause undefined behavior. 22) On systems in which linkers cannot accept extended characters, an encoding of the universal-character-name may be used in forming valid Draft 17 Lexical conventions 2.11 Keywords 2 In addition, some identifiers are reserved for use by C++ implementations and standard libraries (17.4.3.1.2) and shall not be used otherwise; no diagnostic is required. 2.11 Keywords [lex.key] 1 The identifiers shown in Table 3 are reserved for use as keywords (that is, they are unconditionally treated as keywords in phase 7): Table 3: keywords asm do if return try auto double inline short typedef bool dynamic_cast int signed typeid break else long sizeof typename case enum mutable static union catch explicit namespace static_assert unsigned char export new static_cast using class extern operator struct virtual const false private switch void const_cast float protected template volatile continue for public this wchar_t default friend register throw while delete goto reinterpret_cast true 2 Furthermore, the alternative representations shown in Table 4 for certain operators and punctuators (2.5) are reserved and shall not be used otherwise: Table 4: alternative representations and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq 2.12 Operators and punctuators [lex.operators] 1 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: 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. Draft 2.13 Literals Lexical conventions 18 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 (2.1). 2.13 Literals [lex.literal] 1 There are several kinds of literals.23) literal: integer-literal character-literal floating-literal string-literal boolean-literal 2.13.1 Integer literals [lex.icon] integer-literal: decimal-literal integer-suffixopt octal-literal integer-suffixopt hexadecimal-literal integer-suffixopt decimal-literal: nonzero-digit decimal-literal digit octal-literal: 0 octal-literal octal-digit hexadecimal-literal: 0x hexadecimal-digit 0X hexadecimal-digit hexadecimal-literal hexadecimal-digit nonzero-digit: one of 1 2 3 4 5 6 7 8 9 octal-digit: one of 0 1 2 3 4 5 6 7 hexadecimal-digit: one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F 23) The term "literal" generally designates, in this International Standard, those tokens that are called "constants" in ISO C. Draft 19 Lexical conventions 2.13 Literals integer-suffix: unsigned-suffix long-suffixopt long-suffix unsigned-suffixopt unsigned-suffix: one of u U long-suffix: one of l L 1 An integer literal is a sequence of digits that has no period or exponent part. 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 decimal integer literal (base ten) begins with a digit other than 0 and consists of a sequence of decimal digits. An octal integer literal (base eight) begins with the digit 0 and consists of a sequence of octal digits.24) 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, or 0XC. -- end example ] 2 The type of an integer literal depends on its form, value, and suffix. If it is decimal and has no suffix, it has the first of these types in which its value can be represented: int, long int; if the value cannot be represented as a long int, the behavior is undefined. If it is octal or hexadecimal and has no suffix, it has the first of these types in which its value can be represented: int, unsigned int, long int, unsigned long int. If it is suffixed by u or U, its type is the first of these types in which its value can be represented: unsigned int, unsigned long int. If it is suffixed by l or L, its type is the first of these types in which its value can be represented: long int, unsigned long int. If it is suffixed by ul, lu, uL, Lu, Ul, lU, UL, or LU, its type is unsigned long int. 3 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. 2.13.2 Character literals [lex.ccon] character-literal: ' c-char-sequence ' L' c-char-sequence ' c-char-sequence: c-char c-char-sequence c-char c-char: any member of the source character set except the single-quote ', backslash \, or new-line character escape-sequence universal-character-name escape-sequence: simple-escape-sequence octal-escape-sequence hexadecimal-escape-sequence simple-escape-sequence: one of \' \" \? \\ \a \b \f \n \r \t \v 24) The digits 8 and 9 are not octal digits. Draft 2.13 Literals Lexical conventions 20 octal-escape-sequence: \ octal-digit \ octal-digit octal-digit \ octal-digit octal-digit octal-digit hexadecimal-escape-sequence: \x hexadecimal-digit hexadecimal-escape-sequence hexadecimal-digit 1 A character literal is one or more characters enclosed in single quotes, as in 'x', optionally preceded by the letter L, as in L'x'. A character literal that does not begin with L is an ordinary character literal, also referred to as a narrow-character literal. An ordinary character literal that contains a single c-char 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 has type int and implementation-defined value. 2 A character literal that begins with the letter L, such as L'x', is a wide-character literal. A wide-character literal has type wchar_t.25) 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. The value of a wide-character literal containing multiple c-chars is implementation-defined. 3 Certain nongraphic characters, the single quote ', the double quote ", the question mark ?, and the backslash \, can be represented according to Table 5. 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. If the character following a backslash is not one of those specified, the behavior is undefined. An escape sequence specifies a single character. Table 5: 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 4 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 ordinary literals) or wchar_t (for wide literals). 25) They are intended for character sets where a character does not fit into a single byte. Draft 21 Lexical conventions 2.13 Literals 5 A universal-character-name is translated to the encoding, in the 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 ] 2.13.3 Floating literals [lex.fcon] floating-literal: fractional-constant exponent-partopt floating-suffixopt digit-sequence exponent-part floating-suffixopt fractional-constant: digit-sequenceopt . digit-sequence digit-sequence . exponent-part: e signopt digit-sequence E signopt digit-sequence sign: one of + - digit-sequence: digit digit-sequence digit floating-suffix: one of f l F L 1 A floating literal consists of an integer part, a decimal point, a fraction part, an e or E, 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. Either the integer part or the fraction part (not both) can be omitted; either the decimal point or the letter e (or E ) and the exponent (not both) can be omitted. The integer part, the optional decimal point and the optional fraction part form the significant part of the floating literal. The exponent, if present, indicates the power of 10 by which the significant part is to be scaled. 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. 2.13.4 String literals [lex.string] string-literal: "s-char-sequenceopt " L"s-char-sequenceopt " s-char-sequence: s-char s-char-sequence s-char Draft 2.13 Literals Lexical conventions 22 s-char: any member of the source character set except the double-quote ", backslash \, or new-line character escape-sequence universal-character-name 1 A string literal is a sequence of characters (as defined in 2.13.2) surrounded by double quotes, optionally beginning with the letter L, as in "..." or L"...". A string literal that does not begin with L is an ordinary string literal, also referred to as a narrow string literal. An ordinary string literal has type "array of n const char" and static storage duration (3.7), where n is the size of the string as defined below, and 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" and has static storage duration, where n is the size of the string as defined below, and is initialized with the given characters. 2 Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined. The effect of attempting to modify a string literal is undefined. 3 In translation phase 6 (2.1), adjacent narrow string literals are concatenated and adjacent wide string literals are concate- nated. If a narrow string literal token is adjacent to a wide string literal token, the behavior is undefined. 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 ] 4 After any necessary concatenation, in translation phase 7 (2.1), '\0' is appended to every string literal so that programs that scan a string can find its end. 5 Escape sequences and universal-character-names in string literals have the same meaning as in character literals (2.13.2), except that the single quote ' is representable either by itself or by the escape sequence \', and the double quote " shall be preceded by a \. 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 wide string literal is the total number of escape sequences, universal-character-names, and other characters, plus one for the terminating L'\0'. 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'. 2.13.5 Boolean literals [lex.bool] boolean-literal: false true 1 The Boolean literals are the keywords false and true. Such literals have type bool. They are not lvalues. Draft Chapter 3 Basic concepts [basic] 1 [ 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 notion of an lvalue. 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. 2 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 ] 3 An entity is a value, object, subobject, base class subobject, array element, variable, function, instance of a function, enumerator, type, class member, template, or namespace. 4 A name is a use of an identifier (2.10) that denotes an entity or label (6.6.4, 6.1). A variable is introduced by the declaration of an object. The variable's name denotes the object. 5 Every name that denotes an entity is introduced by a declaration. Every name that denotes a label is introduced either by a goto statement (6.6.4) or a labeled-statement (6.1). 6 Some names denote types, classes, enumerations, or templates. In general, it is necessary to determine whether or not a name denotes one of these entities before parsing the program that contains it. The process that determines this is called name lookup (3.4). 7 Two names are the same if -- they are identifiers composed of the same character sequence; or -- they are the names of overloaded operator functions formed with the same operator; or -- they are the names of user-defined conversion functions formed with the same type. 8 An identifier used in more than one translation unit can potentially refer to the same entity in these translation units depending on the linkage (3.5) of the identifier specified in each translation unit. 3.1 Declarations and definitions [basic.def] 1 A declaration (clause 7) introduces names into a translation unit or redeclares names introduced by previous declarations. A declaration specifies the interpretation and attributes of these names. 2 A declaration is a definition unless it declares a function without specifying the function's body (8.4), it contains the 3.1 Declarations and definitions Basic concepts 24 extern specifier (7.1.1) or a linkage-specification 26) (7.5) and neither an initializer nor a function-body, it declares a static data member in a class definition (9.4), it is a class name declaration (9.1), or it is a typedef declaration (7.1.3), a using-declaration (7.3.3), or a using-directive(7.3.4). [ 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 N::d -- end example ] 3 [ Note: in some circumstances, C++ implementations implicitly define the default constructor (12.1), copy constructor (12.8), assignment operator (12.8), or destructor (12.4) member functions. [ Example: given # include < string > struct C { std :: string s ; / / std::string is the standard library class (clause 21) }; int main () { C a; C b = a; b = a; } the implementation will implicitly define functions to make the definition of C equivalent to 26) Appearing inside the braced-enclosed declaration-seq in a linkage-specification does not affect whether a declaration is a definition. Draft 25 Basic concepts 3.2 One definition rule struct C { std :: string s ; C (): s () { } C ( const C & x ): s ( x . s ) { } C & operator =( const C & x ) { s = x . s ; return * this ; } ~ C () { } }; -- end example ] -- end note ] 4 [ Note: a class name can also be implicitly declared by an elaborated-type-specifier (3.3.1). -- end note ] 5 A program is ill-formed if the definition of any object gives the object an incomplete type (3.9). 3.2 One definition rule [basic.def.odr] 1 No translation unit shall contain more than one definition of any variable, function, class type, enumeration type or template. 2 An expression is potentially evaluated unless it appears where an integral constant expression is required (see 5.19), is the operand of the sizeof operator (5.3.3), or is the operand of the typeid operator and the expression does not designate an lvalue of polymorphic class type (5.2.8). An object or non-overloaded function is used if its name appears in a potentially-evaluated expression. A virtual member function is used if it is not pure. An overloaded function is used if it is selected by overload resolution when referred to from a potentially-evaluated expression. [ Note: this covers calls to named functions (5.2.2), operator overloading (clause 13), user-defined conversions (12.3.2), allocation function for placement new (5.3.4), as well as non-default initialization (8.5). A copy constructor is used even if the call is actually elided by the implementation. -- end note ] An allocation or deallocation function for a class is used by a new expression appearing in a potentially-evaluated expression as specified in 5.3.4 and 12.5. A deallocation function for a class is used by a delete expression appearing in a potentially-evaluated expression as specified in 5.3.5 and 12.5. A non-placement allocation or deallocation function for a class is used by the definition of a constructor of that class. A non-placement deallocation function for a class is 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 (12.4).27) A copy-assignment function for a class is used by an implicitly-defined copy-assignment function for another class as specified in 12.8. A default constructor for a class is used by default initialization or value initialization as specified in 8.5. A constructor for a class is used as specified in 8.5. A destructor for a class is used as specified in 12.4. 3 Every program shall contain exactly one definition of every non-inline function or object that is used in that program; 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 12.1, 12.4 and 12.8). An inline function shall be defined in every translation unit in which it is used. 4 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 27) An implementation is not required to call allocation and deallocation functions from constructors or destructors; however, this is a permissible implementation technique. Draft 3.2 One definition rule Basic concepts 26 -- 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: -- an object of type T is defined (3.1), or -- a non-static class data member of type T is declared (9.2), or -- T is used as the object type or array element type in a new-expression (5.3.4), or -- an lvalue-to-rvalue conversion is applied to an lvalue referring to an object of type T (4.1), or -- an expression is converted (either implicitly or explicitly) to type T (clause 4, 5.2.3, 5.2.7, 5.2.9, 5.4), or -- an expression that is not a null pointer constant, and has type other than void *, is converted to the type pointer to T or reference to T using an implicit conversion (clause 4), a dynamic_cast (5.2.7) or a static_cast (5.2.9), or -- a class member access operator is applied to an expression of type T (5.2.5), or -- the typeid operator (5.2.8) or the sizeof operator (5.3.3) is applied to an operand of type T, or -- a function with a return type or argument type of type T is defined (3.1) or called (5.2.2), or -- a class with a base class of type T is defined (10), or -- an lvalue of type T is assigned to (5.17). -- end note ] 5 There can be more than one definition of a class type (clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (clause 14), non-static function template (14.5.5), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template param- eters are not specified (14.7, 14.5.4) 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 3.4, shall refer to an entity defined within the definition of D, or shall refer to the same entity, after overload resolution (13.3) and after matching of partial template specialization (14.8.3), except that a name can refer to a const object with internal or no linkage if the object has the same integral or enumeration type in all definitions of D, and the object is initialized with a constant expression (5.19), and the value (but not the address) of the object is used, and the object has the same value in all definitions of D; 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 three requirements described above (and, if the default argument has sub-expressions with default arguments, this requirement applies recursively).28) 28) 8.3.6 describes how default argument names are looked up. Draft 27 Basic concepts 3.3 Declarative regions and scopes -- if D is a class with an implicitly-declared constructor (12.1), it is as if the constructor was implicitly defined in every translation unit where it is used, and the implicit definition in every translation unit shall call the same constructor for a base class or a class member of D. [ Example: / / translation unit 1: struct X { X ( int ); X ( int , int ); }; X :: X ( int = 0) { } class D : public X { }; D d2 ; / / X(int) called by D() / / translation unit 2: struct X { X ( int ); X ( int , int ); }; X :: X ( int = 0 , int = 0) { } class D : public X { }; / / X(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 last four requirements from the list above shall apply to names from the template's enclosing scope used in the template definition (14.6.3), and also to dependent names at the point of instantiation (14.6.2). If the definitions of D satisfy all these requirements, then the program shall behave as if there were a single definition of D. If the definitions of D do not satisfy these requirements, then the behavior is undefined. 3.3 Declarative regions and scopes [basic.scope] 1 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. 2 [ 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 Draft 3.3 Declarative regions and scopes Basic concepts 28 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 ] 3 The names declared by a declaration are introduced into the scope in which the declaration occurs, except that the presence of a friend specifier (11.4), certain uses of the elaborated-type-specifier (3.3.1), and using-directives (7.3.4) alter this general behavior. 4 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 object or enumerator, or all refer to functions and function templates; in this case the class name or enumeration name is hidden (3.3.7). [ Note: a namespace name or a class template name must be unique in its declarative region (7.3.2, clause 14). -- 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-specifier s (3.3.1) and friend declarations (11.4) may introduce a (possibly not visible) name into an enclosing namespace; these restrictions apply to that region. Local extern declarations (3.5) 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 ] 5 [ Note: the name lookup rules are summarized in 3.4. -- end note ] 3.3.1 Point of declaration [basic.scope.pdecl] 1 The point of declaration for a name is immediately after its complete declarator (clause 8) and before its initializer (if any), except as noted below. [ Example: int x = 12; { int x = x ; } Here the second x is initialized with its own (indeterminate) value. -- end example ] 2 [ Note: a nonlocal name remains visible up to the point of declaration of the local name that hides it. [ Example: const int i = 2; { int i [ i ]; } declares a local array of two integers. -- end example ] -- end note ] 3 The point of declaration for a class first declared by a class-specifier is immediately after the identifier or template-id (if any) in its class-head (Clause 9). The point of declaration for an enumeration is immediately after the identifier (if any) in its enum-specifier (7.2). 4 The point of declaration for an enumerator is immediately after its enumerator-definition. [ Example: const int x = 12; { enum { x = x }; } Draft 29 Basic concepts 3.3 Declarative regions and scopes Here, the enumerator x is initialized with the value of the constant x, namely 12. -- end example ] 5 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 ] 6 The point of declaration of a class first declared in an elaborated-type-specifier is as follows: -- for a declaraton of the form class-key identifier ; the identifier is declared to be a class-name in the scope that contains the declaration, otherwise -- for an elaborated-type-specifier of the form class-key identifier if the elaborated-type-specifier is used in the decl-specifier-seq or parameter-declaration-clause of a function de- fined in namespace scope, the identifier is declared as a class-name in the namespace that contains the declara- tion; otherwise, except as a friend declaration, the identifier is declared in the smallest non-class, non-function- prototype scope that contains the declaration. [ Note: These rules also apply within templates. -- end note ] [ Note: Other forms of elaborated-type-specifier do not declare a new name, and therefore must refer to an exist- ing type-name. See 3.4.4 and 7.1.5.3. -- end note ] 7 The point of declaration for an injected-class-name (9) is immediately following the opening brace of the class definition. 8 [ 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 (7.3.1.2). Function declarations at block scope and object declarations with the extern specifier at block scope refer to delarations that are members of an enclosing namespace, but they do not introduce new names into that scope. -- end note ] 9 [ Note: For point of instantiation of a template, see 14.6.4.1. -- end note ] 3.3.2 Local scope [basic.scope.local] 1 A name declared in a block (6.3) is local to that block. Its potential scope begins at its point of declaration (3.3.1) and ends at the end of its declarative region. 2 The potential scope of a function parameter name in a function definition (8.4) begins at its point of declaration. If the function has a function-try-block the potential scope of a parameter ends at the end of the last associated handler, else 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. 3 The name in a catch exception-declaration is local to the handler and shall not be redeclared in the outermost block of the handler. 4 Names declared in the for-init-statement, 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 Draft 3.3 Declarative regions and scopes Basic concepts 30 condition of that statement nor in the outermost block (or, for the if statement, any of the outermost blocks) of the controlled statement; see 6.4. 3.3.3 Function prototype scope [basic.scope.proto] 1 In a function declaration, or in any function declarator except the declarator of a function definition (8.4), names of parameters (if supplied) have function prototype scope, which terminates at the end of the nearest enclosing function declarator. 3.3.4 Function scope [basic.funscope] 1 Labels (6.1) have function scope and may be used anywhere in the function in which they are declared. Only labels have function scope. 3.3.5 Namespace scope [basic.scope.namespace] 1 The declarative region of a namespace-definition is its namespace-body. The potential scope denoted by an original- namespace-name is the concatenation of the declarative regions established by each of the namespace-definitions in the same declarative region with that original-namespace-name. 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 (3.3.1) onwards; and for each using-directive (7.3.4) 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 } Draft 31 Basic concepts 3.3 Declarative regions and scopes -- end example ] 2 A namespace member can also be referred to after the :: scope resolution operator (5.1) applied to the name of its namespace or the name of a namespace which nominates the member's namespace in a using-directive; see 3.4.3.2. 3 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 (3.3.1) and ends at the end of the translation unit that is its declarative region. Names with global namespace scope are said to be global. 3.3.6 Class scope [basic.scope.class] 1 The following rules describe the scope of names declared in classes. 1) 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, and constructor ctor-initializers in that class (including such things in nested classes). 2) 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. 3) If reordering member declarations in a class yields an alternate valid program under (1) and (2), the program is ill-formed, no diagnostic is required. 4) 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. 5) 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, member function definitions (including the member function body and, for constructor functions (12.1), the ctor-initializer (12.6.2)) and any portion of the declarator part of such definitions which follows the identifier, including a parameter-declaration-clause and any default arguments (8.3.6). [ 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; }; Draft 3.4 Name lookup Basic concepts 32 typedef int I ; class D { typedef I I ; / / error, even though no reordering involved }; -- end example ] 2 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 10) from its class, -- after the . operator applied to an expression of the type of its class (5.2.5) or a class derived from its class, -- after the -> operator applied to a pointer to an object of its class (5.2.5) or a class derived from its class, -- after the :: scope resolution operator (5.1) applied to the name of its class or a class derived from its class. 3.3.7 Name hiding [basic.scope.hiding] 1 A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class (10.2). 2 A class name (9.1) or enumeration name (7.2) can be hidden by the name of an object, function, or enumerator declared in the same scope. If a class or enumeration name and an object, 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 object, function, or enumerator name is visible. 3 In a member function definition, the declaration of a local name hides the declaration of a member of the class with the same name; see 3.3.6. The declaration of a member in a derived class (clause 10) hides the declaration of a member of a base class of the same name; see 10.2. 4 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 (3.4.3.2). 5 If a name is in scope and is not hidden it is said to be visible. 3.4 Name lookup [basic.lookup] 1 The name lookup rules apply uniformly to all names (including typedef-names (7.1.3), namespace-names (7.3) and class-names (9.1)) wherever the grammar allows such names in the context discussed by a particular rule. Name lookup associates the use of a name with a declaration (3.1) of that name. Name lookup shall find an unambiguous declaration for the name (see 10.2). Name lookup may associate more than one declaration with a name if it finds the name to be a function name; the declarations are said to form a set of overloaded functions (13.1). Overload resolution (13.3) takes place after name lookup has succeeded. The access rules (clause 11) 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 5). 2 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. Draft 33 Basic concepts 3.4 Name lookup 3 The injected-class-name of a class (clause 9) is also considered to be a member of that class for the purposes of name hiding and lookup. 4 [ Note: 3.5 discusses linkage issues. The notions of scope, point of declaration and name hiding are discussed in 3.3. -- end note ] 3.4.1 Unqualified name lookup [basic.lookup.unqual] 1 In all the cases listed in 3.4.1, 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. 2 The declarations from the namespace nominated by a using-directive become visible in a namespace enclosing the using-directive; see 7.3.4. For the purpose of the unqualified name lookup rules described in 3.4.1, the declarations from the namespace nominated by the using-directive are considered members of that enclosing namespace. 3 The lookup for an unqualified name used as the postfix-expression of a function call is described in 3.4.2. [ 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 3.4.2 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 (3.4.2) does not apply and the friend function f is not found. -- end note ] 4 A name used in global scope, outside of any function, class or user-declared namespace, shall be declared before its use in global scope. 5 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. 6 A name used in the definition of a function following the function's declarator-id29) that is a member of namespace N (where, only for the purpose of exposition, N could represent the global scope) shall be declared before its use in the block in which it is used or in one of its enclosing blocks (6.3) 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: 29) This refers to unqualified names that occur, for instance, in a type or default argument expression in the parameter-declaration-clause or used in the function body. Draft 3.4 Name lookup Basic concepts 34 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 ] 7 A name used in the definition of a class X outside of a member function body 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 (10.2), or -- if X is a nested class of class Y (9.7), 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) -- if X is a local class (9.8) 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 30) 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. 31) 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 (9.7). Draft 35 Basic concepts 3.4 Name lookup / / 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 7.3.1.2. -- end note ] [ Note: 3.3.6 further describes the restrictions on the use of names in a class definition. 9.7 further describes the restrictions on the use of names in nested class definitions. 9.8 further describes the restrictions on the use of names in local class definitions. -- end note ] 8 A name used in the definition of a member function (9.3) of class X following the function's declarator-id 32) 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 (6.3), or -- shall be a member of class X or be a member of a base class of X (10.2), or -- if X is a nested class of class Y (9.7), 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 (9.8) 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 member function definition, 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 32) That is, an unqualified name that occurs, for instance, in a type or default argument expression in the parameter-declaration-clause, in the function body, or in an expression of a mem-initializer in a constructor definition. 33) 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. Draft 3.4 Name lookup Basic concepts 36 -- end example ] [ Note: 9.3 and 9.4 further describe the restrictions on the use of names in member function definitions. 9.7 further describes the restrictions on the use of names in the scope of nested classes. 9.8 further describes the restrictions on the use of names in local class definitions. -- end note ] 9 Name lookup for a name used in the definition of a friend function (11.4) 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. 10 In a friend declaration naming a member function, a name used in the function declarator and not part of a template- argument in a template-id is first looked up in the scope of the member function's class. If it is not found, or if the name is part of a template-argument in a template-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 ); }; struct B { typedef float BT ; friend void A :: f1 ( AT ); / / parameter type is A::AT friend void A :: f2 ( BT ); / / parameter type is B::BT }; -- end example ] 11 During the lookup for a name used as a default argument (8.3.6) in a function parameter-declaration-clause or used in the expression of a mem-initializer for a constructor (12.6.2), 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: 8.3.6 further describes the restrictions on the use of names in default arguments. 12.6.2 further describes the restrictions on the use of names in a ctor-initializer. -- end note ] 12 A name used in the definition of a static data member of class X (9.4.2) (after the qualified-id of the static member) is looked up as if the name was used in a member function of X. [ Note: 9.4.2 further describes the restrictions on the use of names in the definition of a static data member. -- end note ] 13 A name used in the handler for a function-try-block (clause 15) 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 ] 14 [ Note: the rules for name lookup in template definitions are described in 14.6. -- end note ] 3.4.2 Argument-dependent name lookup [basic.lookup.argdep] 1 When an unqualified name is used as the postfix-expression in a function call (5.2.2), other namespaces not considered during the usual unqualified lookup (3.4.1) may be searched, and in those namespaces, namespace-scope friend function Draft 37 Basic concepts 3.4 Name lookup declarations (11.4) 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). 2 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 is 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 namespaces in which its associated classes are defined. -- If T is an enumeration type, its associated namespace is the namespace in which it is defined. If it is 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 T is a class template specialization its associated namespaces and classes are the namespace in which the template is defined; for member templates, the member template's class; the namespaces and classes associated with the types of the template arguments provided for template type parameters (excluding template template parameters); the namespaces in which any template template arguments are defined; and the classes in which any member templates used as template template arguments are defined. [ Note: non-type template arguments do not contribute to the set of associated namespaces. -- end note ] 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: the namespace in which the function or function template is defined and the classes and namespaces associated with its (non-dependent) parameter types and return type. 3 If the ordinary unqualified lookup of the name finds the declaration of a class member function, or a block-scope function declaration that is not a using-declaration, the associated namespaces are not considered. Otherwise the set of declarations found by the lookup of the function name is the union of the set of declarations found using ordinary unqualified lookup and the set of declarations found in the namespaces associated with the argument types. [ 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 ); Draft 3.4 Name lookup Basic concepts 38 } 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 ] 4 When considering an associated namespace, the lookup is the same as the lookup performed when the associated names- pace is used as a qualifier (3.4.3.2) except that: -- Any using-directive s in the associated namespace are ignored. -- Any namespace-scope friend functions declared in associated classes are visible within their respective names- paces even if they are not visible during an ordinary lookup (11.4). 3.4.3 Qualified name lookup [basic.lookup.qual] 1 The name of a class or namespace member can be referred to after the :: scope resolution operator (5.1) applied to a nested-name-specifier that nominates its class or namespace. During the lookup for a name preceding the :: scope resolution operator, object, function, and enumerator names are ignored. If the name found is not a class-name (clause 9) or namespace-name (7.3.1), 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 ] 2 [ Note: Multiply qualified names, such as N1::N2::N3::n, can be used to refer to members of nested classes (9.7) or members of nested namespaces. -- end note ] 3 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 ]; Draft 39 Basic concepts 3.4 Name lookup }; X C :: arr [ number ]; / / ill-formed: / / equivalent to: ::X C::arr[C::number]; / / not to: C::X C::arr[C::number]; -- end example ] 4 A name prefixed by the unary scope operator :: (5.1) 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 (3.4.3.2). The use of :: allows a global name to be referred to even if its identifier has been hidden (3.3.7). 5 If a pseudo-destructor-name (5.2.4) 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: ::opt nested-name-specifieropt 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: 3.4.5 describes how name lookup proceeds after the . and -> operators. -- end note ] 3.4.3.1 Class members [class.qual] 1 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 (10.2), 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 10). [ Note: a class member can be referred to using a qualified-id at any point in its potential scope (3.3.6). -- end note ] The exceptions to the name lookup rule above are the following: -- a destructor name is looked up as specified in 3.4.3; Draft 3.4 Name lookup Basic concepts 40 -- a conversion-type-id of an operator-function-id is looked up both in the scope of the class and in the context in which the entire postfix-expression occurs and shall refer to the same type in both contexts; -- the template-arguments of a template-id are looked up in the context in which the entire postfix-expression occurs. -- the lookup for a name specified in a using-declaration (7.3.3) also finds class or enumeration names hidden within the same scope (3.3.7). 2 In a lookup in which the constructor is an acceptable lookup result, if the nested-name-specifier nominates a class C, and the name specified after the nested-name-specifier, when looked up in C, is the injected-class-name of C (clause 9), 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. [ 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 ] 3 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. 3.4.3.2 Namespace members [namespace.qual] 1 If the nested-name-specifier of a qualified-id nominates a namespace, the name specified after the nested-name-specifier is looked up in the scope of the namespace, except that the template-arguments of a template-id are looked up in the context in which the entire postfix-expression occurs. 2 Given X::m (where X is a user-declared namespace), or given ::m (where X is the global namespace), let S be the set of all declarations of m in X and in the transitive closure of all namespaces nominated by using-directives in X and its used namespaces, except that using-directives are ignored in any namespace, including X, directly containing one or more declarations of m. No namespace is searched more than once in the lookup of a name. If S is the empty set, the program is ill-formed. Otherwise, if S has exactly one member, or if the context of the reference is a using-declaration (7.3.3), S 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 S, the program is ill-formed. [ Example: int x ; namespace Y { void f ( float ); void h ( int ); } Draft 41 Basic concepts 3.4 Name lookup 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 { A::f(int) , B::f(char) } 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 { A::i , B::i } 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 { Y::h(int) , Z::h(double) } and overload // resolution chooses Z::h(double) } Draft 3.4 Name lookup Basic concepts 42 3 The same declaration found more than once is not an ambiguity (because it is still a unique declaration). For 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 { A::a, A::a } } namespace D { using A :: a ; } namespace BD { using namespace B ; using namespace D ; } void g () { BD :: a ++; / / OK: S is { A::a, A::a } } 4 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 ; Draft 43 Basic concepts 3.4 Name lookup } 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 ] 5 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 object, 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 ] 6 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. [ 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: Draft 3.4 Name lookup Basic concepts 44 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 ] 3.4.4 Elaborated type specifiers [basic.lookup.elab] 1 An elaborated-type-specifier (7.1.5.3) 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 (3.3.7). 2 If the elaborated-type-specifier has no nested-name-specifier, and unless the elaborated-type-specifier appears in a dec- laration with the following form: class-key identifier ; the identifier is looked up according to 3.4.1 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: class-key identifier ; the elaborated-type-specifier is a declaration that introduces the class-nam as described in 3.3.1. 3 If the elaborated-type-specifier has a nested-name-specifier, qualified name lookup is performed, as described in 3.4.3, 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 (7.1.5.3) friend struct Glob ; // OK: Refers to (as yet) undeclared Glob Draft 45 Basic concepts 3.4 Name lookup / / 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 (7.1.5.3) struct Base :: Data ; // error: cannot introduce a qualified type (7.1.5.3) struct Base :: Datum ; // error: Datum undefined struct Base :: Data * pBase ; // OK: refers to nested Data -- end example ] 3.4.5 Class member access [basic.lookup.classref] 1 In a class member access expression (5.2.5), 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 (14.2) 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 or function template. If the lookup in the class of the object expression finds a template, the name is also looked up in the context of the entire postfix-expression and -- if the name is not found, the name found in the class of the object expression is used, otherwise -- if the name is found in the context of the entire postfix-expression and does not name a class template, the name found in the class of the object expression is used, otherwise -- if the name found is a class template, it must refer to the same entity as the one found in the class of the object expression, otherwise the program is ill-formed. 2 If the id-expression in a class member access (5.2.5) is an unqualified-id, and the type of the object expression is of a class type C (or of pointer to a class type C), the unqualified-id is looked up in the scope of class C. If the type of the object expression is of pointer to scalar type, the unqualified-id is looked up in the context of the complete postfix-expression. 3 If the unqualified-id is ~type-name, and the type of the object expression is of a class type C (or of pointer to a class type C), the type-name is looked up in the context of the entire postfix-expression and in the scope of class C. The type-name shall refer to a class-name. If type-name is found in both contexts, the name shall refer to the same class type. If the type of the object expression is of scalar type, the type-name is looked up in the scope of the complete postfix-expression. 4 If the id-expression in a class member access is a qualified-id of the form class-name-or-namespace-name::... Draft 3.5 Program and linkage Basic concepts 46 the class-name-or-namespace-name following the . or -> operator is looked up both in the context of the entire postfix- expression and in the scope of the class of the object expression. If the name is found only in the scope of the class of the object expression, the name shall refer to a class-name. If the name is found only in the context of the entire postfix-expression, the name shall refer to a class-name or namespace-name. If the name is found in both contexts, the class-name-or-namespace-name shall refer to the same entity. 5 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. 6 If the nested-name-specifier contains a class template-id (14.2), its template-arguments are evaluated in the context in which the entire postfix-expression occurs. 7 If the id-expression is a conversion-function-id, its conversion-type-id shall denote the same type in both the context in which the entire postfix-expression occurs and in the context of the class of the object expression (or the class pointed to by the pointer expression). 3.4.6 Using-directives and namespace aliases [basic.lookup.udir] 1 When looking up a namespace-name in a using-directive or namespace-alias-definition, only namespace names are considered. 3.5 Program and linkage [basic.link] 1 A program consists of one or more translation units (clause 2) linked together. A translation unit consists of a sequence of declarations. translation-unit: declaration-seqopt 2 A name is said to have linkage when it might denote the same object, reference, function, type, template, namespace or value as a name introduced by a declaration in another scope: -- When a name has external linkage, the entity it denotes can be referred to by names from scopes of other transla- tion units or from other scopes of the same translation unit. -- When a name has internal linkage, the entity it denotes can be referred to by names from other scopes in the same translation unit. -- When a name has no linkage, the entity it denotes cannot be referred to by names from other scopes. 3 A name having namespace scope (3.3.5) has internal linkage if it is the name of -- an object, reference, function or function template that is explicitly declared static or, -- an object or reference that is explicitly declared const and neither explicitly declared extern nor previously declared to have external linkage; or -- a data member of an anonymous union. 4 A name having namespace scope has external linkage if it is the name of -- an object or reference, unless it has internal linkage; or Draft 47 Basic concepts 3.5 Program and linkage -- a function, unless it has internal linkage; or -- a named class (clause 9), or an unnamed class defined in a typedef declaration in which the class has the typedef name for linkage purposes (7.1.3); or -- a named enumeration (7.2), or an unnamed enumeration defined in a typedef declaration in which the enumeration has the typedef name for linkage purposes (7.1.3); or -- an enumerator belonging to an enumeration with external linkage; or -- a template, unless it is a function template that has internal linkage (clause 14); or -- a namespace (7.3), unless it is declared within an unnamed namespace. 5 In addition, a member function, static data member, a named class or enumeration of class scope, or an unnamed class or enumeration defined in a class-scope typedef declaration such that the class or enumeration has the typedef name for linkage purposes (7.1.3), has external linkage if the name of the class has external linkage. 6 The name of a function declared in block scope, and the name of an object declared by a block scope extern declaration, have linkage. If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace scope, the block scope declaration declares that same entity and receives the linkage of the previous declaration. If there is more than one such matching entity, the program is ill-formed. Otherwise, if no matching entity is found, the block scope entity receives external linkage. [ Example: static void f (); static int i = 0; // 1 void g () { extern void f (); / / internal linkage int i ; / / 2: i has no linkage { extern void f (); / / internal linkage extern int i ; / / 3: external linkage } } There are three objects named i in this program. The object with internal linkage introduced by the declaration in global scope (line //1 ), the object with automatic storage duration and no linkage introduced by the declaration on line //2, and the object with static storage duration and external linkage introduced by the declaration on line //3. -- end example ] 7 When a block scope declaration of an entity with linkage is not found to refer to some other declaration, then that entity is a member of the innermost enclosing namespace. However such a declaration does not introduce the member name in its namespace scope. [ Example: namespace X { void p () { q (); / / error: q not yet declared extern void q (); / / q is a member of namespace X } Draft 3.5 Program and linkage Basic concepts 48 void middle () { q (); / / error: q not yet declared } void q () { / ... / } / / definition of X::q } void q () { / ... / } / / some other, unrelated q -- end example ] 8 Names not covered by these rules have no linkage. Moreover, except as noted, a name declared in a local scope (3.3.2) has no linkage. A type is said to have linkage if and only if: -- it is a class or enumeration type that is named (or has a name for linkage purposes (7.1.3) and the name has linkage; or -- it is a specialization of a class template (14)34) ; or -- it is a fundamental type (3.9.1); or -- it is a compound type (3.9.2) other than a class or enumeration, compounded exclusively from types that have linkage; or -- it is a cv-qualified (3.9.3) version of a type that has linkage. A type without linkage shall not be used as the type of a variable or function with linkage, unless the variable or function has extern "C" linkage (7.5). [ Note: in other words, a type without linkage contains a class or enumeration that cannot be named outside its translation unit. An entity with external linkage declared using such a type could not correspond to any other entity in another translation unit of the program and thus is not permitted. Also note that classes with linkage may contain members whose types do not have linkage, and that typedef names are ignored in the determination of whether a type has linkage. -- end note ] [ Example: void f () { struct A { int x ; }; / / no linkage extern A a ; / / ill-formed typedef A B ; extern B b ; / / ill-formed } -- end example ] This implies that names with no linkage cannot be used as template arguments (14.3). 9 Two names that are the same (clause 3) and that are declared in different scopes shall denote the same object, reference, function, type, enumerator, template or namespace if -- both names have external linkage or else both names have internal linkage and are declared in the same translation unit; and 34) a class template always has external linkage, and the requirements of 14.3.1 and 14.3.2 ensure that the template arguments will also have appropriate linkage. Draft 49 Basic concepts 3.6 Start and termination -- both names refer to members of the same namespace or to members, not by inheritance, of the same class; and -- when both names denote functions, the parameter-type-lists of the functions (8.3.5) are identical; and -- when both names denote function templates, the signatures (14.5.5.1) are the same. 10 After all adjustments of types (during which typedefs (7.1.3) are replaced by their definitions), the types specified by all declarations referring to a given object or function shall be identical, except that declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4). A violation of this rule on type identity does not require a diagnostic. 11 [ Note: linkage to non-C++ declarations can be achieved using a linkage-specification (7.5). -- end note ] 3.6 Start and termination [basic.start] 3.6.1 Main function [basic.start.main] 1 A program shall contain a global function called main, which is the designated start of the program. 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 ] 2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main : int main () { / ... / } and int main ( int argc , char * argv []) { / ... / } In the latter form 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 (NTMBSs) (17.3.2.1.3.2) 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 nonnegative. The value of argv[argc] shall be 0. [ Note: it is recommended that any further (optional) parameters be added after argv. -- end note ] 3 The function main shall not be used (3.2) within a program. The linkage (3.5) of main is implementation-defined. A program that declares main to be inline or static 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 ] 4 Calling the function std::exit(int) declared in (18.3) terminates the program without leaving the current block and hence without destroying any objects with automatic storage duration (12.4). If std::exit is called to end a program during the destruction of an object with static storage duration, the program has undefined behavior. 5 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 reaches the end of main without encountering a return statement, the effect is that of executing Draft 3.6 Start and termination Basic concepts 50 return 0; 3.6.2 Initialization of non-local objects [basic.start.init] 1 Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. A reference with static storage duration and an object of POD type with static storage duration can be initialized with a constant expression (5.19); this is called constant initialization. Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. Static initialization shall be performed before any dynamic initialization takes place. Dynamic initialization of an object is either ordered or unordered. Def- initions of explicitly specialized class template static data members have ordered initialization. Other class template static data members (i.e., implicitly or explicitly instantiated specializations) have unordered initialization. Other ob- jects defined in namespace scope have ordered initialization. Objects defined within a single translation unit and with ordered initialization shall be initialized in the order of their definitions in the translation unit. The order of initialization is unspecified for objects with unordered initialization and for objects defined in different translation units. [ Note: 8.5.1 describes the order in which aggregate members are initialized. The initialization of local static objects is described in 6.7. -- end note ] 2 An implementation is permitted to perform the initialization of an object of namespace scope with static 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 namespace scope with static storage duration prior to its initialization, and -- the static version of the initialization produces the same value in the initialized object as would be produced by the dynamic initialization if all objects 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 with static storage duration 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 1.0 double d1 = fd (); // may be initialized statically to 1.0 -- end note ] 3 It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of namespace scope is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first use of any function or object defined in the same translation unit as the object to be initialized.35) [ Example: / / - File 1 - # include " a . h " # include " b . h " B b; 35) An object defined in namespace scope having initialization with side-effects must be initialized even if it is not used (3.7.1). Draft 51 Basic concepts 3.6 Start and termination 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 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 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 ] 4 If construction or destruction of a non-local static object ends in throwing an uncaught exception, the result is to call std::terminate (18.6.3.3). 3.6.3 Termination [basic.start.term] 1 Destructors (12.4) for initialized objects of static storage duration (declared at block scope or at namespace scope) are called as a result of returning from main and as a result of calling std::exit (18.3). These objects are destroyed in the reverse order of the completion of their constructor or of the completion of their dynamic initialization. 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 local object with static storage duration initialized during the construction of the subobjects is destroyed. 2 If a function contains a local object of static storage duration that has been destroyed and the function is called during the destruction of an object with static storage duration, the program has undefined behavior if the flow of control passes through the definition of the previously destroyed local object. 3 If a function is registered with std::atexit (see , 18.3) then following the call to std::exit, any objects with static storage duration initialized prior to the registration of that function shall not be destroyed until the registered function is called from the termination process and has completed. For an object with static storage duration constructed after a function is registered with std::atexit, then following the call to std::exit, the registered function is not called until the execution of the object's destructor has completed. If std::atexit is called during the construction of an object, the complete object to which it belongs shall be destroyed before the registered function is called. 4 Calling the function std::abort() declared in terminates the program without executing destructors for Draft 3.7 Storage duration Basic concepts 52 objects of automatic or static storage duration and without calling the functions passed to std::atexit(). 3.7 Storage duration [basic.stc] 1 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 -- automatic storage duration -- dynamic storage duration 2 Static and automatic storage durations are associated with objects introduced by declarations (3.1) and implicitly created by the implementation (12.2). The dynamic storage duration is associated with objects created with operator new (5.3.4). 3 The storage class specifiers static and auto are related to storage duration as described below. 4 The storage duration categories apply to references as well. The lifetime of a reference is its storage duration. 3.7.1 Static storage duration [basic.stc.static] 1 All objects which neither have dynamic storage duration nor are local have static storage duration. The storage for these objects shall last for the duration of the program (3.6.2, 3.6.3). 2 If an object of 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 may be eliminated as specified in 12.8. 3 The keyword static can be used to declare a local variable with static storage duration. [ Note: 6.7 describes the initialization of local static variables; 3.6.3 describes the destruction of local static variables. -- end note ] 4 The keyword static applied to a class data member in a class definition gives the data member static storage duration. 3.7.2 Automatic storage duration [basic.stc.auto] 1 Local objects explicitly declared auto or register or not explicitly declared static or extern have automatic storage duration. The storage for these objects lasts until the block in which they are created exits. 2 [ Note: these objects are initialized and destroyed as described in 6.7. -- end note ] 3 If a named automatic object has initialization or a destructor with side effects, it shall not be destroyed before the end of its block, nor shall it be eliminated as an optimization even if it appears to be unused, except that a class object or its copy may be eliminated as specified in 12.8. 3.7.3 Dynamic storage duration [basic.stc.dynamic] 1 Objects can be created dynamically during program execution (1.9), using new-expressions (5.3.4), and destroyed using delete-expressions (5.3.5). 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[]. 2 The library provides default definitions for the global allocation and deallocation functions. Some global allocation and deallocation functions are replaceable (18.4.1). A C++ program shall provide at most one definition of a replaceable Draft 53 Basic concepts 3.7 Storage duration allocation or deallocation function. Any such function definition replaces the default version provided in the library (17.4.3.4). The following allocation and deallocation functions (18.4) are implicitly declared in global scope in each translation unit of a program void * operator new ( std :: size_t ) throw ( std :: bad_alloc ); void * operator new []( std :: size_t ) throw ( std :: bad_alloc ); void operator delete ( void *) throw (); void operator delete []( void *) throw (); These implicit declarations introduce only the function names operator new, operator new[], operator delete, operator delete[]. [ Note: the implicit declarations do not introduce the names std, std::bad_alloc, and std ::size_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 is well-formed. However, referring to std, std::bad_alloc, and std::size_t is ill-formed unless the name has been declared by including the appropriate header. -- end note ] Allocation and/or deallocation functions can also be declared and defined for any class (12.5). 3 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 3.7.3.1 and 3.7.3.2. 3.7.3.1 Allocation functions [basic.stc.dynamic.allocation] 1 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 (18.1). The first parameter shall not have an associated default argument (8.3.6). 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. 2 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 is unspecified. The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type 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 (4.10) p0 different from any previously returned value p1, unless that value p1 was subsequently passed to an operator delete. The effect of dereferencing a pointer returned as a request for zero size is undefined.36) 3 An allocation function that fails to allocate storage can invoke the currently installed new-handler function (18.4.2.2), if any. [ Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the std::set_new_handler function (18.4.2.3). -- end note ] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throwing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc. 36) 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. Draft 3.8 Object Lifetime Basic concepts 54 4 A global allocation function is only called as the result of a new expression (5.3.4), or called directly using the function call syntax (5.2.2), 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 (3.7.1), for objects of type std::type_info (5.2.8), for the copy of an object thrown by a throw expression (15.1). -- end note ] 3.7.3.2 Deallocation functions [basic.stc.dynamic.deallocation] 1 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. 2 Each deallocation function shall return void and its first parameter shall be void*. A deallocation function can have more than one parameter. If a class T has a member deallocation function named operator delete with exactly one parameter, then that function is a usual (non-placement) deallocation function. If class T does not declare such an operator delete but does declare a member deallocation function named operator delete with exactly two parameters, the second of which has type std::size_t (18.1), then this function is a usual deallocation function. Similarly, if a class T has a member deallocation function named operator delete[] with exactly one parameter, then that function is a usual (non-placement) deallocation function. If class T does not declare such an operator delete[] but does declare a member deallocation function named operator delete[] with exactly two parameters, the second of which has type std::size_t, then this function is a usual deallocation function. A deallocation function can 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. 3 The value of the first argument supplied to one of the deallocation functions provided in the standard library may be a null pointer value; if so, the call to the deallocation function has no effect. Otherwise, the value supplied to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(std::size_t) or operator new(std::size_t, const std::nothrow_t&) in the standard library, and the value supplied to operator delete[](void*) in the standard library shall be one of the values returned by a previous invocation of either operator new[](std::size_t) or operator new[](std::size_t, const std::nothrow_- t&) in the standard library. 4 If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value (4.10), the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage. The effect of using an invalid pointer value (including passing it to a deallocation function) is undefined.37) 3.7.4 Duration of subobjects [basic.stc.inherit] 1 The storage duration of member subobjects, base class subobjects and array elements is that of their complete object (1.8). 3.8 Object Lifetime [basic.life] 1 The lifetime of an object is a runtime property of the object. The lifetime of an object of type T begins when: -- storage with the proper alignment and size for type T is obtained, and 37) On some implementations, it causes a system-generated runtime fault. Draft 55 Basic concepts 3.8 Object Lifetime -- if T is a class type and the constructor invoked to create the object is non-trivial (12.1), the constructor call has completed. the initialization is complete. [ Note: the initialization can be performed by a constructor call or, in the case of an aggregate with an implicitly-declared non-trivial default constructor, an aggregate initialization 8.5.1. -- end note ] The lifetime of an object of type T ends when: -- if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or -- the storage which the object occupies is reused or released. 2 [ Note: the lifetime of an array object or of an object of POD type (3.9) starts as soon as storage with proper size and alignment is obtained, and its lifetime ends when the storage which the array or object occupies is reused or released. 12.6.2 describes the lifetime of base and member subobjects. -- end note ] 3 The properties ascribed to objects throughout this International Standard apply for a given object 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 12.6.2 and in 12.7. 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. 12.6.2 and 12.7 describe the behavior of objects during the construction and destruction phases. -- end note ] 4 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 (5.3.5) 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. 5 Before the lifetime of an object has started but after the storage which the object will occupy has been allocated38) or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that refers to the storage location where the object will be or was located may be used but only in limited ways. Such a pointer refers to allocated storage (3.7.3.2), and using the pointer as if the pointer were of type void*, is well- defined. Such a pointer may be dereferenced but the resulting lvalue may only be used in limited ways, as described below. 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 program has undefined behavior. If the object will be or was of a non-POD class type, the program has undefined behavior if: -- 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 (4.10) to a pointer to a base class type, or -- the pointer is used as the operand of a static_cast (5.2.9) (except when the conversion is to void*, or to void* and subsequently to char*, or unsigned char* ). -- the pointer is used as the operand of a dynamic_cast (5.2.7). [ Example: # include < cstdlib > struct B { virtual void f (); 38) For example, before the construction of a global object of non-POD class type (12.7). Draft 3.8 Object Lifetime Basic concepts 56 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 ] 6 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 lvalue which refers to the original object may be used but only in limited ways. Such an lvalue refers to allocated storage (3.7.3.2), and using the properties of the lvalue which do not depend on its value is well-defined. If an lvalue-to-rvalue conversion (4.1) is applied to such an lvalue, the program has undefined behavior; if the original object will be or was of a non-POD class type, the program has undefined behavior if: -- the lvalue is used to access a non-static data member or call a non-static member function of the object, or -- the lvalue is implicitly converted (4.10) to a reference to a base class type, or -- the lvalue is used as the operand of a static_cast (5.2.9) except when the conversion is ultimately to cv char& or cv unsigned char& ), or -- the lvalue is used as the operand of a dynamic_cast (5.2.7) or as the operand of typeid. 7 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 Draft 57 Basic concepts 3.8 Object Lifetime -- the original object was a most derived object (1.8) 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 ] 8 If a program ends the lifetime of an object of type T with static (3.7.1) or automatic (3.7.2) storage duration and if T has a non-trivial destructor,39) 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 ] 9 Creating a new object at the storage location that a const object with static or automatic storage duration occupies or, at the storage location that such a const object used to occupy before its lifetime ended results in undefined behavior. [ Example: struct B { B (); 39) that is, an object for which a destructor will be called implicitly­either either upon exit from the block for an object with automatic storage duration or upon exit from the program for an object with static storage duration. Draft 3.9 Types Basic concepts 58 ~ B (); }; const B b ; void h () { b .~ B (); new (& b ) const B ; / / undefined behavior } -- end example ] 3.9 Types [basic.types] 1 [ Note: 3.9 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 (1.8), references (8.3.2), or functions (8.3.5). -- end note ] 2 For any object (other than a base-class subobject) of POD type T, whether or not the object holds a valid value of type T, the underlying bytes (1.7) making up the object can be copied into an array of char or unsigned char.40) If the content of the array of char or unsigned char 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 ] 3 For any POD 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 value of obj1 is copied into obj2, using the std::memcpy library function, 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 POD type in *t1p contains / / the same value as the corresponding subobject in *t2p -- end example ] 4 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. 40) By using, for example, the library functions (17.4.1.2) std::memcpy or std::memmove. Draft 59 Basic concepts 3.9 Types For POD 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.41) 5 Object types have alignment requirements (3.9.1, 3.9.2). The alignment of a complete object type is an implementation- defined integer value representing a number of bytes; an object is allocated at an address that meets the alignment requirements of its object type. 6 A class that has been declared but not defined, or an array of unknown size or of incomplete element type, is an incompletely-defined object type.42) Incompletely-defined object types and the void types are incomplete types (3.9.1). Objects shall not be defined to have an incomplete type. 7 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 size 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 size, or of a type defined by a typedef declaration to be an array of unknown size, 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 ] 41) The intent is that the memory model of C++ is compatible with that of ISO/IEC 9899 Programming Language C. 42) The size and layout of an instance of an incompletely-defined object type is unknown. Draft 3.9 Types Basic concepts 60 8 [ Note: the rules for declarations and expressions describe in which contexts incomplete types are prohibited. -- end note ] 9 An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type. 10 Arithmetic types (3.9.1), enumeration types, pointer types, and pointer to member types (3.9.2), and cv-qualified versions of these types (3.9.3) are collectively called scalar types. Scalar types, POD-struct types, POD-union types (clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively called POD types. 11 If two types T1 and T2 are the same type, then T1 and T2 are layout-compatible types. [ Note: Layout-compatible enumerations are described in 7.2. Layout-compatible POD-structs and POD-unions are described in 9.2. -- end note ] 3.9.1 Fundamental types [basic.fundamental] 1 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. A char, a signed char, and an unsigned char occupy the same amount of storage and have the same alignment requirements (3.9); that is, they have the same object representation. For character types, all bits of the object representation participate in the value representation. For unsigned character types, all possible bit patterns of the value representation represent numbers. 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. 2 There are four signed integer types : "signed char", "short int", "int", and "long int." In this list, each type provides at least as much storage as those preceding it in the list. Plain ints have the natural size suggested by the architecture of the execution environment43) ; the other signed integer types are provided to meet special needs. 3 For each of the signed integer types, there exists a corresponding (but different) unsigned integer type: "unsigned char", "unsigned short int", "unsigned int", and "unsigned long int," each of which occupies the same amount of storage and has the same alignment requirements (3.9) as the corresponding signed integer type44) ; that is, each signed integer type has the same object representation as its corresponding unsigned integer type. The range of nonnegative values of a signed integer type is a subrange of the corresponding unsigned integer type, and the value representation of each corresponding signed/unsigned type shall be the same. 4 Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.45) 5 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 (22.1.1). Type wchar_t shall have the same size, signedness, and alignment requirements (3.9) as one of the other integral types, called its underlying type. 6 Values of type bool are either true or false.46) [ Note: there are no signed, unsigned, short, or long bool types or values. -- end note ] As described below, bool values behave as integral types. Values of type bool participate in 43) that is, large enough to contain any value in the range of INT_MIN and INT_MAX, as defined in the header . 44) See 7.1.5.2 regarding the correspondence between types and the sequences of type-specifiers that designate them. 45) 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. 46) Using a bool value in ways described by this International Standard as "undefined," such as by examining the value of an uninitialized automatic variable, might cause it to behave as if it is neither true nor false. Draft 61 Basic concepts 3.9 Types integral promotions (4.5). 7 Types bool, char, wchar_t, and the signed and unsigned integer types are collectively called integral types.47) A synonym for integral type is integer type. The representations of integral types shall define values by use of a pure binary numeration system.48) [ Example: this International Standard permits 2's complement, 1's complement and signed magnitude representations for integral types. -- end example ] 8 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. Integral and floating types are collectively called arithmetic types. Specializations of the standard template std::numeric_- limits (18.2) shall specify the maximum and minimum values of each arithmetic type for an implementation. 9 The void type has an empty set of values. The void type is an incomplete type that cannot be completed. 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 (5.4). An expression of type void shall be used only as an expression statement (6.2), as an operand of a comma expression (5.18), as a second or third operand of ?: (5.16), as the operand of typeid, or as the expression in a return statement (6.6.3) for a function with the return type void. 10 [ Note: even if the implementation defines two or more basic types to have the same value representation, they are nevertheless different types. -- end note ] 3.9.2 Compound types [basic.compound] 1 Compound types can be constructed in the following ways: -- arrays of objects of a given type, 8.3.4; -- functions, which have parameters of given types and return void or references or objects of a given type, 8.3.5; -- pointers to void or objects or functions (including static members of classes) of a given type, 8.3.1; -- references to objects or functions of a given type, 8.3.2; -- classes containing a sequence of objects of various types (clause 9), a set of types, enumerations and functions for manipulating these objects (9.3), and a set of restrictions on the access to these entities (clause 11); -- unions, which are classes capable of containing objects of different types at different times, 9.5; -- enumerations, which comprise a set of named constant values. Each distinct enumeration constitutes a different enumerated type, 7.2; -- pointers to non-static 49) class members, which identify members of a given type within objects of a given class, 8.3.3. 47) Therefore, enumerations (7.2) are not integral; however, enumerations can be promoted to int, unsigned int, long, or unsigned long, as specified in 4.5. 48) 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.) 49) Static class members are objects or functions, and pointers to them are ordinary pointers to objects or functions. Draft 3.9 Types Basic concepts 62 2 These methods of constructing types can be applied recursively; restrictions are mentioned in 8.3.1, 8.3.4, 8.3.5, and 8.3.2. 3 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 (3.9). A valid value of an object pointer type represents either the address of a byte in memory (1.7) or a null pointer (4.10). If an object of type T is located at an address A, a pointer of type cv T* whose value is the address A is said to point to that object, regardless of how the value was obtained. [ Note: for instance, the address one past the end of an array (5.7) would be considered to point to an unrelated object of the array's element type that might be located at that address. -- end note ] The value representation of pointer types is implementation-defined. Pointers to cv-qualified and cv-unqualified versions (3.9.3) of layout-compatible types shall have the same value representation and alignment requirements (3.9). 4 Objects of cv-qualified (3.9.3) or cv-unqualified type void* (pointer to void), can be used to point to objects of unknown type. A void* shall be able to hold any object pointer. A cv-qualified or cv-unqualified (3.9.3) void* shall have the same representation and alignment requirements as a cv-qualified or cv-unqualified char*. 3.9.3 CV-qualifiers [basic.type.qualifier] 1 A type mentioned in 3.9.1 and 3.9.2 is a cv-unqualified type. Each type which is a cv-unqualified complete or incomplete object type or is void (3.9) has three corresponding cv-qualified versions of its type: a const-qualified version, a volatile- qualified version, and a const-volatile-qualified version. The term object type (1.8) includes the cv-qualifiers specified when the object is created. The presence of a const specifier in a decl-specifier-seq declares an object of const-qualified object type; such object is called a const object. The presence of a volatile specifier in a decl-specifier-seq declares an object of volatile-qualified object type; such object is called a volatile object. The presence of both cv-qualifiers in a decl-specifier-seq declares an object of const-volatile-qualified object type; such object is called a const volatile object. The cv-qualified or cv-unqualified versions of a type are distinct types; however, they shall have the same representation and alignment requirements (3.9).50) 2 A compound type (3.9.2) 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, not the array type (8.3.4). 3 Each non-static, non-mutable, non-reference data member of a const-qualified class object is const-qualified, each non- static, non-reference data member of a volatile-qualified class object is volatile-qualified and similarly for members of a const-volatile class. See 8.3.5 and 9.3.2 regarding cv-qualified function types. 4 There is a (partial) ordering on cv-qualifiers, so that a type can be said to be more cv-qualified than another. Table 6 shows the relations that constitute this ordering. 5 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. 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. Such array types can be said to be more (or less) cv-qualified than other types based 50) The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from func- tions, and members of unions. Draft 63 Basic concepts 3.10 Lvalues and rvalues Table 6: relations on const and volatile no cv-qualifier < const no cv-qualifier < volatile no cv-qualifier < const volatile const < const volatile volatile < const volatile on the cv-qualification of the underlying element types. 3.10 Lvalues and rvalues [basic.lval] 1 Every expression is either an lvalue or an rvalue. 2 An lvalue refers to an object or function. Some rvalue expressions--those of class or cv-qualified class type--also refer to objects.51) 3 [ Note: some built-in operators and function calls yield lvalues. [ Example: if E is an expression of pointer type, then *E is an lvalue expression referring to the object or function to which E points. As another example, the function int & f (); yields an lvalue, so the call f() is an lvalue expression. -- end example ] -- end note ] 4 [ Note: some built-in operators expect lvalue operands. [ Example: built-in assignment operators all expect their left- hand operands to be lvalues. -- end example ] Other built-in operators yield rvalues, and some expect them. [ Example: the unary and binary + operators expect rvalue arguments and yield rvalue results. -- end example ] The discussion of each built-in operator in clause 5 indicates whether it expects lvalue operands and whether it yields an lvalue. -- end note ] 5 The result of calling a function that does not return a reference is an rvalue. User defined operators are functions, and whether such operators expect or yield lvalues is determined by their parameter and return types. 6 An expression which holds a temporary object resulting from a cast to a nonreference type is an rvalue (this includes the explicit creation of an object using functional notation (5.2.3)). 7 Whenever an lvalue appears in a context where an rvalue is expected, the lvalue is converted to an rvalue; see 4.1, 4.2, and 4.3. 8 The discussion of reference initialization in 8.5.3 and of temporaries in 12.2 indicates the behavior of lvalues and rvalues in other significant contexts. 9 Class rvalues can have cv-qualified types; non-class rvalues always have cv-unqualified types. Rvalues shall always have complete types or the void type; in addition to these types, lvalues can also have incomplete types. 10 An lvalue for an object is necessary in order to modify the object except that an rvalue of class type can also be used to modify its referent under certain circumstances. [ Example: a member function called for an object (9.3) can modify the object. -- end example ] 11 Functions cannot be modified, but pointers to functions can be modifiable. 51) Expressions such as invocations of constructors and of functions that return a class type refer to objects, and the implementation can invoke a member function upon such objects, but the expressions are not lvalues. Draft 3.10 Lvalues and rvalues Basic concepts 64 12 A pointer to an incomplete type can be modifiable. At some point in the program when the pointed to type is complete, the object at which the pointer points can also be modified. 13 The referent of a const-qualified expression shall not be modified (through that expression), except that if it is of class type and has a mutable component, that component can be modified (7.1.5.1). 14 If an expression can be used to modify the object to which it refers, the expression is called modifiable. A program that attempts to modify an object through a nonmodifiable lvalue or rvalue expression is ill-formed. 15 If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined52) -- the dynamic type of the object, -- a cv-qualified version of the dynamic type of the object, -- a type similar (as defined in 4.4) 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 members (including, recur- sively, a 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 or unsigned char type. 52) The intent of this list is to specify those circumstances in which an object may or may not be aliased. Draft Chapter 4 Standard conversions [conv] 1 Standard conversions are implicit conversions defined for built-in types. Clause 4 enumerates the full set of such con- versions. 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 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. 2 [ 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 5). -- When used in the condition of an if statement or iteration statement (6.4, 6.5). The destination type is bool. -- When used in the expression of a switch statement. The destination type is integral (6.4). -- 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. See 8.5, 8.5.3. -- end note ] 3 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 (8.5). The effect of the implicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The result is an lvalue if T is a reference type (8.3.2), and an rvalue otherwise. The expression e is used as an lvalue if and only if the initialization uses it as an lvalue. 4 [ Note: For user-defined types, user-defined conversions are considered as well; see 12.3. In general, an implicit conver- sion sequence (13.3.3.1) consists of a standard conversion sequence followed by a user-defined conversion followed by another standard conversion sequence. 5 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 4.1 Lvalue-to-rvalue conversion Standard conversions 66 contexts. -- end note ] 4.1 Lvalue-to-rvalue conversion [conv.lval] 1 An lvalue (3.10) of a non-function, non-array type T can be converted to an rvalue. If T is an incomplete type, a program that necessitates this conversion is ill-formed. If the object to which the lvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior. If T is a non-class type, the type of the rvalue is the cv-unqualified version of T. Otherwise, the type of the rvalue is T.53) 2 The value contained in the object indicated by the lvalue is the rvalue result. When an lvalue-to-rvalue conversion occurs within the operand of sizeof (5.3.3) the value contained in the referenced object is not accessed, since that operator does not evaluate its operand. 3 [ Note: See also 3.10. -- end note ] 4.2 Array-to-pointer conversion [conv.array] 1 An lvalue or rvalue of type "array of N T" or "array of unknown bound of T" can be converted to an rvalue of type "pointer to T". The result is a pointer to the first element of the array. 2 A string literal (2.13.4) that is not a wide string literal can be converted to an rvalue of type "pointer to char"; a wide string literal can be converted to an rvalue of type "pointer to wchar_t". In either case, the result is a pointer to the first element of the array. This conversion is considered only when there is an explicit appropriate pointer target type, and not when there is a general need to convert from an lvalue to an rvalue. [ Note: this conversion is deprecated. See Annex D. -- end note ] For the purpose of ranking in overload resolution (13.3.3.1.1), this conversion is considered an array-to-pointer conversion followed by a qualification conversion (4.4). [ Example: "abc" is converted to "pointer to const char" as an array-to-pointer conversion, and then to "pointer to char" as a qualification conversion. -- end example ] 4.3 Function-to-pointer conversion [conv.func] 1 An lvalue of function type T can be converted to an rvalue of type "pointer to T ." The result is a pointer to the function.54) 2 [ Note: See 13.4 for additional rules for the case where the function is overloaded. -- end note ] 4.4 Qualification conversions [conv.qual] 1 An rvalue of type "pointer to cv1 T " can be converted to an rvalue of type "pointer to cv2 T " if "cv2 T " is more cv-qualified than "cv1 T ." 2 An rvalue of type "pointer to member of X of type cv1 T " can be converted to an rvalue of type "pointer to member of X of type cv2 T " if "cv2 T " is more cv-qualified than "cv1 T ." 3 [ Note: Function types (including those used in pointer to member function types) are never cv-qualified (8.3.5). -- end note ] 4 A conversion can add cv-qualifiers at levels other than the first in multi-level pointers, subject to the following rules:55) 53) In C++ class rvalues can have cv-qualified types (because they are objects). This differs from ISO C, in which non-lvalues never have cv-qualified types. 54) This conversion never applies to non-static member functions because an lvalue that refers to a non-static member function cannot be obtained. 55) These rules ensure that const-safety is preserved by the conversion. Draft 67 Standard conversions 4.5 Integral promotions Two pointer types T1 and T2 are similar if there exists a type T and integer n > 0 such that: T1 is cv1,0 pointer to cv1,1 pointer to · · · cv1,n-1 pointer to cv1,n T and T2 is cv2,0 pointer to cv2,1 pointer to · · · cv2,n-1 pointer to cv2,n T where each cvi, j is const, volatile, const volatile, or nothing. The n-tuple of cv-qualifiers after the first in a pointer type, e.g., cv1,1 , cv1,2 , · · ·, cv1,n in the pointer type T1, is called the cv-qualification signature of the pointer type. An expression of type T1 can be converted to type T2 if and only if the following conditions are satisfied: -- the pointer types are similar. -- for every j > 0, if const is in cv1, j then const is in cv2, j , and similarly for volatile. -- if the cv1, j and cv2, j are different, then const is in every cv2,k for 0 < k < j. [ Note: if a program could assign a pointer of type T** to a pointer of type const T** (that is, if line //1 below was 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 ] 5 A multi-level pointer to member type, or a multi-level mixed pointer and pointer to member type has the form: cv0 P0 to cv1 P1 to · · · cvn-1 Pn-1 to cvn T where Pi is either a pointer or pointer to member and where T is not a pointer type or pointer to member type. 6 Two multi-level pointer to member types or two multi-level mixed pointer and pointer to member types T1 and T2 are similar if there exists a type T and integer n > 0 such that: T1 is cv1,0 P0 to cv1,1 P1 to · · · cv1,n-1 Pn-1 to cv1,n T and T2 is cv2,0 P0 to cv2,1 P1 to · · · cv2,n-1 Pn-1 to cv2,n T 7 For similar multi-level pointer to member types and similar multi-level mixed pointer and pointer to member types, the rules for adding cv-qualifiers are the same as those used for similar pointer types. 4.5 Integral promotions [conv.prom] 1 An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int rvalue can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int. Draft 4.6 Floating point promotion Standard conversions 68 2 An rvalue of type wchar_t (3.9.1) can be converted to an rvalue of the first of the following types that can represent all the values of its underlying type: int, unsigned int, long, or unsigned long. An rvalue of an enumeration type (7.2) can be converted to an rvalue of the first of the following types that can represent all the values of the enumeration (i.e. the values in the range bmin to bmax as described in 7.2: int, unsigned int, long, or unsigned long. 3 An rvalue for an integral bit-field (9.6) can be converted to an rvalue 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. 4 An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one. 5 These conversions are called integral promotions. 4.6 Floating point promotion [conv.fpprom] 1 An rvalue of type float can be converted to an rvalue of type double. The value is unchanged. 2 This conversion is called floating point promotion. 4.7 Integral conversions [conv.integral] 1 An rvalue of an integer type can be converted to an rvalue of another integer type. An rvalue of an enumeration type can be converted to an rvalue of an integer type. 2 If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (mod- ulo 2n 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 ] 3 If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined. 4 If the destination type is bool, see 4.12. If the source type is bool, the value false is converted to zero and the value true is converted to one. 5 The conversions allowed as integral promotions are excluded from the set of integral conversions. 4.8 Floating point conversions [conv.double] 1 An rvalue of floating point type can be converted to an rvalue 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. 2 The conversions allowed as floating point promotions are excluded from the set of floating point conversions. 4.9 Floating-integral conversions [conv.fpint] 1 An rvalue of a floating point type can be converted to an rvalue 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 4.12. -- end note ] 2 An rvalue of an integer type or of an enumeration type can be converted to an rvalue of a floating point type. The result is exact if possible. Otherwise, it is an implementation-defined choice of either the next lower or higher representable Draft 69 Standard conversions 4.10 Pointer conversions 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 source type is bool, the value false is converted to zero and the value true is converted to one. 4.10 Pointer conversions [conv.ptr] 1 A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to zero. 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 pointer to object or pointer to function type. 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 (4.4). 2 An rvalue of type "pointer to cv T ," where T is an object type, can be converted to an rvalue of type "pointer to cv void". The result of converting a "pointer to cv T" to a "pointer to cv void" points to the start of the storage location where the object of type T resides, as if the object is a most derived object (1.8) of type T (that is, not a base class subobject). 3 An rvalue of type "pointer to cv D", where D is a class type, can be converted to an rvalue of type "pointer to cv B", where B is a base class (clause 10) of D. If B is an inaccessible (clause 11) or ambiguous (10.2) 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. 4.11 Pointer to member conversions [conv.mem] 1 A null pointer constant (4.10) 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. 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 (4.4). 2 An rvalue of type "pointer to member of B of type cv T", where B is a class type, can be converted to an rvalue of type "pointer to member of D of type cv T", where D is a derived class (clause 10) of B. If B is an inaccessible (clause 11), ambiguous (10.2) or virtual (10.1) 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", it can be dereferenced with a D object. The result is the same as if the pointer to member of B were dereferenced with the B subobject of D. The null member pointer value is converted to the null member pointer value of the destination type.56) 4.12 Boolean conversions [conv.bool] 1 An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue 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. 56) 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) (4.10, clause 10). This inversion is necessary to ensure type safety. Note that a pointer to member is not a pointer to object or a pointer to function 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*. Draft 4.12 Boolean conversions Standard conversions 70 Draft Chapter 5 Expressions [expr] 1 [ Note: Clause 5 defines the syntax, order of evaluation, and meaning of expressions. 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. 2 Operators can be overloaded, that is, given meaning when applied to expressions of class type (clause 9) or enumeration type (7.2). Uses of overloaded operators are transformed into function calls as described in 13.5. Overloaded operators obey the rules for syntax specified in clause 5, but the requirements of operand type, lvalue, and evaluation order are replaced by the rules for function call. Relations between operators, such as ++a meaning a+=1, are not guaranteed for overloaded operators (13.5), and are not guaranteed for operands of type bool. -- end note ] 3 Clause 5 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 5; see 13.3.1.2, 13.6. 4 Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expres- sions, and the order in which side effects take place, is unspecified.57) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined. [ Example: i = v [ i ++]; / / the behavior is undefined i = 7 , i ++ , i ++; / / i becomes 9 i = ++ i + 1; / / the behavior is undefined i = i + 1; / / the value of i is incremented -- end example ] 5 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, unless such an expression is a constant expression (5.19), in which case the program is ill-formed. [ Note: most existing implementations of C++ ignore integer overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all floating point exceptions vary among machines, and is usually adjustable by a library function. -- end note ] 6 If an expression initially has the type "reference to T (8.3.2, 8.5.3), 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. 57) The precedence of operators is not directly specified, but it can be derived from the syntax. 5.1 Primary expressions Expressions 72 7 An expression designating an object is called an object-expression. 8 Whenever an lvalue expression appears as an operand of an operator that expects an rvalue for that operand, the lvalue-to- rvalue (4.1), array-to-pointer (4.2), or function-to-pointer (4.3) standard conversions are applied to convert the expression to an rvalue. [ Note: because cv-qualifiers are removed from the type of an expression of non-class type when the expression is converted to an rvalue, an lvalue expression of type const int can, for example, be used where an rvalue expression of type int is required. -- end note ] 9 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 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 (4.5) shall be performed on both operands.58) -- Then, if either operand is unsigned long the other shall be converted to unsigned long. -- Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int otherwise both operands shall be converted to unsigned long int. -- Otherwise, if either operand is long, the other shall be converted to long. -- Otherwise, if either operand is unsigned, the other shall be converted to unsigned. [ Note: otherwise, the only remaining case is that both operands are int -- end note ] 10 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.59) 5.1 Primary expressions [expr.prim] 1 Primary expressions are literals, names, and names qualified by the scope resolution operator ::. 58) As a consequence, operands of type bool, wchar_t, or an enumerated type are converted to some integral type. 59) The cast and assignment operators must still perform their specific conversions as described in 5.4, 5.2.9 and 5.17. Draft 73 Expressions 5.1 Primary expressions primary-expression: literal this ( expression ) id-expression id-expression: unqualified-id qualified-id unqualified-id: identifier operator-function-id conversion-function-id class-name template-id 2 A literal is a primary expression. Its type depends on its form (2.13). A string literal is an lvalue; all other literals are rvalues. 3 The keyword this names a pointer to the object for which a non-static member function (9.3.2) is invoked. The keyword this shall be used only inside a non-static class member function body (9.3) or in a constructor mem-initializer (12.6.2). The type of the expression is a pointer to the function's class (9.3.2), possibly with cv-qualifiers on the class type. The expression is an rvalue. 4 The operator :: followed by an identifier, a qualified-id, or an operator-function-id is a primary-expression. Its type is specified by the declaration of the identifier, qualified-id, or operator-function-id. The result is the entity denoted by the identifier, qualified-id, or operator-function-id. The result is an lvalue if the entity is a function or variable. The identifier, qualified-id, or operator-function-id shall have global namespace scope or be visible in global scope because of a using-directive (7.3.4). [ Note: the use of :: allows a type, an object, a function, an enumerator, or a namespace declared in the global namespace to be referred to even if its identifier has been hidden (3.4.3). -- end note ] 5 A parenthesized expression is a primary expression whose type and value are identical to those of the enclosed expres- sion. The presence of parentheses does not affect whether the expression is an lvalue. The parenthesized expression can be used in exactly the same contexts as those where the enclosed expression can be used, and with the same meaning, except as otherwise indicated. 6 An id-expression is a restricted form of a primary-expression. [ Note: an id-expression can appear after . and -> operators (5.2.5). -- end note ] 7 An identifier is an id-expression provided it has been suitably declared (clause 7). [ Note: for operator-function-ids, see 13.5; for conversion-function-ids, see 12.3.2; for template-ids, see 14.2. A class-name prefixed by denotes a destructor; see 12.4. 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 (9.3.1). -- end note ] The type of the expression is the type of the identifier. The result is the entity denoted by the identifier. The result is an lvalue if the entity is a function, variable, or data member. qualified-id: ::opt nested-name-specifier templateopt unqualified-id :: identifier :: operator-function-id :: template-id Draft 5.2 Postfix expressions Expressions 74 nested-name-specifier: type-name :: namespace-name :: nested-name-specifier identifier :: nested-name-specifier templateopt template-id :: A nested-name-specifier that names a class, optionally followed by the keyword template (14.2), and then followed by the name of a member of either that class (9.2) or one of its base classes (clause 10), is a qualified-id; 3.4.3.1 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. [ Note: a class member can be referred to using a qualified-id at any point in its potential scope (3.3.6). -- end note ] Where class- name :: class-name is used, and the two class-names refer to the same class, this notation names the constructor (12.1). Where class-name :: class-name is used, the two class-names shall refer to the same class; this notation names the destructor (12.4). [ Note: a typedef-name that names a class is a class-name (9.1). -- end note ] 8 A nested-name-specifier that names a namespace (7.3), 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; 3.4.3.2 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. 9 In a qualified-id, if the id-expression 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. 10 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 (5.2.5) in which the object-expression refers to the member's class or a class derived from that class, or -- to form a pointer to member (5.3.1), or -- in the body of a non-static member function of that class or of a class derived from that class (9.3.1), or -- in a mem-initializer for a constructor for that class or for a class derived from that class (12.6.2). 5.2 Postfix expressions [expr.post] 1 Postfix expressions group left-to-right. Draft 75 Expressions 5.2 Postfix expressions postfix-expression: primary-expression postfix-expression [ expression ] postfix-expression ( expression-listopt ) simple-type-specifier ( expression-listopt ) typename-specifier ( expression-listopt ) postfix-expression . templateopt id-expression postfix-expression -> templateopt id-expression postfix-expression . pseudo-destructor-name postfix-expression -> pseudo-destructor-name postfix-expression ++ postfix-expression -- dynamic_cast < type-id > ( expression ) static_cast < type-id > ( expression ) reinterpret_cast < type-id > ( expression ) const_cast < type-id > ( expression ) typeid ( expression ) typeid ( type-id ) expression-list: assignment-expression expression-list , assignment-expression pseudo-destructor-name: ::opt nested-name-specifieropt type-name :: type-name ::opt nested-name-specifier template template-id :: type-name ::opt nested-name-specifieropt type-name 5.2.1 Subscripting [expr.sub] 1 A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type "pointer to T and the other shall have enumeration or integral type. The result is an lvalue of type "T." The type "T" shall be a completely-defined object type.60) The expression E1[E2] is identical (by definition) to *((E1)+(E2)) [ Note: see 5.3 and 5.7 for details of * and + and 8.3.4 for details of arrays. -- end note ] 5.2.2 Function call [expr.call] 1 There are two kinds of function call: ordinary function call and member function61) (9.3) call. A function call is a postfix expression followed by parentheses containing a possibly empty, comma-separated list of expressions which constitute the arguments to the function. For an ordinary function call, the postfix expression shall be either an lvalue that refers to a function (in which case the function-to-pointer standard conversion (4.3) is suppressed on the postfix expression), or it shall have pointer to function type. Calling a function through an expression whose function type has a language linkage that is different from the language linkage of the function type of the called function's definition is undefined (7.5). For a member function call, the postfix expression shall be an implicit (9.3.1, 9.4) or explicit class member access (5.2.5) whose id-expression is a function member name, or a pointer-to-member expression (5.5) selecting a function member. The first expression in the postfix expression is then called the object expression, and the call is as a member of the object pointed to or referred to. 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 9.3.1). -- end note ] If a function or member function name is used, the name can be overloaded (clause 13), in which case the appropriate function shall be 60) This is true even if the subscript operator is used in the following common idiom: &x[0]. 61) A static member function (9.4) is an ordinary function. Draft 5.2 Postfix expressions Expressions 76 selected according to the rules in 13.3. The function called in a member function call is normally selected according to the static type of the object expression (clause 10), but if that function is virtual and is not specified using a qualified- id then the function actually called will be the final overrider (10.3) of the selected function in the dynamic type of the object expression [ Note: the dynamic type is the type of the object pointed or referred to by the current value of the object expression. 12.7 describes the behavior of virtual function calls when the object-expression refers to an object under construction or destruction. -- end note ] 2 [ Note: if a function or member function name is used, and name lookup (3.4) does not find a declaration of that name, the program is ill-formed. No function is implicitly declared by such a call. -- end note ] 3 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 type shall be a complete object type, a reference type or the type void. 4 When a function is called, each parameter (8.3.5) shall be initialized (8.5, 12.8, 12.1) with its corresponding argument. If the function is a non-static member function, the this parameter of the function (9.3.2) shall be initialized with a pointer to the object of the call, converted as if by an explicit type conversion (5.4). [ 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. See 10.2, 11.2, and 5.2.5. -- 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 ] During the initialization of a parameter, an implementation may avoid the construction of extra temporaries by combining the conversions on the associated argument and/or the construction of temporaries with the initialization of the parameter (see 12.2). The lifetime of a parameter ends when the function in which it is defined returns. 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 15) with a handler that could handle the exception, this handler is not considered. -- end example ] The value of a function call is the value returned by the called function 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. 5 [ 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 (8.3.2); 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 (7.1.5, 2.13, 2.13.4, 8.3.4, 12.2). In addition, it is possible to modify the values of nonconstant objects through pointer parameters. -- end note ] 6 A function can be declared to accept fewer arguments (by declaring default arguments (8.3.6)) or more arguments (by using the ellipsis, ... 8.3.5) than the number of parameters in the function definition (8.4). [ Note: this implies that, except where the ellipsis (...) is used, a parameter is available for each argument. -- end note ] 7 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 (18.7). The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are performed on the argument expression. After these conversions, if the argument does not have arithmetic, enumeration, pointer, pointer to member, or class type, the program is ill-formed. If the argument has a non-POD class type (clause 9), the behavior is undefined. If the argument has integral or enumeration type that is subject to the integral promotions (4.5), or a floating point type that is subject to the floating point promotion Draft 77 Expressions 5.2 Postfix expressions (4.6), the value of the argument is converted to the promoted type before the call. These promotions are referred to as the default argument promotions. 8 The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered. The order of evaluation of the postfix expression and the argument expression list is unspecified. 9 Recursive calls are permitted, except to the function named main (3.6.1). 10 A function call is an lvalue if and only if the result type is a reference. 5.2.3 Explicit type conversion (functional notation) [expr.type.conv] 1 A simple-type-specifier (7.1.5) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in de- finedness, and if defined in meaning) to the corresponding cast expression (5.4). If the simple-type-specifier specifies a class type, the class type shall be complete. If the expression list specifies more than a single value, the type shall be a class with a suitably declared constructor (8.5, 12.1), and the expression T(x1, x2, ...) is equivalent in effect to the declaration T t(x1, x2, ...); for some invented temporary variable t, with the result being the value of t as an rvalue. 2 The expression T(), where T is a simple-type-specifier (7.1.5.2) for a non-array complete object type or the (possibly cv-qualified) void type, creates an rvalue of the specified type, which is value-initialized (8.5; no initialization is done for the void() case). [ Note: if T is a non-class type that is cv-qualified, the cv-qualifiers are ignored when determining the type of the resulting rvalue (3.10). -- end note ] 5.2.4 Pseudo destructor call [expr.pseudo] 1 The use of a pseudo-destructor-name after a dot . or arrow -> operator represents the destructor for the non-class type named by type-name. 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. 2 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 type designated by the pseudo-destructor-name shall be the same as the object type. Furthermore, the two type-names in a pseudo-destructor-name of the form ::opt nested-name-specifieropt type-name :: type-name shall designate the same scalar type. The cv-unqualified versions of the object type and of the type designated by the pseudo-destructor-name shall be the same type. 5.2.5 Class member access [expr.ref] 1 A postfix expression followed by a dot . or an arrow ->, optionally followed by the keyword template (14.8.1), and then followed by an id-expression, is a postfix expression. The postfix expression before the dot or arrow is evaluated;62) the result of that evaluation, together with the id-expression, determine the result of the entire postfix expression. 2 For the first option (dot) the type of the first expression (the object expression ) shall be "class object" (of a complete type). For the second option (arrow) the type of the first expression (the pointer expression ) shall be "pointer to class object" (of a complete type). In these cases, the id-expression shall name a member of the class or of one of its base 62) This 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. Draft 5.2 Postfix expressions Expressions 78 classes. [ Note: because the name of a class is inserted in its class scope (clause 9), the name of a class is also considered a nested member of that class. -- end note ] [ Note: 3.4.5 describes how names are looked up after the . and -> operators. -- end note ] 3 If E1 has the type "pointer to class X," then the expression E1->E2 is converted to the equivalent form (*(E1)).E2; the remainder of 5.2.5 will address only the first option (dot)63) . Abbreviating object-expression.id-expression as E1.E2, then the type and lvalue properties of this expression are determined as follows. In the remainder of 5.2.5, cq represents either const or the absence of const vq represents either volatile or the absence of volatile. cv represents an arbitrary set of cv-qualifiers, as defined in 3.9.3. 4 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, it is an rvalue. 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 (13.3) 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 returning T", then E1.E2 is not an lvalue. The expression designates a non-static member func- tion. The expression can be used only as the left-hand operand of a member function call (9.3). [ Note: any redundant set of parentheses surrounding the expression is ignored (5.1). -- 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 not an lvalue. The type of E1.E2 is T. [ Note: "class objects" can be structures (9.2) and unions (9.5). Classes are discussed in clause 9. -- end note ] 5 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 (10.2) of the naming class (11.2) of E2. 63) Note that if E1 has the type "pointer to class X," then (*(E1)) is an lvalue. Draft 79 Expressions 5.2 Postfix expressions 5.2.6 Increment and decrement [expr.post.incr] 1 The value obtained by applying a postfix ++ is the value that the operand had before applying the operator. [ 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 or a pointer to a complete object type. After the result is noted, the value of the object is modified by adding 1 to it, unless the object is of type bool, in which case it is set to true. [ Note: this use is deprecated, see Annex D. -- end note ] The result is an rvalue. The type of the result is the cv-unqualified version of the type of the operand. See also 5.7 and 5.17. The operand of postfix - is decremented analogously to the postfix ++ operator, except that the operand shall not be of type bool. [ Note: For prefix increment and decrement, see 5.3.2. -- end note ] 5.2.7 Dynamic cast [expr.dynamic.cast] 1 The result of the expression dynamic_cast(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." Types shall not be defined in a dynamic_cast. The dynamic_cast operator shall not cast away constness (5.2.11). 2 If T is a pointer type, v shall be an rvalue of a pointer to complete class type, and the result is an rvalue of type T. If T is a 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. 3 If the type of v is the same as the required result type (which, for convenience, will be called R in this description), or it is the same as R except that the class object type in R is more cv-qualified than the class object type in v, the result is v (converted if necessary). 4 If the value of v is a null pointer value in the pointer case, the result is the null pointer value of type R. 5 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 an lvalue for the unique B subobject of the D object referred to by v. 64) In both the pointer and reference cases, cv1 shall be the same cv-qualification as, or greater cv-qualification than, cv2, and B shall be an accessible unambiguous 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 ] 6 Otherwise, v shall be a pointer to or an lvalue of a polymorphic type (10.3). 7 If T is "pointer to cv void," then the result is a pointer to the most derived object pointed to by v. Otherwise, a run-time 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. 8 The run-time check logically executes as follows: 64) The most derived object (1.8) pointed or referred to by v can contain other B objects as base classes, but these are ignored. Draft 5.2 Postfix expressions Expressions 80 -- If, in the most derived object pointed (referred) to by v, v points (refers) to a public base class subobject of a T object, and if only one object of type T is derived from the subobject pointed (referred) to by v the result is a pointer (an lvalue referring) to that T 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 T, that is unambiguous and public, the result is a pointer (an lvalue referring) to the T subobject of the most derived object. -- Otherwise, the run-time check fails. 9 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 std::bad_cast (18.5.2). [ 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 ); / / fails } 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 0 / / 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: 12.7 describes the behavior of a dynamic_cast applied to an object under construction or destruction. -- end note ] 5.2.8 Type identification [expr.typeid] 1 The result of a typeid expression is an lvalue of static type const std::type_info (18.5.1) and dynamic type const std::type_info or const name where name is an implementation-defined class derived from std :: type_info Draft 81 Expressions 5.2 Postfix expressions which preserves the behavior described in 18.5.1.65) 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. 2 When typeid is applied to an lvalue expression whose type is a polymorphic class type (10.3), the result refers to a std::type_info object representing the type of the most derived object (1.8) (that is, the dynamic type) to which the lvalue refers. If the lvalue expression is obtained by applying the unary * operator to a pointer66) and the pointer is a null pointer value (4.10), the typeid expression throws the std::bad_typeid exception (18.5.3). 3 When typeid is applied to an expression other than an lvalue of a polymorphic class type, the result refers to a std::type_info object representing the static type of the expression. Lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) conversions are not applied to the expression. If the type of the expression is a class type, the class shall be completely-defined. The expression is not evaluated. 4 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 type, the result of the typeid expression refers to a std::type_info object representing the 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. Types shall not be defined in the type-id. 5 The top-level cv-qualifiers of the lvalue expression or the type-id that is the operand of typeid are always ignored. [ 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 ] 6 If the header (18.5.1) is not included prior to a use of typeid, the program is ill-formed. 7 [ Note: 12.7 describes the behavior of typeid applied to an object under construction or destruction. -- end note ] 5.2.9 Static cast [expr.static.cast] 1 The result of the expression static_cast(v) is the result of converting the expression v to type T. If T is a reference type, the result is an lvalue; otherwise, the result is an rvalue. Types shall not be defined in a static_cast. The static_cast operator shall not cast away constness (5.2.11). 2 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 10) from B, if a valid standard conversion from "pointer to D" to "pointer to B" exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is not a virtual base class of D. The result is an lvalue of type cv2 D. If the lvalue of type cv1 B is actually a subobject of an object of type D, the lvalue refers to the enclosing object of type D. Otherwise, the result of the cast is undefined. [ Example: 65) The recommended name for such a class is extended_type_info. 66) If p is an expression of pointer type, then *p, (*p), *(p), ((*p)), *((p)), and so on all meet this requirement. Draft 5.2 Postfix expressions Expressions 82 struct B {}; struct D : public B {}; D d; B & br = d ; static_cast < D & >( br ); / / produces lvalue to the original d object -- end example ] 3 Otherwise, an expression e can be explicitly converted to a type T using a static_cast of the form static_- cast(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The result is an lvalue if T is a reference type (8.3.2), and an rvalue otherwise. The expression e is used as an lvalue if and only if the initialization uses it as an lvalue. 4 Otherwise, the static_cast shall perform one of the conversions listed below. No other conversion shall be performed explicitly using a static_cast. 5 Any expression can be explicitly converted to type cv void. The expression value is discarded. [ Note: however, if the value is in a temporary variable (12.2), the destructor for that variable is not executed until the usual time, and the value of the variable is preserved for the purpose of executing the destructor. -- end note ] The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are not applied to the expression. 6 The inverse of any standard conversion sequence (clause 4), other than the lvalue-to-rvalue (4.1), array-to-pointer (4.2), function-to-pointer (4.3), and boolean (4.12) conversions, 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 ] 7 The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) conversions are applied to the operand. Such a static_cast is subject to the restriction that the explicit conversion does not cast away constness (5.2.11), and the following additional rules for specific cases: 8 A value of integral or enumeration type can be explicitly converted to an enumeration type. The value is unchanged if the original value is within the range of the enumeration values (7.2). Otherwise, the resulting enumeration value is unspecified. 9 An rvalue of type "pointer to cv1 B," where B is a class type, can be converted to an rvalue of type "pointer to cv2 D," where D is a class derived (clause 10) from B, if a valid standard conversion from "pointer to D" to "pointer to B" exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is not a virtual base class of D. The null pointer value (4.10) is converted to the null pointer value of the destination type. If the rvalue 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 result of the cast is undefined. Draft 83 Expressions 5.2 Postfix expressions 10 An rvalue of type "pointer to member of D of type cv1 T" can be converted to an rvalue of type "pointer to member of B" of type cv2 T, where B is a base class (clause 10) of D, if a valid standard conversion from "pointer to member of B of type T" to "pointer to member of D of type T" exists (4.11), and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1.67) The null member pointer value (4.11) 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 result of the cast is undefined. [ Note: although class B need not contain the original member, the dynamic type of the object on which the pointer to member is dereferenced must contain the original member; see 5.5. -- end note ] 11 An rvalue of type "pointer to cv1 void" can be converted to an rvalue 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. A value of type pointer to object converted to "pointer to cv void" and back, possibly with different cv-qualification, shall have its original value.[ 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 ] 5.2.10 Reinterpret cast [expr.reinterpret.cast] 1 The result of the expression reinterpret_cast(v) is the result of converting the expression v to type T. If T is a reference type, the result is an lvalue; otherwise, the result is an rvalue and the lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are performed on the the expression v. Types shall not be defined in a reinterpret_cast. Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast. 2 The reinterpret_cast operator shall not cast away constness. [ Note: see 5.2.11 for the definition of "casting away constness". Subject to the restrictions in this section, an expression may be cast to its own type using a reinterpret_- cast operator. -- end note ] 3 The mapping performed by reinterpret_cast is implementation-defined. [ Note: it might, or might not, produce a representation different from the original value. -- end note ] 4 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 ] 5 A value of integral type or enumeration type can be explicitly converted to a pointer.68) 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. 6 A pointer to a function can be explicitly converted to a pointer to a function of a different type. The effect of calling a function through a pointer to a function type (8.3.5) that is not the same as the type used in the definition of the function is undefined. Except that converting an rvalue 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 4.10 for more details of pointer conversions. -- end note ] 67) Function types (including those used in pointer to member function types) are never cv-qualified; see 8.3.5. 68) Converting an integral constant expression (5.19) with value zero always yields a null pointer (4.10), but converting other expressions that happen to have value zero need not yield a null pointer. Draft 5.2 Postfix expressions Expressions 84 7 A pointer to an object can be explicitly converted to a pointer to an object of different type.69) Except that converting an rvalue 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, the result of such a pointer conversion is unspecified. 8 Converting a pointer to a function into a pointer to an object 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 an rvalue of one type to the other type and back, possibly with different cv-qualification, shall yield the original pointer value. 9 The null pointer value (4.10) is converted to the null pointer value of the destination type. 10 An rvalue of type "pointer to member of X of type T1" can be explicitly converted to an rvalue of type "pointer to member of Y of type T2" if T1 and T2 are both function types or both object types.70) The null member pointer value (4.11) 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 an rvalue 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 an rvalue 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. 11 An lvalue 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. That is, a reference cast reinterpret_- cast(x) has the same effect as the conversion *reinterpret_cast(&x) with the built-in & and * operators. The result is an lvalue that refers to the same object as the source lvalue, but with a different type. No temporary is created, no copy is made, and constructors (12.1) or conversion functions (12.3) are not called.71) 5.2.11 Const cast [expr.const.cast] 1 The result of the expression const_cast(v) is of type T. If T is a reference type, the result is an lvalue; other- wise, the result is an rvalue and, the lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are performed on the expression v. Types shall not be defined in a const_cast. Conversions that can be performed explicitly using const_cast are listed below. No other conversion shall be performed explicitly using const_cast. 2 [ Note: Subject to the restrictions in this section, an expression may be cast to its own type using a const_cast operator. -- end note ] 3 For two pointer types T1 and T2 where T1 is cv1,0 pointer to cv1,1 pointer to · · · cv1,n-1 pointer to cv1,n T and T2 is cv2,0 pointer to cv2,1 pointer to · · · cv2,n-1 pointer to cv2,n T 69) The types may have different cv-qualifiers, subject to the overall restriction that a reinterpret_cast cannot cast away constness. 70) T1 and T2 may have different cv-qualifiers, subject to the overall restriction that a reinterpret_cast cannot cast away constness. 71) This is sometimes referred to as a type pun. Draft 85 Expressions 5.2 Postfix expressions where T is any object type or the void type and where cv1,k and cv2,k may be different cv-qualifications, an rvalue of type T1 may be explicitly converted to the type T2 using a const_cast. The result of a pointer const_cast refers to the original object. 4 An lvalue of type T1 can be explicitly converted to an lvalue of type T2 using the cast const_cast (where T1 and T2 are object types) if a pointer to T1 can be explicitly converted to the type pointer to T2 using a const_cast. The result of a reference const_cast refers to the original object. 5 For a const_cast involving pointers to data members, multi-level pointers to data members and multi-level mixed pointers and pointers to data members (4.4), the rules for const_cast are the same as those used for pointers; the "member" aspect of a pointer to member is ignored when determining where the cv-qualifiers are added or removed by the const_cast. The result of a pointer to data member const_cast refers to the same member as the original (uncast) pointer to data member. 6 A null pointer value (4.10) is converted to the null pointer value of the destination type. The null member pointer value (4.11) is converted to the null member pointer value of the destination type. 7 [ 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-qualifier72) may produce undefined behavior (7.1.5.1). -- end note ] 8 The following rules define the process known as casting away constness. In these rules Tn and Xn represent types. For two pointer types: X1 is T1cv1,1 * · · · cv1,N * where T1 is not a pointer type X2 is T2cv2,1 * · · · cv2,M * where T2 is not a pointer type K is min(N, M) casting from X1 to X2 casts away constness if, for a non-pointer type T there does not exist an implicit conversion (clause 4) from: Tcv1,(N-K+1) * cv1,(N-K+2) * · · · cv1,N * to Tcv2,(M-K+1) * cv2,(M-K+2) * · · · cv2,M * 9 Casting from an lvalue of type T1 to an lvalue of type T2 using a reference cast casts away constness if a cast from an rvalue of type "pointer to T1" to the type "pointer to T2" casts away constness. 10 Casting from an rvalue of type "pointer to data member of X of type T1" to the type "pointer to data member of Y of type T2" casts away constness if a cast from an rvalue of type "pointer to T1" to the type "pointer to T2" casts away constness. 11 For multi-level pointer to members and multi-level mixed pointers and pointer to members (4.4), the "member" aspect of a pointer to member level is ignored when determining if a const cv-qualifier has been cast away. 12 [ 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, 72) const_cast is not limited to conversions that cast away a const-qualifier. Draft 5.3 Unary expressions Expressions 86 the conversion from a pointer to a const member function to a pointer to a non-const member function, are not covered. -- end note ] 5.3 Unary expressions [expr.unary] 1 Expressions with unary operators group right-to-left. unary-expression: postfix-expression ++ cast-expression -- cast-expression unary-operator cast-expression sizeof unary-expression sizeof ( type-id ) new-expression delete-expression unary-operator: one of *&+-! 5.3.1 Unary operators [expr.unary.op] 1 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: a pointer to an incomplete type (other than cv void ) can be dereferenced. The lvalue thus obtained can be used in limited ways (to initialize a reference, for example); this lvalue must not be converted to an rvalue, see 4.1. -- end note ] 2 The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id. In the first case, if the type of the expression is "T," the type of the result is "pointer to T." In particular, the address of an object of type "cv T" is "pointer to cv T," with the same cv-qualifiers. For a qualified-id, if the member is a static member of type "T", the type of the result is plain "pointer to T." If the member is a non-static member of class C of type T, the type of the result is "pointer to member of class C of type T." [ Example: struct A { int i ; }; struct B : A { }; ... & B :: i ... / / has type int A::* -- end example ] [ Note: a pointer to member formed from a mutable non-static data member (7.1.1) does not reflect the mutable specifier associated with the non-static data member. -- end note ] 3 A pointer to member is only formed when an explicit & is used and its operand is a qualified-id not enclosed in paren- theses. [ 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" (4.3). Nor is &unqualified-id a pointer to member, even within the scope of the unqualified-id's class. -- end note ] 4 The address of an object of incomplete type can be taken, but if the complete type of that object is a class type that declares operator&() as a member function, then the behavior is undefined (and no diagnostic is required). The operand of & shall not be a bit-field. Draft 87 Expressions 5.3 Unary expressions 5 The address of an overloaded function (clause 13) can be taken only in a context that uniquely determines which version of the overloaded function is referred to (see 13.4). [ 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 ] 6 The operand of the unary + operator shall have arithmetic, 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. 7 The operand of the unary - operator shall have arithmetic or 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 2n , where n is the number of bits in the promoted operand. The type of the result is the type of the promoted operand. 8 The operand of the logical negation operator ! is implicitly converted to bool (clause 4); its value is true if the converted operand is false and false otherwise. The type of the result is bool. 9 The operand of ~ shall have integral or enumeration type; the result is the one's 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 unary- expression ~X(), where X is a class-name. The ambiguity is resolved in favor of treating ~ as a unary complement rather than treating ~X as referring to a destructor. 5.3.2 Increment and decrement [expr.pre.incr] 1 The operand of prefix ++ is modified by adding 1, or set to true if it is bool (this use is deprecated). The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type 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. If x is not of type bool, the expression ++x is equivalent to x+=1 [ Note: see the discussions of addition (5.7) and assignment operators (5.17) for information on conversions. -- end note ] 2 The operand of prefix - is modified by subtracting 1. The operand shall not be of type bool. 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 5.2.6. -- end note ] 5.3.3 Sizeof [expr.sizeof] 1 The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is not evaluated, or a parenthesized type-id. The sizeof operator shall not be applied to an expression that has function or incomplete type, or to an enumeration type before all its enumerators have been declared, or to the parenthesized name of such types, or to an lvalue 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 (3.9.1) is implementation-defined. [ Note: in particular, sizeof(bool) and sizeof(wchar_t) are implementation-defined.73) -- end note ] [ Note: See 1.7 for the definition of byte and 3.9 for the definition of object representation. -- end note ] 2 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 (1.8). The result of applying sizeof to a base 73) sizeof(bool) is not required to be 1. Draft 5.3 Unary expressions Expressions 88 class subobject is the size of the base class type.74) 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. 3 The sizeof operator can be applied to a pointer to a function, but shall not be applied directly to a function. 4 The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are not applied to the operand of sizeof. 5 Types shall not be defined in a sizeof expression. 6 The result is a constant of type std::size_t. [ Note: std::size_t is defined in the standard header (18.1). -- end note ] 5.3.4 New [expr.new] 1 The new-expression attempts to create an object of the type-id (8.1) 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 (1.8, 3.9, 10.4). [ 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 ] new-expression: ::opt new new-placementopt new-type-id new-initializeropt ::opt new new-placementopt ( type-id ) new-initializeropt new-placement: ( expression-list ) new-type-id: type-specifier-seq new-declaratoropt new-declarator: ptr-operator new-declaratoropt direct-new-declarator direct-new-declarator: [ expression ] direct-new-declarator [ constant-expression ] new-initializer: ( expression-listopt ) Entities created by a new-expression have dynamic storage duration (3.7.3). [ 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. 2 The new-type-id in a new-expression is the longest possible sequence of new-declarators. [ Note: this prevents ambigu- ities between declarator operators &, *, [], and their expression counterparts. -- end note ] [ Example: new int * i ; / / syntax error: parsed as (new int*) i / / not as (new int)*i 74) 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. Draft 89 Expressions 5.3 Unary expressions The * is the pointer declarator and not the multiplication operator. -- end example ] 3 [ 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 (3.9.2): new ( int (*[10])()); allocates an array of 10 pointers to functions (taking no argument and returning int. -- end example ] -- end note ] 4 The type-specifier-seq shall not contain class declarations, or enumeration declarations. 5 When the allocated object is an array (that is, the direct-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 ] 6 Every constant-expression in a direct-new-declarator shall be an integral constant expression (5.19) and evaluate to a strictly positive value. The expression in a direct-new-declarator shall have integral or enumeration type (3.9.1) with a non-negative value. [ Example: if n is a variable of type int, then new float[n][5] is well-formed (because n is the expression of a direct-new-declarator), but new float[5][n] is ill-formed (because n is not a constant-expression). If n is negative, the effect of new float[n][5] is undefined. -- end example ] 7 When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements. 8 A new-expression obtains storage for the object by calling an allocation function (3.7.3.1). If the new-expression termi- nates by throwing an exception, it may release storage by calling a deallocation function (3.7.3.2). 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 (3.7.3, 18.4.1.1, 18.4.1.2). A C++ program can provide alternative definitions of these functions (17.4.3.4) and/or class-specific versions (12.5). -- end note ] 9 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. 10 A 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 and unsigned char, the difference between the result of the new-expression and the address returned by the allocation function shall be an integral multiple of the most stringent alignment requirement (3.9) 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, 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 ] Draft 5.3 Unary expressions Expressions 90 11 The new-placement syntax is used to supply additional arguments to an allocation function. If used, overload resolution is performed on a function call created by assembling an argument list consisting of the amount of space requested (the first argument) and the expressions in the new-placement part of the new-expression (the second and succeeding arguments). The first of these arguments has type std::size_t and the remaining arguments have the corresponding types of the expressions in the new-placement. 12 [ Example: -- new T results in a call of operator new(sizeof(T)), -- new(2,f) T results in a call of operator new(sizeof(T),2,f), -- new T[5] results in a call of operator new[](sizeof(T)*5+x), and -- new(2,f) T[5] results in a call of operator new[](sizeof(T)*5+y,2,f). Here, x and y are non-negative unspecified values representing array allocation overhead; the result of the new-expres- sion 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 ] 13 [ Note: unless an allocation function is declared with an empty exception-specification (15.4), throw(), it indicates failure to allocate storage by throwing a bad_alloc exception (clause 15, 18.4.2.1); it returns a non-null pointer otherwise. If the allocation function is declared with an empty exception-specification, throw(), it returns null to indicate failure to allocate storage and a non-null pointer otherwise. -- end note ] 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. 14 [ 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 ] 15 A new-expression that creates an object of type T initializes that object as follows: -- If the new-initializer is omitted: -- If T is a (possibly cv-qualified) non-POD class type (or array thereof), the object is default-initialized (8.5). If T is a const-qualified type, the underlying class type shall have a user-declared default constructor. -- Otherwise, the object created has indeterminate value. If T is a const-qualified type, or a (possibly cv- qualified) POD class type (or array thereof) containing (directly or indirectly) a member of const-qualified type, the program is ill-formed; -- If the new-initializer is of the form (), the item is value-initialized (8.5); -- If the new-initializer is of the form (expression-list) and T is a class type, the appropriate constructor is called, using expression-list as the arguments (8.5); -- If the new-initializer is of the form (expression-list) and T is an arithmetic, enumeration, pointer, or pointer-to- member type and expression-list comprises exactly one expression, then the object is initialized to the (possibly converted) value of the expression (8.5); -- Otherwise the new-expression is ill-formed. Draft 91 Expressions 5.3 Unary expressions 16 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 (12.5), and the constructor (12.1). If the new expression creates an array of objects of class type, access and ambiguity control are done for the destructor (12.4). 17 If any part of the object initialization described above75) 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 ] 18 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. 19 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 (8.3.5), all parameter types except the first are identical. Any non-placement deallocation function matches a non-placement allocation function. 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 the two-parameter form of a usual deallocation function (3.7.3.2) 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. [ 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 ] 20 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. 21 Whether the allocation function is called before evaluating the constructor arguments or after evaluating the constructor arguments but before entering the constructor is unspecified. It is also unspecified whether the arguments to a constructor are evaluated if the allocation function returns the null pointer or exits using an exception. 75) This may include evaluating a new-initializer and/or calling a constructor. Draft 5.3 Unary expressions Expressions 92 5.3.5 Delete [expr.delete] 1 The delete-expression operator destroys a most derived object (1.8) or array created by a new-expression. delete-expression: ::opt delete cast-expression ::opt delete [ ] cast-expression The first alternative is for non-array objects, and the second is for arrays. The operand shall have a pointer type, or a class type having a single conversion function (12.3.2) to a pointer type. The result has type void. 2 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 either alternative, if the value of the operand of delete is the null pointer the operation has no effect. In the first alternative (delete object ), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a subobject (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined. In the second alternative (delete array ), the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression.76) 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 (5.2.11) of the pointer expression before it is used as the operand of the delete-expression. -- end note ] 3 In the first alternative (delete object ), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand's dynamic type 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.77) 4 The cast-expression in a delete-expression shall be evaluated exactly once. If the delete-expression calls the implemen- tation deallocation function (3.7.3.2), and if the operand of the delete expression is not the null pointer constant, the deallocation function will deallocate the storage referenced by the pointer thus rendering the pointer invalid. [ Note: the value of a pointer that refers to deallocated storage is indeterminate. -- end note ] 5 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. 6 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 12.6.2). 7 The delete-expression will call a deallocation function (3.7.3.2). [ 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 ] 8 [ Note: An implementation provides default definitions of the global deallocation functions operator delete() for non-arrays (18.4.1.1) and operator delete[]() for arrays (18.4.1.2). A C++ program can provide alternative defini- tions of these functions (17.4.3.4), and/or class-specific versions (12.5). -- end note ] When the keyword delete in a delete-expression is preceded by the unary :: operator, the global deallocation function is used to deallocate the storage. 76) For non-zero-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. 77) This implies that an object cannot be deleted using a pointer of type void* because there are no objects of type void. Draft 93 Expressions 5.4 Explicit type conversion (cast notation) 9 Access and ambiguity control are done for both the deallocation function and the destructor (12.4, 12.5). 5.4 Explicit type conversion (cast notation) [expr.cast] 1 The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is a reference type, otherwise the result is an rvalue. [ Note: if T is a non-class type that is cv-qualified, the cv-qualifiers are ignored when determining the type of the resulting rvalue; see 3.10. -- end note ] 2 An explicit type conversion can be expressed using functional notation (5.2.3), a type conversion operator (dynamic_- cast, static_cast, reinterpret_cast, const_cast ), or the cast notation. cast-expression: unary-expression ( type-id ) cast-expression 3 Types shall not be defined in casts. 4 Any type conversion not mentioned below and not explicitly defined by the user (12.3) is ill-formed. 5 The conversions performed by -- a const_cast (5.2.11), -- a static_cast (5.2.9), -- a static_cast followed by a const_cast, -- a reinterpret_cast (5.2.10), or -- a reinterpret_cast followed by a const_cast, 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 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, an lvalue 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 } Draft 5.5 Pointer-to-member operators Expressions 94 -- end example ] 6 The operand of a cast using the cast notation can be an rvalue of type "pointer to incomplete class type". The destination type of a cast using the cast notation can be "pointer to incomplete class type". In such cases, even if there is a inheritance relationship between the source and destination classes, whether the static_cast or reinterpret_cast interpretation is used is unspecified. 5.5 Pointer-to-member operators [expr.mptr.oper] 1 The pointer-to-member operators ->* and .* group left-to-right. pm-expression: cast-expression pm-expression .* cast-expression pm-expression ->* cast-expression 2 The binary operator .* binds its second operand, which shall be of type "pointer to member of T" (where T is a completely-defined class type) to its first operand, which shall be 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. 3 The binary operator ->* binds its second operand, which shall be of type "pointer to member of T" (where T is a completely-defined class type) to its first operand, which shall be of type "pointer to T" or "pointer to 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. 4 If the dynamic type of the object does not contain the member to which the pointer refers, the behavior is undefined. 5 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 5.2.5. [ 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 { mutable int i ; }; 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 ] 6 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 ] The result of a .* expression is an lvalue only if its first operand is an lvalue and its second operand is a pointer to data member. The result of an ->* expression is an lvalue only if its second operand is a pointer to data member. If the second operand is the null pointer to member value (4.11), the behavior is undefined. 5.6 Multiplicative operators [expr.mul] 1 The multiplicative operators *, /, and % group left-to-right. Draft 95 Expressions 5.7 Additive operators multiplicative-expression: pm-expression multiplicative-expression * pm-expression multiplicative-expression / pm-expression multiplicative-expression % pm-expression 2 The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. The usual arithmetic conversions are performed on the operands and determine the type of the result. 3 The binary * operator indicates multiplication. 4 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; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined78) . 5.7 Additive operators [expr.add] 1 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 enumeration type, or one operand shall be a pointer to a completely defined object type and the other shall have integral or enumeration type. 2 For subtraction, one of the following shall hold: -- both operands have arithmetic or 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 enumeration type. 3 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. 4 For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type. 5 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 pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i + n-th and 78) According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero. Draft 5.8 Shift operators Expressions 96 i - n-th elements of the array object, provided they exist. Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. 6 When two pointers to elements of the same array object are subtracted, the result is the difference of the subscripts of the two array elements. 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 header (18.1). As with any other arithmetic overflow, if the result does not fit in the space provided, the behavior is undefined. In other words, if the expressions P and Q point to, respectively, the i-th and j-th elements of an array object, the expression (P)-(Q) has the value i - j provided the value fits in an object of type std::ptrdiff_t. Moreover, if the expression P points either to an element of an array object or one past the last element of an array object, and the expression Q points to the last element of the same array object, the expression ((Q)+1)-(P) has the same value as ((Q)-(P))+1 and as -((P)-((Q)+1)), and has the value zero if the expression P points one past the last element of the array object, even though the expression (Q)+1 does not point to an element of the array object. Unless both pointers point to elements of the same array object, or one past the last element of the array object, the behavior is undefined.79) 7 If the value 0 is added to or subtracted from a pointer value, the result compares equal to the original pointer value. If two pointers point to the same object or both point one past the end of the same array or both are null, and the two pointers are subtracted, the result compares equal to the value 0 converted to the type std::ptrdiff_t. 5.8 Shift operators [expr.shift] 1 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 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. 2 The value of E1 << E2 is E1 (interpreted as a bit pattern) left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 multiplied by the quantity 2 raised to the power E2, reduced modulo ULONG_MAX+1 if E1 has type unsigned long, UINT_MAX+1 otherwise. [ Note: the constants ULONG_MAX and UINT_MAX are defined in the header . -- end note ] 3 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 nonnegative value, the value of the result is the integral part of the quotient of E1 divided by the quantity 2 raised to the 79) Another way to approach pointer arithmetic is first to convert the pointer(s) to character pointer(s): In this scheme the integral value of the expression added to or subtracted from the converted pointer is first multiplied by the size of the object originally pointed to, and the resulting pointer is converted back to the original type. For pointer subtraction, the result of the difference between the character pointers is similarly divided by the size of the object originally pointed to. When viewed in this way, an implementation need only provide one extra byte (which might overlap another object in the program) just after the end of the object in order to satisfy the "one past the last element" requirements. Draft 97 Expressions 5.9 Relational operators power E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined. 5.9 Relational operators [expr.rel] 1 The relational operators group left-to-right. [ Example: a shift-expression relational-expression <= shift-expression relational-expression >= shift-expression The operands shall have arithmetic, enumeration or pointer type. 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. 2 The usual arithmetic conversions are performed on operands of arithmetic or enumeration type. Pointer conversions (4.10) and qualification conversions (4.4) are performed on pointer operands (or on a pointer operand and a null pointer constant) to bring them to their composite pointer type. If one operand is a null pointer constant, the composite pointer type is the type of the other operand. Otherwise, if one of the operands has type "pointer to cv1 void," then the other has type "pointer to cv2 T" and the composite pointer type is "pointer to cv12 void," where cv12 is the union of cv1 and cv2. Otherwise, the composite pointer type is a pointer type similar (4.4) to the type of one of the operands, with a cv-qualification signature (4.4) that is the union of the cv-qualification signatures of the operand types. [ Note: this implies that any pointer can be compared to a null pointer constant and that any object pointer can be compared to a pointer to (possibly cv-qualified) void. -- end note ] [ Example: void * p ; const int * q ; int ** pi ; const int * const * pci ; void ct () { p <= q ; / / Both converted to const void* before comparison pi <= pci ; / / Both converted to const int *const * before comparison } -- end example ] Pointers to objects or functions of the same type (after pointer conversions) can be compared, with a result defined as follows: -- If two pointers p and q of the same type point to the same object or function, or both point one past the end of the same array, or are both null, then p<=q and p>=q both yield true and pq both yield false. -- If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of pq, p<=q, and p>=q are unspecified. -- If two pointers point to non-static data members of the same object, or to subobjects or array elements of such members, recursively, the pointer to the later declared member compares greater provided the two members are not separated by an access-specifier label (11.1) and provided their class is not a union. Draft 5.10 Equality operators Expressions 98 -- If two pointers point to non-static data members of the same object separated by an access-specifier label (11.1) the result is unspecified. -- If two pointers point to data members of the same union object, they compare equal (after conversion to void*, if necessary). If two pointers point to elements of the same array or one beyond the end of the array, the pointer to the object with the higher subscript compares higher. -- Other pointer comparisons are unspecified. 5.10 Equality operators [expr.eq] equality-expression: relational-expression equality-expression == relational-expression equality-expression != relational-expression 1 The == (equal to) and the != (not equal to) operators have the same semantic restrictions, conversions, and result type as the relational operators except for their lower precedence and truth-value result. [ Note: a>= <<= &= ^= |= 2 In simple assignment (=), the value of the expression replaces that of the object referred to by the left operand. 3 If the left operand is not of class type, the expression is implicitly converted (clause 4) to the cv-unqualified type of the left operand. 4 If the left operand is of class type, the class shall be complete. Assignment to objects of a class is defined by the copy assignment operator (12.8, 13.5.3). 5 [ Note: For class objects, assignment is not in general the same as initialization (8.5, 12.1, 12.6, 12.8). -- end note ] 6 When the left operand of an assignment operator denotes a reference to T, the operation assigns to the object of type T denoted by the reference. 7 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. Draft 5.18 Comma operator Expressions 102 8 If the value being stored in an object is accessed from 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. 5.18 Comma operator [expr.comma] 1 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 and the value of the left expression is discarded. The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are not applied to the left expression. All side effects (1.9) of the left expression, except for the destruction of temporaries (12.2), are performed before the evaluation of the right expression. The type and value of the result are the type and value of the right operand; the result is an lvalue if its right operand is an lvalue, and is a bit-field if its right operand is an lvalue and a bit-field. 2 In contexts where comma is given a special meaning, [ Example: in lists of arguments to functions (5.2.2) and lists of initializers (8.5) -- end example ] the comma operator as described in clause 5 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 ] 5.19 Constant expressions [expr.const] 1 In several places, C++ requires expressions that evaluate to an integral or enumeration constant: as array bounds (8.3.4, 5.3.4), as case expressions (6.4.2), as bit-field lengths (9.6), as enumerator initializers (7.2), as static member initializers (9.4.2), and as integral or enumeration non-type template arguments (14.3). constant-expression: conditional-expression An integral constant-expression can involve only literals of arithmetic types (2.13, 3.9.1), enumerators, non-volatile const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), non-type template parameters of integral or enumeration types, and sizeof expressions. Floating literals (2.13.3) can appear only if they are cast to integral or enumeration types. Only type conversions to integral or enumeration types can be used. In particular, except in sizeof expressions, functions, class objects, pointers, or references shall not be used, and assignment, increment, decrement, function-call, or comma operators shall not be used. 2 Other expressions are considered constant-expressions only for the purpose of non-local static object initialization (3.6.2). Such constant expressions shall evaluate to one of the following: -- a null pointer value (4.10), -- a null member pointer value (4.11), -- an arithmetic constant expression, -- an address constant expression, -- a reference constant expression, Draft 103 Expressions 5.19 Constant expressions -- an address constant expression for a complete object type, plus or minus an integral constant expression, or -- a pointer to member constant expression. 3 An arithmetic constant expression shall satisfy the requirements for an integral constant expression, except that -- floating literals need not be cast to integral or enumeration type, and -- conversions to floating point types are permitted. 4 An address constant expression is a pointer to an lvalue designating an object of static storage duration, a string literal (2.13.4), or a function. The pointer shall be created explicitly, using the unary & operator, or implicitly using a non- type template parameter of pointer type, or using an expression of array (4.2) or function (4.3) type. The subscripting operator [] and the class member access . and -> operators, the & and * unary operators, and pointer casts (except dynamic_casts, 5.2.7) can be used in the creation of an address constant expression, but the value of an object shall not be accessed by the use of these operators. If the subscripting operator is used, one of its operands shall be an integral constant expression. An expression that designates the address of a subobject of a non-POD class object (clause 9) is not an address constant expression (12.7). Function calls shall not be used in an address constant expression, even if the function is inline and has a reference return type. 5 A reference constant expression is an lvalue designating an object of static storage duration, a non-type template param- eter of reference type, or a function. The subscripting operator [], the class member access . and -> operators, the & and * unary operators, and reference casts (except those invoking user-defined conversion functions (12.3.2) and except dynamic_casts (5.2.7)) can be used in the creation of a reference constant expression, but the value of an object shall not be accessed by the use of these operators. If the subscripting operator is used, one of its operands shall be an integral constant expression. An lvalue expression that designates a member or base class of a non-POD class object (clause 9) is not a reference constant expression (12.7). Function calls shall not be used in a reference constant expression, even if the function is inline and has a reference return type. 6 A pointer to member constant expression shall be created using the unary & operator applied to a qualified-id operand (5.3.1), optionally preceded by a pointer to member cast (5.2.9). Draft 5.19 Constant expressions Expressions 104 Draft Chapter 6 Statements [stmt.stmt] 1 Except as indicated, statements are executed in sequence. statement: labeled-statement expression-statement compound-statement selection-statement iteration-statement jump-statement declaration-statement try-block 6.1 Labeled statement [stmt.label] 1 A statement can be labeled. labeled-statement: identifier : statement case constant-expression : statement default : statement 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 definition. Labels have their own name space and do not interfere with other identifiers. 2 Case labels and default labels shall occur only in switch statements. 6.2 Expression statement [stmt.expr] 1 Expression statements have the form expression-statement: expressionopt ; The expression is evaluated and its value is discarded. The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function- to-pointer (4.3) standard conversions are not applied to the expression. 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 (6.5.1). -- end note ] 6.3 Compound statement or block [stmt.block] 1 So that several statements can be used where one is expected, the compound statement (also, and equivalently, called 6.4 Selection statements Statements 106 "block") is provided. compound-statement: { statement-seqopt } statement-seq: statement statement-seq statement A compound statement defines a local scope (3.3). [ Note: a declaration is a statement (6.7). -- end note ] 6.4 Selection statements [stmt.select] 1 Selection statements choose one of several flows of control. selection-statement: if ( condition ) statement if ( condition ) statement else statement switch ( condition ) statement condition: expression type-specifier-seq declarator = assignment-expression In clause 6, 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 local scope (3.3). 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 ] 2 The rules for conditions apply both to selection-statements and to the for and while statements (6.5). The declarator shall not specify a function or an array. The type-specifier-seq shall not contain typedef and shall not declare a new class or enumeration. 3 A name introduced by a declaration in a condition (either introduced by the type-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 re-declared in the outermost block of a substatement controlled by the condition, the declaration that re-declares 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 } Draft 107 Statements 6.4 Selection statements -- end example ] 4 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 implicitly converted to type bool. 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, implicitly 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. 5 If a condition can be syntactically resolved as either an expression or the declaration of a local name, it is interpreted as a declaration. 6.4.1 The if statement [stmt.if] 1 If the condition (6.4) 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. 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.80) 6.4.2 The switch statement [stmt.switch] 1 The switch statement causes control to be transferred to one of several statements depending on the value of a condition. 2 The condition shall be of integral type, enumeration type, or of a class type for which a single conversion function to integral or enumeration type exists (12.3). If the condition is of class type, the condition is converted by calling that conversion function, and the result of the conversion is used in place of the original condition for the remainder of this section. Integral promotions are performed. 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 an integral constant-expression. The integral constant-expression (5.19) is im- plicitly converted to the promoted type of the switch condition. No two of the case constants in the same switch shall have the same value after conversion to the promoted type of the switch condition. 3 There shall be at most one label of the form default : within a switch statement. 4 Switch statements can be nested; a case or default label is associated with the smallest switch enclosing it. 5 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. 6 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, 6.6.1. [ Note: usually, the substatement that is the subject of a switch is compound and 80) In other words, the else is associated with the nearest un-elsed if. Draft 6.5 Iteration statements Statements 108 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 ] 6.5 Iteration statements [stmt.iter] 1 Iteration statements specify looping. iteration-statement: while ( condition ) statement do statement while ( expression ) ; for ( for-init-statement conditionopt ; expressionopt ) statement for-init-statement: expression-statement simple-declaration [ Note: a for-init-statement ends with a semicolon. -- end note ] 2 The substatement in an iteration-statement implicitly defines a local scope (3.3) 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 ; } 3 Thus after the while statement, i is no longer in scope. -- end example ] 4 [ Note: The requirements on conditions in iteration statements are described in 6.4. -- end note ] 6.5.1 The while statement [stmt.while] 1 In the while statement the substatement is executed repeatedly until the value of the condition (6.4) becomes false. The test takes place before each execution of the substatement. 2 When the condition of a while statement is a declaration, the scope of the variable that is declared extends from its point of declaration (3.3.1) 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 ; Draft 109 Statements 6.5 Iteration statements } } / / end of condition scope The object 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 ] 6.5.2 The do statement [stmt.do] 1 The expression is implicitly converted to bool; if that is not possible, the program is ill-formed. 2 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. 6.5.3 The for statement [stmt.for] 1 The for statement for ( for-init-statement conditionopt ; expressionopt ) statement is equivalent to { for-init-statement while ( condition ) { statement expression ; } } except that names declared in the for-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 (6.4) specifies a test, made before each iteration, such that the loop is exited when the condition becomes false; the expression often specifies incrementing that is done after each iteration. -- end note ] 2 Either or both of the condition and the expression can be omitted. A missing condition makes the implied while clause equivalent to while(true). Draft 6.6 Jump statements Statements 110 3 If the for-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 ] 6.6 Jump statements [stmt.jump] 1 Jump statements unconditionally transfer control. jump-statement: break ; continue ; return expressionopt ; goto identifier ; 2 On exit from a scope (however accomplished), destructors (12.4) are called for all constructed objects with automatic storage duration (3.7.2) (named objects or temporaries) that are declared in that scope, in the reverse order of their declaration. Transfer out of a loop, out of a block, or back past an initialized variable with automatic storage duration involves the destruction of variables with automatic storage duration that are in scope at the point transferred from but not at the point transferred to. (See 6.7 for transfers into blocks). [ Note: However, the program can be terminated (by calling std::exit() or std::abort() (18.3), for example) without destroying class objects with automatic storage duration. -- end note ] 6.6.1 The break statement [stmt.break] 1 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. 6.6.2 The continue statement [stmt.cont] 1 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 ) { do { for (;;) { { { { / / ... / / ... / / ... } } } contin : ; contin : ; contin : ; } } while ( foo ); } Draft 111 Statements 6.7 Declaration statement a continue not contained in an enclosed iteration statement is equivalent to goto contin. 6.6.3 The return statement [stmt.return] 1 A function returns to its caller by the return statement. 2 A return statement without an expression can be used only in functions that do not return a value, that is, a function with the return type void, a constructor (12.1), or a destructor (12.4). A return statement with an expression of non-void type can be used only in functions returning a value; the value of the expression is returned to the caller of the function. The expression is implicitly converted to the return type of the function in which it appears. A return statement can involve the construction and copy of a temporary object (12.2). Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function. 3 A return statement with an expression of type "cv void" can be used only in functions with a return type of cv void; the expression is evaluated just before the function returns to its caller. 6.6.4 The goto statement [stmt.goto] 1 The goto statement unconditionally transfers control to the statement labeled by the identifier. The identifier shall be a label (6.1) located in the current function. 6.7 Declaration statement [stmt.dcl] 1 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. 2 Variables with automatic storage duration (3.7.2) are initialized each time their declaration-statement is executed. Vari- ables with automatic storage duration declared in the block are destroyed on exit from the block (6.6). 3 It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps81) from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5). [ 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 } 81) The transfer from the condition of a switch statement to a case label is considered a jump in this respect. Draft 6.8 Ambiguity resolution Statements 112 -- end example ] 4 The zero-initialization (8.5) of all local objects with static storage duration (3.7.1) is performed before any other initial- ization takes place. A local object of POD type (3.9) with static storage duration initialized with constant-expressions is initialized before its block is first entered. An implementation is permitted to perform early initialization of other local objects with static storage duration under the same conditions that an implementation is permitted to statically initialize an object with static storage duration in namespace scope (3.6.2). Otherwise such an object is initialized the first time control passes through its declaration; such an object 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 re-enters the declaration (recursively) while the object 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 ] 5 The destructor for a local object with static storage duration will be executed if and only if the variable was constructed. [ Note: 3.6.3 describes the order in which local objects with static storage duration are destroyed. -- end note ] 6.8 Ambiguity resolution [stmt.ambig] 1 There is an ambiguity in the grammar involving expression-statements and declarations: An expression-statement with a function-style explicit type conversion (5.2.3) 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: To disambiguate, the whole statement might have to be examined to determine if it is an expression-statement or a declaration. This disambiguates many examples. [ Example: assuming T is a simple-type-specifier (7.1.5), 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 ] 2 The remaining cases are declarations. [ Example: class T { / / ... public : T (); T ( int ); T ( int , int ); Draft 113 Statements 6.8 Ambiguity resolution }; 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 ] 3 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 disam- biguated 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 (*(* b )( T2 ( c )))( int ( d )); / / a variable of type T1 / / but this will not allow / / the last part of the / / declaration to parse / / properly since it depends / / on T2 being a type-name } -- end example ] Draft 6.8 Ambiguity resolution Statements 114 Draft Chapter 7 Declarations [dcl.dcl] 1 Declarations specify how names are to be interpreted. Declarations have the form declaration-seq: declaration declaration-seq declaration declaration: block-declaration function-definition template-declaration explicit-instantiation explicit-specialization linkage-specification namespace-definition block-declaration: simple-declaration asm-definition namespace-alias-definition using-declaration using-directive static_assert-declaration simple-declaration: decl-specifier-seqopt init-declarator-listopt ; static_assert-declaration: static_assert ( constant-expression , string-literal ) ; [ Note: asm-definitions are described in 7.4, and linkage-specifications are described in 7.5. Function-definitions are de- scribed in 8.4 and template-declarations are described in clause 14. Namespace-definitions are described in 7.3.1, using- declarations are described in 7.3.3 and using-directives are described in 7.3.4. -- end note ] The simple-declaration decl-specifier-seqopt init-declarator-listopt ; is divided into two parts: decl-specifiers, the components of a decl-specifier-seq, are described in 7.1 and declarators, the components of an init-declarator-list, are described in clause 8. 2 A declaration occurs in a scope (3.3); the scope rules are summarized in 3.4. 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 7 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. 7.1 Specifiers Declarations 116 3 In a simple-declaration, the optional init-declarator-list can be omitted only when declaring a class (clause 9) or enu- meration (7.2), that is, when the decl-specifier-seq contains either a class-specifier, an elaborated-type-specifier with a class-key (9.1), 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, and except for the declaration of an unnamed bit-field (9.6), 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 ] 4 In a static_assert-declaration the constant-expression shall be an integral constant expression (5.19). If the value of the expression when converted to bool is true, the declaration has no effect. Otherwise, the program is ill-formed, and the resulting diagnostic message (1.4) shall include the text of the string-literal, except that characters not in the basic source character set (2.2) are not required to appear in the diagnostic message. [ Example: static_assert ( sizeof ( long ) >= 8 , " 64 - bit code generation not supported . " ); -- end example ] 5 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 type-specifiers (7.1.5) in the decl-specifier- seq and the recursive declarator structure of the init-declarator describe a type (8.3), which is then associated with the name being declared by the init-declarator. 6 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 (7.1.3). 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 (8.3.5) and an object declaration otherwise. 7 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 (3.1). A definition causes the appropriate amount of storage to be reserved and any appropriate initialization (8.5) to be done. 8 Only in function declarations for constructors, destructors, and type conversions can the decl-specifier-seq be omitted.82) 7.1 Specifiers [dcl.spec] 1 The specifiers that can be used in a declaration are decl-specifier: storage-class-specifier type-specifier function-specifier friend typedef 82) The "implicit int" rule of C is no longer supported. Draft 117 Declarations 7.1 Specifiers decl-specifier-seq: decl-specifier-seqopt decl-specifier 2 The longest sequence of decl-specifiers that could possibly be a type name is taken as the decl-specifier-seq of a decla- ration. 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 ] 3 [ 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 ] 7.1.1 Storage class specifiers [dcl.stc] 1 The storage class specifiers are storage-class-specifier: auto register static extern mutable At most one storage-class-specifier shall appear in a given decl-specifier-seq. 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 of the declaration shall not be empty (except for global anonymous unions, which shall be declared static (9.5)). 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 shall not be specified in an explicit specialization (14.7.3) or an explicit instantiation (14.7.2) directive. 2 The auto or register specifiers can be applied only to names of objects declared in a block (6.3) or to function parameters (8.4). They specify that the named object has automatic storage duration (3.7.2). An object declared without a storage-class-specifier at block scope or declared as a function parameter has automatic storage duration by default. [ Note: hence, the auto specifier is always redundant and not often used; one use of auto is to distinguish a declaration- statement from an expression-statement explicitly rather than relying on the disambiguation rules (6.8), which may aid readers. -- end note ] 3 A register specifier has the same semantics as an auto specifier together with a hint to the implementation that the object so declared will be heavily used. [ Note: the hint can be ignored and in most implementations it will be ignored if the address of the object is taken. -- end note ] Draft 7.1 Specifiers Declarations 118 4 The static specifier can be applied only to names of objects and functions and to anonymous unions (9.5). There can be no static function declarations within a block, nor any static function parameters. A static specifier used in the declaration of an object declares the object to have static storage duration (3.7.1). A static specifier can be used in declarations of class members; 9.4 describes its effect. For the linkage of a name declared with a static specifier, see 3.5. 5 The extern specifier can be applied only to the names of objects 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 3.5. 6 A name declared in a namespace scope without a storage-class-specifier has external linkage unless it has internal linkage because of a previous declaration and provided it is not declared const. Objects declared const and not explicitly declared extern have internal linkage. 7 The linkages implied by successive declarations for a given entity shall agree. That is, within a given scope, each declaration declaring the same object 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 Draft 119 Declarations 7.1 Specifiers -- end example ] 8 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 can be applied only to names of class data members (9.2) and cannot be applied to names declared const or static, and cannot be applied to reference members. [ Example: class X { mutable const int * p ; / / OK mutable int * const q ; / / ill-formed }; -- end example ] 9 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 (7.1.5.1). 7.1.2 Function specifiers [dcl.fct.spec] 1 Function-specifiers can be used only in function declarations. function-specifier: inline virtual explicit 2 A function declaration (8.3.5, 9.3, 11.4) 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 defined by 7.1.2 shall still be respected. 3 A function defined within a class definition is an inline function. The inline specifier shall not appear on a block scope function declaration.83) If the inline specifier is used in a friend declaration, that declaration shall be a definition or the function shall have previously been declared inline. 4 An inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case (3.2). [ Note: a call to the inline function may be encountered before its definition appears in the translation unit. -- end note ] If a function with external linkage is declared inline in one translation unit, it shall be declared inline 83) The inline keyword has no effect on the linkage of a function. Draft 7.1 Specifiers Declarations 120 in all translation units in which it appears; no diagnostic is required. An inline function with external linkage shall have the same address in all translation units. A static local variable in an extern inline function always refers to the same object. A string literal in an extern inline function is the same object in different translation units. 5 The virtual specifier shall only be used in declarations of non-static class member functions that appear within a member-specification of a class definition; see 10.3. 6 The explicit specifier shall be used only in declarations of constructors within a class definition; see 12.3.1. 7.1.3 The typedef specifier [dcl.typedef] 1 Declarations containing the decl-specifier typedef declare identifiers that can be used later for naming fundamental (3.9.1) or compound (3.9.2) types. The typedef specifier shall not be used in a function-definition (8.4), and it shall not be combined in a decl-specifier-seq with any other kind of specifier except a type-specifier. 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 8. A typedef-name is thus a synonym for another type. A typedef-name does not introduce a new type the way a class declaration (9.1) 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 that of metricp is "pointer to int." -- end example ] 2 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 ] 3 In a give 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 ] Draft 121 Declarations 7.1 Specifiers 4 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 ] 5 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 ] 6 [ Note: A typedef-name that names a class type, or a cv-qualified version thereof, is also a class-name (9.1). If a typedef- name is used to identify the subject of an elaborated-type-specifier (7.1.5.3), a class definition (clause 9), a constructor declaration (12.1), or a destructor declaration (12.4), 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 ] 7 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 (3.5). [ Example: typedef struct { } * ps , S ; / / S is the class name for linkage purposes -- end example ] 8 [ Note: if the typedef-name is used where a class-name (or enum-name) is required, the program is ill-formed. For example, typedef struct { S (); / / error: requires a return type because S is / / an ordinary member function, not a constructor } S; -- end note ] 9 If a typedef TD names a type "reference to cv1 S", an attempt to create the type "reference to cv2 TD" creates the type "reference to cv12 S", where cv12 is the union of the cv-qualifiers cv1 and cv2. Redundant qualifiers are ignored. [ Example: Draft 7.1 Specifiers Declarations 122 int i ; typedef int & RI ; RI & r1 = i ; / / r1 has the type int& const RI & r2 = i ; / / r2 has the type const int& -- end example ] 7.1.4 The friend specifier [dcl.friend] The friend specifier is used to specify access to class members; see 11.4. 7.1.5 Type specifiers [dcl.type] 1 The type-specifiers are type-specifier: simple-type-specifier class-specifier enum-specifier elaborated-type-specifier typename-specifier cv-qualifier 2 As a general rule, at most one type-specifier is allowed in the complete decl-specifier-seq of a declaration. The only exceptions to this rule are the following: -- const or volatile can be combined with any other type-specifier. However, redundant cv-qualifiers are prohib- ited except when introduced through the use of typedefs (7.1.3) or template type arguments (14.3), in which case the redundant cv-qualifiers are ignored. -- 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. 3 At least one type-specifier that is not a cv-qualifier is required in a declaration unless it declares a constructor, destructor or conversion function.84) 4 [ Note: class-specifiers and enum-specifiers are discussed in clause 9 and 7.2, respectively. The remaining type-specifiers are discussed in the rest of this section. -- end note ] 7.1.5.1 The cv-qualifiers [dcl.type.cv] 1 There are two cv-qualifiers, const and volatile. If a cv-qualifier appears in a decl-specifier-seq, the init-declarator- list of the declaration shall not be empty. [ Note: 3.9.3 describes how cv-qualifiers affect object and function types. -- end note ] 2 An object declared in namespace scope with a const-qualified type has internal linkage unless it is explicitly declared extern or unless it was previously declared to have external linkage. A variable of non-volatile const-qualified integral 84) 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. Draft 123 Declarations 7.1 Specifiers or enumeration type initialized by an integral constant expression can be used in integral constant expressions (5.19). [ Note: as described in 8.5, the definition of an object or subobject of const-qualified type must specify an initializer or be subject to default-initialization. -- end note ] 3 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 (5.2.11). -- end note ] 4 Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) 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 5 For another example class X { public : mutable int i ; int j ; }; class Y { public : 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 ] Draft 7.1 Specifiers Declarations 124 6 If an attempt is made to refer to an object defined with a volatile-qualified type through the use of an lvalue with a non-volatile-qualified type, the program behaviour is undefined. 7 [ 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. See 1.9 for detailed semantics. In general, the semantics of volatile are intended to be the same in C++ as they are in C. -- end note ] 7.1.5.2 Simple type specifiers [dcl.type.simple] 1 The simple type specifiers are simple-type-specifier: ::opt nested-name-specifieropt type-name ::opt nested-name-specifier template template-id char wchar_t bool short int long signed unsigned float double void type-name: class-name enum-name typedef-name 2 The simple-type-specifiers specify either a previously-declared user-defined type or one of the fundamental types (3.9.1). Table 7 summarizes the valid combinations of simple-type-specifiers and the types they specify. Table 7: simple-type-specifiers and the types they specify Specifier(s) Type type-name the type named char "char" unsigned char "unsigned char" signed char "signed char" 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" Draft 125 Declarations 7.1 Specifiers Specifier(s) Type type-name the type named signed long int "long int" signed 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" 3 When multiple simple-type-specifiers are allowed, they can be freely intermixed with other decl-specifiers in any order. It is implementation-defined whether bit-fields and objects of char type are represented as signed or unsigned quantities. The signed specifier forces char objects and bit-fields to be signed; it is redundant with other integral types. 7.1.5.3 Elaborated type specifiers [dcl.type.elab] elaborated-type-specifier: class-key ::opt nested-name-specifieropt identifier class-key ::opt nested-name-specifieropt templateopt template-id enum ::opt nested-name-specifieropt identifier 1 If an elaborated-type-specifier is the sole constituent of a declaration, the declaration is ill-formed unless it is an explicit specialization (14.7.3), an explicit instantiation (14.7.2) or it has one of the following forms: class-key identifier ; friend class-key ::opt identifier ; friend class-key ::opt template-id ; friend class-key ::opt nested-name-specifier identifier ; friend class-key ::opt nested-name-specifier templateopt template-id ; 2 3.4.4 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, 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. -- end note ] 3 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 (7.2), the union class-key shall be Draft 7.2 Enumeration declarations Declarations 126 used to refer to a union (clause 9), and either the class or struct class-key shall be used to refer to a class (clause 9) declared using the class or struct class-key. 7.2 Enumeration declarations [dcl.enum] 1 An enumeration is a distinct type (3.9.1) with named constants. Its name becomes an enum-name, within its scope. enum-name: identifier enum-specifier: enum identifieropt { enumerator-listopt } enumerator-list: enumerator-definition enumerator-list , enumerator-definition enumerator-definition: enumerator enumerator = constant-expression enumerator: identifier 2 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. The constant-expression shall be of integral or enumeration type. 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 ] 3 The point of declaration for an enumerator is immediately after its enumerator-definition. [ Example: const int x = 12; { enum { x = x }; } 4 Here, the enumerator x is initialized with the value of the constant x, namely 12. -- end example ] 5 Each enumeration defines a type that is different from all other types. Following the closing brace of an enum-specifier, each enumerator has the type of its enumeration. Prior to the closing brace, the type of each enumerator is the type of its initializing value. If an initializer is specified for an enumerator, the initializing value has the same type as the expression. If no initializer is specified for the first enumerator, the type is an unspecified integral type. Otherwise the type is the same as the type of the initializing value 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. 6 The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enu- meration. 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 for an enumeration 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 Draft 127 Declarations 7.2 Enumeration declarations is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value of sizeof() applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of sizeof() applied to the underlying type. 7 For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the enumeration are the values of the underlying type in the range bmin to bmax , where bmin and bmax are, respectively, the smallest and largest values of the smallest bit-field that can store emin and emax .85) It is possible to define an enumeration that has values not defined by any of its enumerators. 8 Two enumeration types are layout-compatible if they have the same underlying type. 9 The value of an enumerator or an object of an enumeration type is converted to an integer by integral promotion (4.5). [ 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 -- end example ] 10 An expression of arithmetic or enumeration type can be converted to an enumeration type explicitly. The value is unchanged if it is in the range of enumeration values of the enumeration type; otherwise the resulting enumeration value is unspecified. 11 The enum-name and each enumerator declared by an enum-specifier is declared in the scope that immediately contains the enum-specifier. These names obey the scope rules defined for all names in (3.3) and (3.4). An enumerator declared in class scope can be referred to using the class member access operators (::, . (dot) and -> (arrow)), see 5.2.5. [ Example: class X { public : enum direction { left = 'l ' , right = 'r ' }; int f ( int i ) { return i == left ? 0 : i == right ? 1 : 2; } }; void g ( X * p ) { 85) On a two's-complement machine, b M-1 ; b max is the smallest value greater than or equal to max(|emin | - 1, |emax |) of the form 2 min is zero if emin is non-negative and -(bmax + 1) otherwise. Draft 7.3 Namespaces Declarations 128 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 ] 7.3 Namespaces [basic.namespace] 1 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. 2 The outermost declarative region of a translation unit is a namespace; see 3.3.5. 7.3.1 Namespace definition [namespace.def] 1 The grammar for a namespace-definition is namespace-name: original-namespace-name namespace-alias original-namespace-name: identifier namespace-definition: named-namespace-definition unnamed-namespace-definition named-namespace-definition: original-namespace-definition extension-namespace-definition original-namespace-definition: namespace identifier { namespace-body } extension-namespace-definition: namespace original-namespace-name { namespace-body } unnamed-namespace-definition: namespace { namespace-body } namespace-body: declaration-seqopt 2 The identifier in an original-namespace-definition shall not have been previously defined in the declarative region in which the original-namespace-definition appears. The identifier in an original-namespace-definition is the name of the namespace. Subsequently in that declarative region, it is treated as an original-namespace-name. 3 The original-namespace-name in an extension-namespace-definition shall have previously been defined in an original- namespace-definition in the same declarative region. 4 Every namespace-definition shall appear in the global scope or in a namespace scope (3.3.5). 5 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: Draft 129 Declarations 7.3 Namespaces namespace Outer { int i ; namespace Inner { void f () { i ++; } / / Outer::i int i ; void g () { i ++; } / / Inner::i } } -- end example ] 7.3.1.1 Unnamed namespaces [namespace.unnamed] 1 An unnamed-namespace-definition behaves as if it were replaced by namespace unique { /* empty body */ } using namespace unique ; namespace unique { namespace-body } where all occurrences of uniquein a translation unit are replaced by the same identifier and this identifier differs from all other identifiers in the entire program.86) [ 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 ] 2 The use of the static keyword is deprecated when declaring objects in a namespace scope (see annex D); the unnamed- namespace provides a superior alternative. 7.3.1.2 Namespace member definitions [namespace.memdef] 1 Members (including explicit specializations of templates (14.7.3)) of a namespace can be defined within that namespace. [ Example: 86) Although entities in an unnamed namespace might have external linkage, they are effectively qualified by a name unique to their translation unit and therefore can never be seen from any other translation unit. Draft 7.3 Namespaces Declarations 130 namespace X { void f () { / ... / } } -- end example ] 2 Members (including explicit specializations of templates (14.7.3)) of a named namespace can also be defined outside that namespace by explicit qualification (3.4.3.2) 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 ] 3 Every name first declared in a namespace is a member of that namespace. If a friend declaration in a non-local class first declares a class or function87) the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by simple name lookup until a matching declaration is provided in that namespace scope (either before or after the class definition granting friendship). If a friend function 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 (3.4.2). When looking for a prior declaration of a class or a function declared as a friend, and when the name of the friend class or function is neither a qualified name nor a template-id, scopes outside the innermost enclosing namespace scope are not considered. [ Example: / / Assume f and g have not yet been defined. 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 }; 87) this implies that the name of the class or function is unqualified. Draft 131 Declarations 7.3 Namespaces }; / / 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 ] 7.3.2 Namespace alias [namespace.alias] 1 A namespace-alias-definition declares an alternate name for a namespace according to the following grammar: namespace-alias: identifier namespace-alias-definition: namespace identifier = qualified-namespace-specifier ; qualified-namespace-specifier: ::opt nested-name-specifieropt namespace-name 2 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 3.4.6. -- end note ] 3 In a declarative region, a namespace-alias-definition can be used to redefine a namespace-alias declared in that declar- ative region to refer only to the namespace to which it already refers. [ Example: the following declarations are well- formed: namespace C o m p a n y _ w i t h _ v e r y _ l o n g _n a me { / . . . / } namespace CWVLN = C o m p a n y _ w i t h _ v er y _l o ng _ na m e ; namespace CWVLN = C o m p a n y _ w i t h _ v er y _l o ng _ na m e ; / / OK: duplicate namespace CWVLN = CWVLN ; -- end example ] 4 A namespace-name or namespace-alias shall not be declared as the name of any other entity in the same declarative region. A namespace-name defined at global scope shall not be declared as the name of any other entity in any global Draft 7.3 Namespaces Declarations 132 scope of the program. No diagnostic is required for a violation of this rule by declarations in different translation units. 7.3.3 The using declaration [namespace.udecl] 1 A using-declaration introduces a name into the declarative region in which the using-declaration appears. That name is a synonym for the name of some entity declared elsewhere. using-declaration: using typenameopt ::opt nested-name-specifier unqualified-id ; using :: unqualified-id ; The member name specified in a using-declaration is declared in the declarative region in which the using-declaration appears. [ 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 ] 2 Every using-declaration is a declaration and a member-declaration and so can 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 ] 3 In a using-declaration used as a member-declaration, the nested-name-specifier shall name a base class of the class being defined. Such a using-declaration introduces the set of declarations found by member name lookup (10.2, 3.4.3.1). [ 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 ] 4 [ Note: since constructors and destructors do not have names, a using-declaration cannot refer to a constructor or 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 (14.5.2). -- end note ] If an assignment operator brought from a base class into a derived class scope has the signature of a copy-assignment Draft 133 Declarations 7.3 Namespaces operator for the derived class (12.8), the using-declaration does not by itself suppress the implicit declaration of the derived class copy-assignment operator; the copy-assignment operator from the base class is hidden or overridden by the implicitly-declared copy-assignment operator of the derived class, as described below. 5 A using-declaration shall not name a template-id. [ Example: class A { public : template < class T > void f ( T ); template < class T > struct X { }; }; class B : public A { public : using A :: f < double >; / / ill-formed using A :: X < int >; / / ill-formed }; -- end example ] 6 A using-declaration shall not name a namespace. 7 A using-declaration for 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 ] 8 Members declared by a using-declaration can be referred to by explicit qualification just like other member names (3.4.3.2). In a using-declaration, a prefix :: refers to the global namespace. [ Example: void f (); namespace A { void g (); } namespace X { using :: f ; / / global f using A :: g ; / / A's g } Draft 7.3 Namespaces Declarations 134 void h () { X :: f (); / / calls ::f X :: g (); / / calls A::g } -- end example ] 9 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 ; using A :: i ; / / OK: double declaration } void f () { using A :: i ; using A :: i ; / / error: double declaration } class B { public : int i ; }; class X : public B { using B :: i ; using B :: i ; / / error: double member declaration }; -- end example ] 10 The entity declared by a using-declaration shall be known in the context using it according to its definition at the point of the using-declaration. Definitions added to the namespace after the using-declaration are not considered when a use of the name is made. [ 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 ); } Draft 135 Declarations 7.3 Namespaces 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 ] 11 [ Note: partial specializations of class templates are found by looking up the primary class template and then consid- ering 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 (14.5.4). -- end note ] 12 Since a using-declaration is a declaration, the restrictions on declarations of the same name in the same declarative region (3.3) 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 } Draft 7.3 Namespaces Declarations 136 -- end example ] 13 If a function declaration in namespace scope or block scope has the same name and the same parameter types as a function introduced by a using-declaration, and the declarations do not declare the same function, the program is ill- formed. [ Note: two using-declarations may introduce functions with the same name and the same parameter types. 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 ] 14 When a using-declaration brings names from a base class into a derived class scope, 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 (8.3.5), and cv-qualification in a base class (rather than conflicting). [ 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 Draft 137 Declarations 7.3 Namespaces 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) } -- end example ] 15 [ Note: two using-declarations may introduce functions with the same name and the same parameter types. 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. -- end note ] 16 For the purpose of overload resolution, the functions which are introduced by a using-declaration into a derived class will be 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. 17 All instances of the name mentioned in a using-declaration shall be accessible. In particular, if a derived class uses a using-declaration 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-declaration shall be visible in the scope of at least one of the direct base classes of the class where the using-declaration is specified. [ Note: because a using-declaration designates a base class member (and not a member subobject or a member function of a base class subobject), a using-declaration cannot be used to resolve inherited member ambiguities. For 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 (); / / ambiguous: B::x or C::x } -- end note ] 18 The alias created by the using-declaration has the usual accessibility for a member-declaration. [ Example: class A { Draft 7.3 Namespaces Declarations 138 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 ] 19 [ Note: use of access-declarations (11.3) is deprecated; member using-declarations provide a better alternative. -- end note ] 20 If a using-declaration uses the keyword typename and specifies a dependent name (14.6.2), the name introduced by the using-declaration is treated as a typedef-name (7.1.3). 7.3.4 Using directive [namespace.udir] using-directive: using namespace ::opt nested-name-specifieropt namespace-name ; 1 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 3.4.6. -- end note ] 2 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 (3.4.1), 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 ] 3 A using-directive does not add any members to the declarative region in which it appears. [ Example: namespace A {