1. Trang chủ
  2. » Công Nghệ Thông Tin

ansi C reference phần 9 ppsx

191 264 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 191
Dung lượng 698,33 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

16– 2 Preprocessing directives DRAFT: 28 April 1995 16 Preprocessing directivescontrol-line: # include pp-tokens new-line # define identifier replacement-list new-line # define identifie

Trang 1

15– 4 Exception handling DRAFT: 28 April 1995 15.3 Handling an exception

void f() {

try { g();

}

catch (Overflow oo) { //

} catch (Matherr mm) { //

} }

Here, theOverflow handler will catch exceptions of typeOverflow and theMatherr handler willcatch exceptions of typeMatherrand all types publicly derived fromMatherrincludingUnderflowandZerodivide ]

3 The handlers for a try block are tried in order of appearance That makes it possible to write handlers that

can never be executed, for example by placing a handler for a derived class after a handler for a ing base class

correspond-4 A in a handler’s exception-declaration functions similarly to in a function parameter

declara-tion; it specifies a match for any exception If present, a handler shall be the last handler for its tryblock

5 If no match is found among the handlers for a try block, the search for a matching handler continues in a

dynamically surrounding try block

6 An exception is considered handled upon entry to a handler [Note: the stack will have been unwound at

that point ]

7 If no matching handler is found in a program, the functionterminate()(15.5.1) is called Whether or

not the stack is unwound before callingterminate()is implementation-defined

8 Referring to any non-static member or base class of the object in the handler of a function-try-block of a

constructor or destructor of the object results in undefined behavior

9 The fully constructed base classes and members of an object shall be destroyed before entering the handler

of a function-try-block of a constructor or destructor for that object.

10 The scope and lifetime of the parameters of a function or constructor extend into the handlers of a

function-try-block.

11 If the handlers of a function-try-block contain a jump into the body of a constructor or destructor, the

pro-gram is ill-formed

12 If a return statement appears in a handler of function-try-block of a constructor, the program is ill-formed.

13 The exception being handled shall be rethrown if control reaches the end of a handler of the

function-try-block of a constructor or destructor Otherwise, the function shall return when control reaches the end of a

handler for the function-try-block (6.6.3).

14

[except.spec] 15.4 Exception specifications

1 A function declaration lists exceptions that its function might directly or indirectly throw by using an

exception-specification as a suffix of its declarator.

exception-specification:

throw ( type-id-list )

Trang 2

15.4 Exception specifications DRAFT: 28 April 1995 Exception handling 15– 5

type-id-list:

type-id type-id-list , type-id

An exception-specification shall appear only on a function declarator in a declaration or definition An

exception-specification shall not appear in a typedef declaration [Example:

void f() throw(int); // OK void (*fp) throw (int); // OK void g(void pfa() throw(int)); // OK typedef int (*pf)() throw(int); // ill-formed

—end example]

2 If any declaration of a function has an exception-specification, all declarations, including the definition, of

that function shall have an exception-specification with the same set of type-ids If a virtual function has an

exception-specification, all declarations, including the definition, of any function that overrides that virtual

function in any derived class shall have an exception-specification at least as restrictive as that in the base class [Example:

struct B { virtual void f() throw (int, double);

pf1 = pf2; // ok: pf1 is less restrictive pf2 = pf1; // error: pf2 is more restrictive }

—end example]

3 In such an assignment or initialization, exception-specifications on return types and parameter types shall

match exactly

4 In other assignments or initializations, exception-specifications shall match exactly.

5 Calling a function through a declaration whose exception-specification is less restrictive that that of the

function’s definition is ill-formed No diagnostic is required

6 Types shall not be defined in exception-specifications.

7 An exception-specification can include the same class more than once and can include classes related by

inheritance, even though doing so is redundant An exception specification can include identifiers that resent incomplete types An exception can also include the name of the predefined classbad_exception

rep-8 If a classXis in the type-id-list of the exception-specification of a function, that function is said to allow

exception objects of class X or any class publicly and unambiguously derived from X Similarly, if apointer type Y* is in the type-id-list of the exception-specification of a function, the function allows

Trang 3

15– 6 Exception handling DRAFT: 28 April 1995 15.4 Exception specifications

exceptions of typeY*or that are pointers to any type publicly and unambiguously derived fromY*

9 Whenever an exception is thrown and the search for a handler (15.3) encounters the outermost block of a

function with an exception-specification, the functionunexpected()is called (15.5.2) if the

exception-specification does not allow the exception [Example:

int n = 0;

if (n) throw X(); // OK

if (n) throw Z(); // also OK throw W(); // will call unexpected() }

—end example]

10 The function unexpected() may throw an exception that will satisfy the exception-specification for

which it was invoked, and in this case the search for another handler will continue at the call of the function

with this exception-specification (see 15.5.2), or it may call terminate.

11 An implementation shall not reject an expression merely because when executed it throws or might throw

an exception that the containing function does not allow [Example:

extern void f() throw(X, Y);

void g() throw(X) {

}

the call tofis well-formed even though when called,fmight throw exceptionYthatgdoes not allow ]

12 A function with no specification allows all exceptions A function with an empty

exception-specification,throw(), does not allow any exceptions

13 An exception-specification is not considered part of a function’s type.

[except.special] 15.5 Special functions

1 The exception handling mechanism relies on two functions, terminate() and unexpected(), for

coping with errors related to the exception handling mechanism itself (18.6)

[except.terminate] 15.5.1 The terminate() function

1 In the following situations exception handling must be abandoned for less subtle error handling techniques:

— when a exception handling mechanism, after completing evaluation of the object to be thrown but

before completing the initialization of the exception-declaration in the matching handler, calls a user

function that exits via an uncaught exception,98)

— when the exception handling mechanism cannot find a handler for a thrown exception (see 15.3),

— when the implementation’s exception handling mechanism encounters some internal error, or

— when an attempt by the implementation to destroy an object during stack unwinding exits using anexception

98)For example, if the object being thrown is of a class with a copy constructor,terminate()will be called if that copy constructorexits with an exception during a

Trang 4

15.5.1 The terminate() function DRAFT: 28 April 1995 Exception handling 15– 7

2 In such cases,

void terminate();

is called (18.6.2)

[except.unexpected] 15.5.2 The unexpected() function

1 If a function with an specification throws an exception that is not listed in the

exception-specification, the function

void unexpected();

is called (18.6.1)

2 Theunexpected()function shall not return, but it can throw (or re-throw) an exception If it throws a

new exception which is allowed by the exception specification which previously was violated, then thesearch for another handler will continue at the call of the function whose exception specification was vio-

lated If it throws or rethrows an exception an exception that the exception-specification does not allow then the following happens: if the exception-specification does not include the name of the predefined

exceptionbad_exceptionthen the functionterminate()is called, otherwise the thrown exception

is replaced by an implementation-defined object of the typebad_exceptionand the search for another

handler will continue at the call of the function whose exception-specification was violated.

3 Thus, an exception-specification guarantees that only the listed exceptions will be thrown If the

exception-specification includes the name bad_exception then any exception not on the list may bereplaced bybad_exceptionwithin the functionunexpected()

[except.access] 15.6 Exceptions and access

1 If the exception-declaration in a catch clause has class type, and the function in which the catch clause

occurs does not have access to the destructor of that class, the program is ill-formed

2 An object can be thrown if it can be copied and destroyed in the context of the function in which the throw

occurs

Trang 6

1 A preprocessing directive consists of a sequence of preprocessing tokens that begins with a#preprocessing

token that is either the first character in the source file (optionally after white space containing no new-linecharacters) or that follows white space containing at least one new-line character, and is ended by the nextnew-line character.99)

preprocessing-file:

group opt group:

group-part group group-part group-part:

pp-tokens opt new-line if-section

control-line if-section:

if-group elif-groups opt else-group opt endif-line if-group:

# ifdef identifier new-line group opt

# ifndef identifier new-line group opt elif-groups:

elif-group elif-groups elif-group elif-group:

# elif constant-expression new-line group opt else-group:

# else new-line group opt endif-line:

# endif new-line

99)Thus, preprocessing directives are commonly called “lines.” These “lines” have no other syntactic significance, as all white space isequivalent except in certain situations during preprocessing (see the # character string literal creation operator in 16.3.2, for example).

Trang 7

16– 2 Preprocessing directives DRAFT: 28 April 1995 16 Preprocessing directives

control-line:

# include pp-tokens new-line

# define identifier replacement-list new-line

# define identifier lparen identifier-list opt ) replacement-list new-line

# undef identifier new-line

# line pp-tokens new-line

# error pp-tokens opt new-line

# pragma pp-tokens opt new-line

preprocessing-token pp-tokens preprocessing-token new-line:

the new-line character

2 The only white-space characters that shall appear between preprocessing tokens within a preprocessing

directive (from just after the introducing#preprocessing token through just before the terminating new-linecharacter) are space and horizontal-tab (including spaces that have replaced comments or possibly otherwhite-space characters in translation phase 3)

3 The implementation can process and skip sections of source files conditionally, include other source files,

and replace macros These capabilities are called preprocessing, because conceptually they occur before

translation of the resulting translation unit

4 The preprocessing tokens within a preprocessing directive are not subject to macro expansion unless

other-wise stated

[cpp.cond] 16.1 Conditional inclusion

1 The expression that controls conditional inclusion shall be an integral constant expression except that: it

shall not contain a cast; identifiers (including those lexically identical to keywords) are interpreted asdescribed below;100)and it may contain unary operator expressions of the form

defined identifier

or

defined ( identifier )which evaluate to1if the identifier is currently defined as a macro name (that is, if it is predefined or if ithas been the subject of a#definepreprocessing directive without an intervening#undefdirective withthe same subject identifier), zero if it is not

2 Each preprocessing token that remains after all macro replacements have occurred shall be in the lexical

form of a token (2.5)

3 Preprocessing directives of the forms

# elif constant-expression new-line group opt

check whether the controlling constant expression evaluates to nonzero

100)Because the controlling constant expression is evaluated during translation phase 4, all identifiers either are or are not macronames — there simply are no keywords, enumeration constants, and so on.

Trang 8

16.1 Conditional inclusion DRAFT: 28 April 1995 Preprocessing directives 16– 3

4 Prior to evaluation, macro invocations in the list of preprocessing tokens that will become the controlling

constant expression are replaced (except for those macro names modified by thedefinedunary operator),just as in normal text If the tokendefinedis generated as a result of this replacement process or use ofthedefined unary operator does not match one of the two specified forms prior to macro replacement,the behavior is undefined After all replacements due to macro expansion and thedefinedunary operatorhave been performed, all remaining identifiers are replaced with the pp-number0, and then each prepro-cessing token is converted into a token The resulting tokens comprise the controlling constant expressionwhich is evaluated according to the rules of 5.19 using arithmetic that has at least the ranges specified in18.2, except thatint andunsigned intact as if they have the same representation as, respectively,longandunsigned long This includes interpreting character literals, which may involve convertingescape sequences into execution character set members Whether the numeric value for these character lit-erals matches the value obtained when an identical character literal occurs in an expression (other thanwithin a#ifor#elifdirective) is implementation-defined.101)Also, whether a single-character charac-ter literal may have a negative value is implementation-defined

5 Preprocessing directives of the forms

# ifdef identifier new-line group opt

# ifndef identifier new-line group opt

check whether the identifier is or is not currently defined as a macro name Their conditions are equivalent

to#if definedidentifier and#if !definedidentifier respectively.

6 Each directive’s condition is checked in order If it evaluates to false (zero), the group that it controls is

skipped: directives are processed only through the name that determines the directive in order to keep track

of the level of nested conditionals; the rest of the directives’ preprocessing tokens are ignored, as are theother preprocessing tokens in the group Only the first group whose control condition evaluates to true(nonzero) is processed If none of the conditions evaluates to true, and there is a #else directive, thegroup controlled by the#elseis processed; lacking a#elsedirective, all the groups until the#endifare skipped.102)

[cpp.include] 16.2 Source file inclusion

1 A#includedirective shall identify a header or source file that can be processed by the implementation

2 A preprocessing directive of the form

# include <h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specifiedsequence between the<and>delimiters, and causes the replacement of that directive by the entire contents

of the header How the places are specified or the header identified is implementation-defined

3 A preprocessing directive of the form

# include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specifiedsequence between the "delimiters The named source file is searched for in an implementation-definedmanner If this search is not supported, or if the search fails, the directive is reprocessed as if it read

# include <h-char-sequence> new-line

with the identical contained sequence (including>characters, if any) from the original directive

Trang 9

16– 4 Preprocessing directives DRAFT: 28 April 1995 16.2 Source file inclusion

4 A preprocessing directive of the form

# include pp-tokens new-line

(that does not match one of the two previous forms) is permitted The preprocessing tokens afterinclude

in the directive are processed just as in normal text (Each identifier currently defined as a macro name isreplaced by its replacement list of preprocessing tokens.)The directive resulting after all replacements shallmatch one of the two previous forms.103) The method by which a sequence of preprocessing tokensbetween a< and a>preprocessing token pair or a pair of"characters is combined into a single headername preprocessing token is implementation-defined

5 There shall be an implementation-defined mapping between the delimited sequence and the external source

file name The implementation shall provide unique mappings for sequences consisting of one or more

nondigits (2.7) followed by a period (.) and a single nondigit The implementation may ignore the

distinc-tions of alphabetical case and restrict the mapping to six significant characters before the period

6 A #include preprocessing directive may appear in a source file that has been read because of a

#includedirective in another file, up to an implementation-defined nesting limit

7 [Example: The most common uses of#includepreprocessing directives are as in the following:

1 Two replacement lists are identical if and only if the preprocessing tokens in both have the same number,

ordering, spelling, and white-space separation, where all white-space separations are considered identical

2 An identifier currently defined as a macro without use of lparen (an object-like macro) may be redefined by

another#definepreprocessing directive provided that the second definition is an object-like macro nition and the two replacement lists are identical

defi-3 An identifier currently defined as a macro using lparen (a function-like macro) may be redefined by another

#define preprocessing directive provided that the second definition is a function-like macro definitionthat has the same number and spelling of parameters, and the two replacement lists are identical

4 The number of arguments in an invocation of a function-like macro shall agree with the number of

parame-ters in the macro definition, and there shall exist a)preprocessing token that terminates the invocation

5 A parameter identifier in a function-like macro shall be uniquely declared within its scope

6 The identifier immediately following thedefineis called the macro name There is one name space for

macro names Any white-space characters preceding or following the replacement list of preprocessingtokens are not considered part of the replacement list for either form of macro

103)Note that adjacent string literals are not concatenated into a single string literal (see the translation phases in 2.1); thus, an sion that results in two string literals is an invalid directive.

Trang 10

expan-16.3 Macro replacement DRAFT: 28 April 1995 Preprocessing directives 16– 5

7 If a#preprocessing token, followed by an identifier, occurs lexically at the point at which a preprocessing

directive could begin, the identifier is not subject to macro replacement

8 A preprocessing directive of the form

# define identifier replacement-list new-line

defines an object-like macro that causes each subsequent instance of the macro name104)to be replaced bythe replacement list of preprocessing tokens that constitute the remainder of the directive The replacementlist is then rescanned for more macro names as specified below

9 A preprocessing directive of the form

# define identifier lparen identifier-list opt ) replacement-list new-line

defines a function-like macro with parameters, similar syntactically to a function call The parameters arespecified by the optional list of identifiers, whose scope extends from their declaration in the identifier listuntil the new-line character that terminates the #define preprocessing directive Each subsequentinstance of the function-like macro name followed by a(as the next preprocessing token introduces thesequence of preprocessing tokens that is replaced by the replacement list in the definition (an invocation ofthe macro) The replaced sequence of preprocessing tokens is terminated by the matching)preprocessingtoken, skipping intervening matched pairs of left and right parenthesis preprocessing tokens Within thesequence of preprocessing tokens making up an invocation of a function-like macro, new-line is considered

a normal white-space character

10 The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the list of

arguments for the function-like macro The individual arguments within the list are separated by commapreprocessing tokens, but comma preprocessing tokens between matching inner parentheses do not separatearguments If (before argument substitution) any argument consists of no preprocessing tokens, the behav-ior is undefined If there are sequences of preprocessing tokens within the list of arguments that would oth-erwise act as preprocessing directives, the behavior is undefined

[cpp.subst] 16.3.1 Argument substitution

1 After the arguments for the invocation of a function-like macro have been identified, argument substitution

takes place A parameter in the replacement list, unless preceded by a#or##preprocessing token or lowed by a##preprocessing token (see below), is replaced by the corresponding argument after all macroscontained therein have been expanded Before being substituted, each argument’s preprocessing tokens arecompletely macro replaced as if they formed the rest of the translation unit; no other preprocessing tokensare available

fol-[cpp.stringize] 16.3.2 The # operator

1 Each#preprocessing token in the replacement list for a function-like macro shall be followed by a

parame-ter as the next preprocessing token in the replacement list

2 If, in the replacement list, a parameter is immediately preceded by a # preprocessing token, both are

replaced by a single character string literal preprocessing token that contains the spelling of the ing token sequence for the corresponding argument Each occurrence of white space between theargument’s preprocessing tokens becomes a single space character in the character string literal Whitespace before the first preprocessing token and after the last preprocessing token comprising the argument isdeleted Otherwise, the original spelling of each preprocessing token in the argument is retained in thecharacter string literal, except for special handling for producing the spelling of string literals and characterliterals: a\character is inserted before each"and\character of a character literal or string literal (includ-ing the delimiting "characters) If the replacement that results is not a valid character string literal, thebehavior is undefined The order of evaluation of#and##operators is unspecified

preprocess-

104)Since, by macro-replacement time, all character literals and string literals are preprocessing tokens, not sequences possibly taining identifier-like subsequences (see 2.1.1.2, translation phases), they are never scanned for macro names or parameters.

Trang 11

con-16– 6 Preprocessing directives DRAFT: 28 April 1995 16.3.3 The ## operator

[cpp.concat] 16.3.3 The ## operator

1 A##preprocessing token shall not occur at the beginning or at the end of a replacement list for either form

of macro definition

2 If, in the replacement list, a parameter is immediately preceded or followed by a##preprocessing token,

the parameter is replaced by the corresponding argument’s preprocessing token sequence

3 For both object-like and function-like macro invocations, before the replacement list is reexamined for

more macro names to replace, each instance of a##preprocessing token in the replacement list (not from

an argument) is deleted and the preceding preprocessing token is concatenated with the following cessing token If the result is not a valid preprocessing token, the behavior is undefined The resultingtoken is available for further macro replacement The order of evaluation of##operators is unspecified

prepro-[cpp.rescan] 16.3.4 Rescanning and further replacement

1 After all parameters in the replacement list have been substituted, the resulting preprocessing token

sequence is rescanned with all subsequent preprocessing tokens of the source file for more macro names toreplace

2 If the name of the macro being replaced is found during this scan of the replacement list (not including the

rest of the source file’s preprocessing tokens), it is not replaced Further, if any nested replacementsencounter the name of the macro being replaced, it is not replaced These nonreplaced macro name prepro-cessing tokens are no longer available for further replacement even if they are later (re)examined in con-texts in which that macro name preprocessing token would otherwise have been replaced

3 The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing

directive even if it resembles one

[cpp.scope] 16.3.5 Scope of macro definitions

1 A macro definition lasts (independent of block structure) until a corresponding #undef directive is

encountered or (if none is encountered) until the end of the translation unit

2 A preprocessing directive of the form

# undef identifier new-line

causes the specified identifier no longer to be defined as a macro name It is ignored if the specified fier is not currently defined as a macro name

identi-3 [Note: The simplest use of this facility is to define a “manifest constant,” as in

#define TABSIZE 100

int table[TABSIZE];

4 The following defines a function-like macro whose value is the maximum of its arguments It has the

advantages of working for any compatible types of the arguments and of generating in-line code without theoverhead of function calling It has the disadvantages of evaluating one or the other of its arguments a sec-ond time (including side effects) and generating more code than a function if invoked several times It alsocannot have its address taken, as it has none

#define max(a, b) ((a) > (b) ? (a) : (b))

The parentheses ensure that the arguments and the resulting expression are bound properly

5 To illustrate the rules for redefinition and reexamination, the sequence

Trang 12

16.3.5 Scope of macro definitions DRAFT: 28 April 1995 Preprocessing directives 16– 7

#define xglue(a, b) glue(a, b)

#define HIGHLOW "hello"

#define LOW LOW ", world"

debug(1, 2);

fputs(str(strncmp("abc\0d", "abc", ’\4’) /* this goes away */

= = 0) str(: @\n), s);

#include xstr(INCFILE(2).h) glue(HIGH, LOW);

Space around the#and##tokens in the macro definition is optional

7 And finally, to demonstrate the redefinition rules, the following sequence is valid

#define OBJ_LIKE (1-1)

#define OBJ_LIKE /* white space */ (1-1) /* other */

#define FTN_LIKE(a) ( a )

#define FTN_LIKE( a )( /* note the white space */ \

a /* other stuff on this line

*/ )

Trang 13

16– 8 Preprocessing directives DRAFT: 28 April 1995 16.3.5 Scope of macro definitions

But the following redefinitions are invalid:

#define OBJ_LIKE (0) /* different token sequence */

#define OBJ_LIKE (1 - 1) /* different white space */

#define FTN_LIKE(b) ( a ) /* different parameter usage */

#define FTN_LIKE(b) ( b ) /* different parameter spelling */

—end note]

[cpp.line] 16.4 Line control

1 The string literal of a#linedirective, if present, shall be a character string literal

2 The line number of the current source line is one greater than the number of new-line characters read or

introduced in translation phase 1 (2.1) while processing the source file to the current token

3 A preprocessing directive of the form

# line digit-sequence new-line

causes the implementation to behave as if the following sequence of source lines begins with a source linethat has a line number as specified by the digit sequence (interpreted as a decimal integer) The digitsequence shall not specify zero, nor a number greater than 32767

4 A preprocessing directive of the form

# line digit-sequence "s-char-sequence opt" new-line

sets the line number similarly and changes the presumed name of the source file to be the contents of thecharacter string literal

5 A preprocessing directive of the form

# line pp-tokens new-line

(that does not match one of the two previous forms) is permitted The preprocessing tokens afterlineonthe directive are processed just as in normal text (each identifier currently defined as a macro name isreplaced by its replacement list of preprocessing tokens) The directive resulting after all replacementsshall match one of the two previous forms and is then processed as appropriate

[cpp.error] 16.5 Error directive

1 A preprocessing directive of the form

# error pp-tokens opt new-line

causes the implementation to produce a diagnostic message that includes the specified sequence of cessing tokens

prepro-[cpp.pragma] 16.6 Pragma directive

1 A preprocessing directive of the form

# pragma pp-tokens opt new-line

causes the implementation to behave in an implementation-defined manner Any pragma that is not nized by the implementation is ignored

recog-[cpp.null] 16.7 Null directive

1 A preprocessing directive of the form

has no effect

Trang 14

16.8 Predefined macro names DRAFT: 28 April 1995 Preprocessing directives 16– 9

[cpp.predefined] 16.8 Predefined macro names

1 The following macro names shall be defined by the implementation:

_ _LINE_ _The line number of the current source line (a decimal constant)

_ _FILE_ _The presumed name of the source file (a character string literal)

_ _DATE_ _The date of translation of the source file (a character string literal of the form

"Mmm dd yyyy", where the names of the months are the same as those generated by theasctimefunction, and the first character ofddis a space character if the value is less than 10) If the date oftranslation is not available, an implementation-defined valid date shall be supplied

_ _TIME_ _The time of translation of the source file (a character string literal of the form"hh:mm:ss"

as in the time generated by the asctime function) If the time of translation is not available, animplementation-defined valid time shall be supplied

_ _STDC_ _Whether_ _STDC_ _is defined and if so, what its value is, are implementation-defined._ _cplusplusThe name _ _cplusplus is defined (to an unspecified value) when compiling a C + +translation unit

2 The values of the predefined macros (except for_ _LINE_ _and_ _FILE_ _) remain constant throughout

the translation unit

3 None of these macro names, nor the identifierdefined, shall be the subject of a#defineor a#undef

preprocessing directive All predefined macro names shall begin with a leading underscore followed by anuppercase letter or a second underscore

Trang 16

1 This clause describes the contents of the C + + Standard library, how a well-formed C + + program makes use

of the library, and how a conforming implementation may provide the entities in the library

2 The C + + Standard library provides an extensible framework, and contains components for: language

sup-port, diagnostics, general utilities, strings, locales, containers, iterators, algorithms, numerics, andinput/output The language support components are required by certain parts of the C + + language, such asmemory allocation (5.3.4, 5.3.5) and exception processing (15)

3 The general utilities include components used by other library elements, such as a predefined storage

allo-cator for dynamic storage management (3.7.3) The diagnostics components provide a consistent work for reporting errors in a C + + program, including predefined exception classes

frame-4 The strings components provide support for manipulating text represented as sequences of type char,

sequences of typewchar_t, or sequences of any other ‘‘character-like’’ type The localization nents extend internationalization support for such text processing

compo-5 The containers, iterators, and algorithms provide a C + + program with access to a subset of the most widely

used algorithms and data structures

6 Numeric algorithms and the complex number components extend support for numeric processing The

valarray components provide support for n-at-a-time processing, potentially implemented as parallel

operations on platforms that support such processing

7 Theiostreamscomponents are the primary mechanism for C + + program input/output They can be used

with other elements of the library, particularly strings, locales, and iterators

8 This library also makes available the facilities of the Standard C library, suitably adjusted to ensure static

type safety

9 The following subclauses describe the definitions (17.1), and method of description (17.2) for the library

Subclause 17.3 and Clauses 18 through 27 specify the contents of the library, and library requirements andconstraints on both well-formed C + + programs and conforming implementations

[lib.definitions] 17.1 Definitions

— category: A logical collection of library entities Clauses 18 through 27 each describe a single category

of entities within the library

— comparison function: An operator function (13.5) for any of the equality (5.10) or relational (5.9)

operators

— component: A group of library entities directly related as members, parameters, or return types For

example, the class templatebasic_stringand the non-member template functions that operate on

strings can be referred to as the string component.

— default behavior: A description of replacement function and handler function semantics Any specific

behavior provided by the implementation, within the scope of the required behavior.

— handler function: A non-reserved function whose definition may be provided by a C + + program A

C + + program may designate a handler function at various points in its execution, by supplying a pointer

to the function when calling any of the library functions that install handler functions (18)

Trang 17

17– 2 Library introduction DRAFT: 28 April 1995 17.1 Definitions

— modifier function: A class member function (9.4), other than constructors, assignment, or destructor,

that alters the state of an object of the class

— object state: The current value of all nonstatic class members of an object (9.2) The state of an object

can be obtained by using one or more observer functions

— observer function: A class member function (9.4) that accesses the state of an object of the class, but

does not alter that state Observer functions are specified asconstmember functions (9.4.2)

— replacement function: A non-reserved function whose definition is provided by a C + + program Onlyone definition for such a function is in effect for the duration of the program’s execution, as the result ofcreating the program (2.1) and resolving the definitions of all translation units (3.5)

— required behavior: A description of replacement function and handler function semantics, applicable

to both the behavior provided by the implementation and the behavior that shall be provided by anyfunction definition in the program If a function defined in a C + + program fails to meet the requiredbehavior when it executes, the behavior is undefined

— reserved function: A function, specified as part of the C + + Standard library, that must be defined by the

implementation If a C + + program provides a definition for any reserved function, the results are fined

unde-Subclause 1.3 defines additional terms used elsewhere in this International Standard

[lib.description] 17.2 Method of description (Informative)

1 This subclause describes the conventions used to describe the C + + Standard library It describes the

struc-tures of the normative Clauses 18 through 27 (17.2.1), and other editorial conventions (17.2.2)

[lib.structure] 17.2.1 Structure of each subclause

1 Subclause 17.3.1 provides a summary of the C + + Standard library’s contents Other Library clauses provide

detailed specifications for each of the components in the library, as shown in Table 10:

Table 10—Library Categories

Trang 18

tem-17.2.1 Structure of each subclause DRAFT: 28 April 1995 Library introduction 17– 3

— Detailed specifications

— References to the Standard C library

[lib.structure.summary] 17.2.1.1 Summary

1 The Summary provides a synopsis of the category, and introduces the first-level subclauses Each

sub-clause also provides a summary, listing the headers specified in the subsub-clause and the library entities vided in each header

pro-2 Paragraphs labelled ‘‘Note(s):’’ or ‘‘Example(s):’’ are informative, other paragraphs are normative

3 The summary and the detailed specifications are presented in the order:

1 The library can be extended by a C + + program Each clause, as applicable, describes the requirements that

such extensions must meet Such extensions are generally one of the following:

— Template arguments

— Derived classes

— Containers, iterators, and/or algorithms that meet an interface convention

2 The string and iostreams components use an explicit representation of operations required of template

argu-ments They use a template class nameXXX_traitsto define these constraints

3 Interface convention requirements are stated as generally as possible Instead of stating ‘‘class X has to

define a member functionoperator++(),’’ the interface requires ‘‘for any objectxof class X,++xisdefined.’’ That is, whether the operator is a member is unspecified

4 Requirements are stated in terms of well-defined expressions, which define valid terms of the types that

sat-isfy the requirements For every set of requirements there is a table that specifies an initial set of the validexpressions and their semantics (20.1, 23.1, 24.1) Any generic algorithm (25) that uses the requirements isdescribed in terms of the valid expressions for its formal type parameters

5 In some cases the semantic requirements are presented as C + + code Such code is intended as a

specifica-tion of equivalence of a construct to another construct, not necessarily as the way the construct must beimplemented.106)

[lib.structure.specifications] 17.2.1.3 Specifications

1 The detailed specifications each contain the following elements:107)

— Name and brief description

— Synopsis (class definition or function prototype, as appropriate)

— Restrictions on template arguments, if any

106)Although in some cases the code given is unambiguously the optimum implementation.

107)The form of these specifications was designed to follow the conventions established by existing C + + library vendors.

Trang 19

17– 4 Library introduction DRAFT: 28 April 1995 17.2.1.3 Specifications

— Decription of class invariants

— Description of function semantics

2 Descriptions of class member functions follow the order (as appropriate):108)

— Constructor(s) and destructor

— Copying & assignment functions

— Comparison functions

— Modifier functions

— Observer functions

— Operators and other non-member functions

3 Descriptions of function semantics contain the following elements (as appropriate):109)

— Requires: the preconditions for calling the function

— Effects: the actions performed by the function

— Postconditions: the observable results established by the function

— Returns: a description of the value(s) returned by the function

— Throws: any exceptions thrown by the function, and the conditions that would cause the exception

— Complexity: the time and/or space complexity of the function

4 For non-reserved replacement and handler functions, Clause 18 specifies two behaviors for the functions in

question: their required and default behavior The default behavior describes a function definition provided

by the implementation The required behavior describes the semantics of a function definition provided by

either the implementation or a C + + program Where no distinction is explicitly made in the description, thebehavior described is the required behavior

5 If an operation is required to be linear time, it means no worse than linear time, and a constant time

opera-tion satisfies the requirement

[lib.structure.see.also] 17.2.1.4 C Library

1 Paragraphs labelled ‘‘SEE ALSO:’’ contain cross-references to the relevant portions of this Standard and the

ISO C standard, which is incorporated into this Standard by reference

[lib.conventions] 17.2.2 Other conventions

1 This subclause describes several editorial conventions used to describe the contents of the C + + Standard

library These conventions are for describing implementation-defined types (17.2.2.1), and member tions (17.2.2.2)

func-[lib.type.descriptions] 17.2.2.1 Type descriptions

1 The Requirements subclauses describe names that are used to specify constraints on template

argu-ments.110)These names are used in Clauses 23, 25, and 26 to describe the types that may be supplied asarguments by a C + + program when instantiating template components from the library

Trang 20

17.2.2.1 Type descriptions DRAFT: 28 April 1995 Library introduction 17– 5

2 Certain types defined in Clause 27 are used to describe implementation-defined types They are based on

other types, but with added constraints

[lib.enumerated.types] 17.2.2.1.1 Enumerated types

1 Several types defined in Clause 27 are enumerated types Each enumerated type may be implemented as an

enumeration or as a synonym for an enumeration.111)

2 The enumerated typeenumeratedcan be written:

enum enumerated { V0, V1, V2, V3, };

static const enumerated C0(V0);

static const enumerated C1(V1);

static const enumerated C2(V2);

static const enumerated C3(V3);

3 Here, the namesC0,C1, etc represent enumerated elements for this particular enumerated type All such

elements have distinct values

[lib.bitmask.types] 17.2.2.1.2 Bitmask types

1 Several types defined in Clause 27 are bitmask types Each bitmask type can be implemented as an

enu-merated type that overloads certain operators, as an integer type, or as abitset(23.2.1)

2 The bitmask typebitmaskcan be written:

enum bitmask {

V0 = 1 << 0, V1 = 1 << 1, V2 = 1 << 2, V3 = 1 << 3,

};

static const bitmask C0(V0);

static const bitmask C1(V1);

static const bitmask C2(V2);

static const bitmask C3(V3);

bitmask& operator&=(bitmask& X, bitmask Y) { X = bitmask(X & Y); return X; } bitmask& operator|=(bitmask& X, bitmask Y) { X = bitmask(X | Y); return X; } bitmask& operator^=(bitmask& X, bitmask Y) { X = bitmask(X ^ Y); return X; } bitmask operator& (bitmask X, bitmask Y) { return bitmask(X & Y); }

bitmask operator| (bitmask X, bitmask Y) { return bitmask(X | Y); }

bitmask operator^ (bitmask X, bitmask Y) { return bitmask(X ^ Y); }

bitmask operator~ (bitmask X) { return (bitmask)~X; }

3 Here, the names C0,C1, etc represent bitmask elements for this particular bitmask type All such

ele-ments have distinct values such that, for any pairCiandCj,Ci&Ciis nonzero andCi&Cjis zero

4 The following terms apply to objects and values of bitmask types:

— To set a valueYin an objectXis to evaluate the expressionX=Y

— To clear a valueYin an objectXis to evaluate the expressionX&= ˜Y

— The valueYis set in the objectXif the expressionX&Yis nonzero

111)Such as an integer type, with constant integer values (3.9.1).

Trang 21

17– 6 Library introduction DRAFT: 28 April 1995 17.2.2.1.3 Character sequences

[lib.character.seq] 17.2.2.1.3 Character sequences

1 The Standard C library makes widespread use of characters and character sequences that follow a few

uni-form conventions:

— A letter is any of the 26 lowercase or 26 uppercase letters in the basic execution character set.112)

— The decimal-point character is the (single-byte) character used by functions that convert between a

(single-byte) character sequence and a value of one of the floating-point types It is used in the ter sequence to denote the beginning of a fractional part It is represented in Clauses 18 through 27 by aperiod,’.’, which is also its value in the"C"locale, but may change during program execution by acall tosetlocale(int, const char*),113)or by a change to alocaleobject, as described inClauses 22.1 and 27

charac-— A character sequence is an array object (8.3.4)Athat can be declared asT A[N], whereTis any of thetypeschar,unsigned char, orsigned char(3.9.1), optionally qualified by any combination

ofconstorvolatile The initial elements of the array have defined contents up to and including

an element determined by some predicate A character sequence can be designated by a pointer valueSthat points to its first element

[lib.byte.strings] 17.2.2.1.3.1 Byte strings

1 A null-terminated byte string, or NTBS , is a character sequence whose highest-addressed element with

defined content has the value zero (the terminating null character).114)

2 The length of an NTBS is the number of elements that precede the terminating null character An empty NTBS

has a length of zero

3 The value of an NTBS is the sequence of values of the elements up to and including the terminating null

character

4 A static NTBSis anNTBSwith static storage duration.115)

[lib.multibyte.strings] 17.2.2.1.3.2 Multibyte strings

1 A null-terminated multibyte string, or NTMBS , is anNTBSthat constitutes a sequence of valid multibyte

char-acters, beginning and ending in the initial shift state.116)

2 A static NTMBSis anNTMBSwith static storage duration

[lib.wide.characters] 17.2.2.1.3.3 Wide-character sequences

1 A wide-character sequence is an array object (8.3.4)Athat can be declared asT A[N], whereTis type

wchar_t(_basic.fundmental_), optionally qualified by any combination ofconstorvolatile Theinitial elements of the array have defined contents up to and including an element determined by somepredicate A character sequence can be designated by a pointer valueSthat designates its first element

2 A null-terminated wide-character string, or NTWCS , is a wide-character sequence whose highest-addressed

element with defined content has the value zero.117)

3 The length of an NTWCSis the number of elements that precede the terminating null wide character An

empty NTWCShas a length of zero

115)A string literal, such as "abc", is a static

NTBS 116)An

NTBS that contains characters only from the basic execution character set is also an NTMBS Each multibyte character then sists of a single byte.

con-117)Many of the objects manipulated by function signatures declared in<cwchar>are wide-character sequences or s.

Trang 22

17.2.2.1.3.3 Wide-character sequences DRAFT: 28 April 1995 Library introduction 17– 7

4 The value of an NTWCSis the sequence of values of the elements up to and including the terminating null

character

5 A static NTWCSis anNTWCSwith static storage duration.118)

[lib.functions.within.classes] 17.2.2.2 Functions within classes

1 For the sake of exposition, Clauses 18 through 27 do not describe copy constructors, assignment operators,

or (non-virtual) destructors with the same apparent semantics as those that can be generated by default(12.1, 12.4, 12.8)

2 It is unspecified whether the implementation provides explicit definitions for such member function

signa-tures, or for virtual destructors that can be generated by default

[lib.objects.within.classes] 17.2.2.3 Private members

1 Clauses 18 through 27 do not specify the representation of classes, and intentionally omit specification of

class members (9.2) An implementation may define static or non-static class members, or both, as needed

to implement the semantics of the member functions specified in Clauses 18 through 27

2 Objects of certain classes are sometimes required by the external specifications of their classes to store data,

apparently in member objects For the sake of exposition, subclauses 22.1.1, 23.2.1, 24.4.3, 24.4.4, 27.4.3,27.7.1, and 27.8.1.1 provide representative declarations, and semantic requirements, for private memberobjects of classes that meet the external specifications of the classes The declarations for such member

objects and the definitions of related member types are enclosed in a comment that ends with exposition

only, as in:

// streambuf* sb; exposition only

3 Any alternate implementation that provides equivalent external behavior is equally acceptable

[lib.requirements] 17.3 Library-wide requirements

1 This subclause specifies requirements that apply to the entire C + + Standard library Clauses 18 through 27

specify the requirements of individual entities within the library

2 The following subclauses describe the library’s contents and organization (17.3.1), how well-formed C + +

programs gain access to library entities (17.3.2), constraints on such programs (17.3.3), and constraints onconforming implementations (17.3.4)

[lib.organization] 17.3.1 Library contents and organization

1 This subclause provides a summary of the entities defined in the C + + Standard library Subclause 17.3.1.1

provides an alphabetical listing of entities by type, while subclause 17.3.1.2 provides an alphabetical listing

of library headers

[lib.contents] 17.3.1.1 Library contents

1 The C + + Standard library provides definitions for the following types of entities:

Trang 23

17– 8 Library introduction DRAFT: 28 April 1995 17.3.1.1 Library contents

— Functions

— Objects

2 All library entities shall be defined within the namespacestd

3 The C + + Standard library provides 54 standard macros from the C library (C.4)

4 The C + + Standard library provides 45 standard values from the C library (C.4)

5 The C + + Standard library provides 19 standard types from the C library (C.4), and 28 additional types, as

shown in Table 11:

Table 11—Standard Types

_

filebuf ostringstream wfilebuf wstreambuf

istringstream string wistringstream new_handler stringbuf wofstream ofstream terminate_handler wostream ostream unexpected_handler wostringstream_

6 The C + + Standard library provides 66 standard template classes, as shown in Table 12:

Table 12—Standard Template classes

_ _

allocator mask_array auto_ptr messages back_insert_iterator messages_byname basic_filebuf moneypunct basic_ifstream moneypunct_byname basic_ios money_get

basic_istream money_put basic_istringstream multimap basic_ofstream multiset basic_ostream numeric_limits basic_ostringstream numpunct basic_streambuf num_get basic_string num_put basic_stringbuf ostreambuf_iterator binary_negate ostream_iterator_ _

Trang 24

17.3.1.1 Library contents DRAFT: 28 April 1995 Library introduction 17– 9

_

binder1st pointer_to_binary_function binder2nd pointer_to_unary_function bitset priority_queue

codecvt queue codecvt_byname raw_storage_iterator collate reverse_bidirectional_iterator collate_byname reverse_iterator

complex set ctype slice_array ctype_byname stack deque time_get front_insert_iterator time_get_byname gslice_array time_put

indirect_array time_put_byname insert_iterator unary_negate istreambuf_iterator valarray istream_iterator vector list

map_

7 The C + + Standard library provides 24 standard template structures, as shown in Table 13:

Table 13—Standard Template structs

_

bidirectional_iterator less pair binary_function less_equal plus divides logical_and random_access_iterator equal_to logical_not string_char_traits forward_iterator logical_or times

greater_equal modulus input_iterator negate ios_traits not_equal_to

8 The C + + Standard library provides 86 standard template operator functions, as shown in Table 14

9 Types shown (enclosed in(and)) indicate that the given function is overloaded by that type Numbers

shown (enclosed in[and]) indicate how many overloaded functions are overloaded by that type

Trang 25

17– 10 Library introduction DRAFT: 28 April 1995 17.3.1.1 Library contents

Table 14—Standard Template operators

_ operator!= (basic_string) [5] operator<< (basic_string)

operator!= (complex) [3] operator<< (bitset) operator!= (istreambuf_iterator) operator<< (complex) operator!= (ostreambuf_iterator) operator<< (valarray) [3]

operator!= (T) operator<<=(valarray) [2]

operator!= (valarray) [3] operator<= (T) operator% (valarray) [3] operator<= (valarray) [3]

operator%= (valarray) [2] operator== (basic_string) [5]

operator& (bitset) operator== (complex) [3]

operator& (valarray) [3] operator== (deque) operator&& (valarray) [3] operator== (istreambuf_iterator) operator&= (valarray) [2] operator== (istream_iterator) operator* (complex) [3] operator== (list)

operator* (valarray) [3] operator== (map) operator*= (complex) operator== (multimap) operator*= (valarray) [2] operator== (multiset) operator+ (basic_string) [5] operator== (ostreambuf_iterator) operator+ (complex) [4] operator== (pair)

operator+ (reverse_iterator) operator== (queue) operator+ (valarray) [3] operator== (restrictor) operator+= (complex) operator== (reverse_bidir_iter) operator+= (valarray) [2] operator== (reverse_iterator) operator- (complex) [4] operator== (set)

operator- (reverse_iterator) operator== (stack) operator- (valarray) [3] operator== (valarray) [3]

operator-= (complex) operator== (vector) operator-= (valarray) [2] operator> (T) operator/ (complex) [3] operator> (valarray) [3]

operator/ (valarray) [3] operator>= (T) operator/= (complex) operator>= (valarray) [3]

operator/= (valarray) [2] operator>> (basic_string) operator< (deque) operator>> (bitset) operator< (list) operator>> (complex) operator< (map) operator>> (valarray) [3]

operator< (multimap) operator>>=(valarray) [2]

operator< (multiset) operator^ (bitset) operator< (pair) operator^ (valarray) [3]

operator< (queue) operator^= (valarray) [2]

operator< (restrictor) operator| (bitset) operator< (reverse_iterator) operator| (valarray) [3]

operator< (set) operator|= (valarray) [2]

operator< (stack) operator|| (valarray) [3]

operator< (valarray) [3]

operator< (vector)_

Trang 26

17.3.1.1 Library contents DRAFT: 28 April 1995 Library introduction 17– 11

Table 15—Standard Template functions

_

_

adjacent_difference [2] merge [2]

Trang 27

17– 12 Library introduction DRAFT: 28 April 1995 17.3.1.1 Library contents

_ _

get_temporary_buffer sort_heap [2]

imag (complex) sqrt (complex) includes [2] sqrt (valarray) inner_product [2] stable_partition inplace_merge [2] stable_sort [2]

inserter swap isalnum swap_ranges

islower tolower isprint toupper

isspace uninitialized_copy isupper uninitialized_fill_n

iterator_category [7] unique_copy [2]

lexicographical_compare [2] unititialized_fill log (complex) upper_bound [2]

log (valarray) value_type [7]

log10(complex) log10(valarray)_ _

11 The C + + Standard library provides 28 standard classes, as shown in Table 16

12 Type names (enclosed in<and>) indicate that these are specific instances of templates

Table 16—Standard Classes

_ _

bad_alloc ctype_byname<char> logic_error

bad_exception exception overflow_error bad_typeid gslice range_error basic_string<char> invalid_argument runtime_error basic_string<wchar_t> ios_base slice

complex<double> length_error type_info complex<float> locale vector<bool,allocator>

complex<long double> locale::facet ctype<char> locale::id_ _

13 The C + + Standard library provides 2 standard structures from the C library (C.4), and 16 additional

struc-tures, as shown in Table 17:

Trang 28

17.3.1.1 Library contents DRAFT: 28 April 1995 Library introduction 17– 13

Table 17—Standard Structs

_

bidirectional_iterator_tag nothrow codecvt_base output_iterator ctype_base output_iterator_tag forward_iterator_tag random_access_iterator_tag input_iterator_tag string_char_traits<char>

ios_traits<char> string_char_traits<wchar_t>

ios_traits<wchar_t> time_base money_base

money_base::pattern_

14 The C + + Standard library provides 12 standard operator functions, as shown in Table 18:

Table 18—Standard Operator functions

_

operator delete operator new[] (void*) operator delete[] operator< (vector<bool,allocator>) operator new operator<< (locale)

operator new (nothrow) operator== (vector<bool,allocator>) operator new (void*) operator>> (locale)

15 The C + + Standard library provides 208 standard functions from the C library (C.4), and 78 additional

func-tions, as shown in Table 19:

Trang 29

17– 14 Library introduction DRAFT: 28 April 1995 17.3.1.1 Library contents

Table 19—Standard Functions

_

abs (long double) modf (float,float*) abs (long) modf (long double,long double*)

acos (long double) noshowpoint

asin (long double) noskipws

atan (long double) oct

atan2(long double,long double) pow (long double) [2]

ceil (long double) right

cos (long double) setbase

cosh (long double) setiosflags dec setprecision

endl set_new_handler ends set_terminate

exp (long double) showbase fixed showpoint floor(float) showpos floor(long double) sin (float)

frexp(long double,int*) sinh (long double) hex skipws

ldexp(long double,int) tanh (long double) left terminate

log (long double) uppercase log10(float) ws

log10(long double) mod (float)_

16 The C + + Standard library provides 8 standard objects, as shown in Table 20:

Table 20—Standard Objects

_ _

cerr cin clog cout werr win wlog wout_ _





Trang 30

17.3.1.2 Headers DRAFT: 28 April 1995 Library introduction 17– 15

[lib.headers] 17.3.1.2 Headers

1 The elements of the C + + Standard library are declared or defined (as appropriate) in a header.119)

2 The C + + Standard library provides 32 C + + headers, as shown in Table 21:

Table 21—C++ Library Headers

_

<algorithm> <iomanip> <list> <queue> <typeinfo>

<bitset> <ios> <locale> <set> <utility>

<complex> <iosfwd> <map> <sstream> <valarray>

<deque> <iostream> <memory> <stack> <vector>

<exception> <istream> <new> <stdexcept>

<fstream> <iterator> <numeric> <streambuf>

<functional> <limits> <ostream> <string>

3 The facilities of the Standard C Library are provided in 18 additional headers, as shown in Table 22:

Table 22—C + + Headers for C Library Facilities

_

<cassert> <ciso646> <csetjmp> <cstdio> <cwchar>

<cctype> <climits> <csignal> <cstdlib> <cwctype>

<cerrno> <clocale> <cstdarg> <cstring>

<cfloat> <cmath> <cstddef> <ctime>

4 Except as noted in Clauses 18 through 27, the contents of each headercname shall be the same as that of

the corresponding header name.h, as specified in ISO C (Clause 7), or Amendment 1, (Clause 7), as

appro-priate In this C + + Standard library, however, the declarations and definitions are within namespace scope(3.3.4) of the namespacestd

5 Subclause D.1, Standard C library headers, describes the effects of using the name.h(C header) form in a

C + + program.120)

[lib.compliance] 17.3.1.3 Freestanding implementations

1 Two kinds of implementations are defined: hosted and freestanding (1.7) For a hosted implementation,

this International Standard describes the set of available headers

2 A freestanding implementation has has an implementation-defined set of headers This set shall include at

least the following headers, as shown in Table 23:

119)A header is not necessarily a source file, nor are the sequences delimited by<and>in header names necessarily valid source filenames (16.2).

120)The".h"headers dump all their names into the global namespace, whereas the newer forms keep their names in namespace

std Therefore, the newer forms are the preferred forms for all uses except for C + + programs which are intended to be strictly ible with C.

Trang 31

compat-17– 16 Library introduction DRAFT: 28 April 1995 17.3.1.3 Freestanding implementations

Table 23—C + + Headers for Freestanding Implementations

3 The supplied version of the header <cstdlib> shall declare at least the functions abort(),

atexit(), andexit()(18.3)

[lib.using] 17.3.2 Using the library

1 This subclause describes how a C + + program gains access to the facilities of the C + + Standard library

Sub-clause 17.3.2.1 describes effects during translation phase 4, while subSub-clause 17.3.2.2 describes effects ing phase 8 (2.1)

dur-[lib.using.headers] 17.3.2.1 Headers

1 The entities in the C + + Standard library are defined in headers, whose contents are made available to a

translation unit when it contains the appropriate#includepreprocessing directive (16.2)

2 A translation unit may include library headers in any order (2) Each may be included more than once, with

no effect different from being included exactly once, except that the effect of including either<cassert>

or<assert.h>depends each time on the lexically current definition ofNDEBUG.121)

3 A translation unit shall include a header only outside of any external declaration or definition, and shall

include the header lexically before the first reference to any of the entities it declares or first defines in thattranslation unit

[lib.using.linkage] 17.3.2.2 Linkage

1 Entities in the C + + Standard library have external linkage (3.5) Unless otherwise specified, objects and

functions have the default extern "C++"linkage (7.5)

2 It is unspecified whether a name from the Standard C library declared with external linkage has either

extern "C"or extern "C++"linkage.122)

3 Objects and functions defined in the library and required by a C + + program are included in the program

prior to program startup

121)This is the same as the Standard C library.

122)The only reliable way to declare an object or function signature from the Standard C library is by including the header thatdeclares it, notwithstanding the latitude granted in subclause 7.1.7 of the C Standard.

Trang 32

17.3.3 Constraints on programs DRAFT: 28 April 1995 Library introduction 17– 17

[lib.constraints] 17.3.3 Constraints on programs

1 This subclause describes restrictions on C + + programs that use the facilities of the C + + Standard library

The following subclauses specify constraints on the program’s namespace (17.3.3.1), its use of headers(17.3.3.2), classes derived from standard library classes (17.3.3.3), definitions of replacement functions(17.3.3.4), and installation of handler functions during execution (17.3.3.5)

[lib.reserved.names] 17.3.3.1 Reserved names

1 A C + + program shall not extend the namespacestd

2 The C + + Standard library reserves the following kinds of names:

— Macros

— Global names

— Names with external linkage

3 If the program declares or defines a name in a context where it is reserved, other than as explicitly allowed

by this clause, the behavior is undefined

[lib.macro.names] 17.3.3.1.1 Macro names

1 Each name defined as a macro in a header is reserved to the implementation for any use if the translation

unit includes the header.123)

2 A translation unit that includes a header shall not contain any macros that define names declared or defined

in that header Nor shall such a translation unit define macros for names lexically identical to keywords

[lib.global.names] 17.3.3.1.2 Global names

1 Each header also optionally declares or defines names which are always reserved to the implementation for

any use and names reserved to the implementation for use at file scope

2 Certain sets of names and function signatures are reserved whether or not a translation unit includes a

header:

3 Each name that begins with an underscore and either an uppercase letter or another underscore (2.8) is

reserved to the implementation for any use

4 Each name that begins with an underscore is reserved to the implementation for use as a name with file

scope or within the namespacestdin the ordinary name space

[lib.extern.names] 17.3.3.1.3 External linkage

1 Each name declared as an object with external linkage in a header is reserved to the implementation to

des-ignate that library object with external linkage.124)

2 Each global function signature declared with external linkage in a header is reserved to the implementation

to designate that function signature with external linkage.125)

3 Each name having two consecutive underscores (2.8) is reserved to the implementation for use as a name

with both extern "C"and extern "C++"linkage

4 Each name from the Standard C library declared with external linkage is reserved to the implementation for

use as a name with extern "C"linkage

123)It is not permissible to remove a library macro definition by using the#undefdirective.

124)The list of such reserved names includeserrno, declared or defined in<cerrno>.

125) The list of such reserved function signatures with external linkage includessetjmp(jmp_buf), declared or defined in

<csetjmp> , and va_end(va_list) , declared or defined in <cstdarg>

Trang 33

17– 18 Library introduction DRAFT: 28 April 1995 17.3.3.1.3 External linkage

5 Each function signature from the Standard C library declared with external linkage is reserved to the

imple-mentation for use as a function signature with both extern "C"and extern "C++"linkage.126)

[lib.alt.headers] 17.3.3.2 Headers

1 If a file has a name equivalent to the derived file name for one of the C + + Standard library headers, is not

provided as part of the implementation, and is placed in any of the standard places for a source file to beincluded (16.2), the behavior is undefined

[lib.derived.classes] 17.3.3.3 Derived classes

1 Virtual member function signatures defined for a base class in the C + + Standard library may be overridden

in a derived class defined in the program (10.3)

[lib.replacement.functions] 17.3.3.4 Replacement functions

1 Clauses 18 through 27 describe the behavior of numerous functions defined by the C + + Standard library

Under some circumstances, however, certain of these function descriptions also apply to replacement tions defined in the program (17.1)

func-2 A C + + program may provide the definition for any of six (6) dynamic memory allocation function

signa-tures declared in header<new>(3.7.3, 18):127)

3 The program’s definitions are used instead of the default versions supplied by the implementation (8.4)

Such replacement occurs prior to program startup (3.2, 3.6)

[lib.handler.functions] 17.3.3.5 Handler functions

1 The C + + Standard library provides default versions of the three handler functions (18):

— new_ handler

— unexpected_ handler

— terminate_ handler

2 A C + + program may install different handler functions during execution, by supplying a pointer to a

func-tion defined in the program or the library as an argument to (respectively):

126)The function signatures declared in<cwchar>and<cwctype>are always reserved, notwithstanding the restrictions imposed

in subclause 4.5.1 of Amendment 1 to the C Standard for these headers.

Trang 34

17.3.3.6 Other functions DRAFT: 28 April 1995 Library introduction 17– 19

[lib.res.on.functions] 17.3.3.6 Other functions

1 In certain cases (replacement functions, handler functions, operations on types used to instantiate standard

library template components), the C + + Standard library depends on components supplied by a C + + program

If these components do not meet their requirements, the Standard places no requirements on the tation

implemen-2 In particular, the effects are undefined in the following cases:

— for replacement functions (18.4.1), if the installed handler function does not implement the semantics of

the applicable Required behavior paragraph.

— for handler functions (18.4.2.2, 18.6.2.1, 18.6.1.2), if the installed handler function does not implement

the semantics of the applicable Required behavior paragraph

— for types used as template arguments when instantiating a template component, if the operations on the

type do not implement the semantics of the applicable Requirements subclause (20.1, 23.1, 24.1, 26.1).

— if any of these functions or operations throws an exception, unless specifically allowed in the applicable

Required behavior paragraph.

[lib.res.on.arguments] 17.3.3.7 Function arguments

1 Each of the following statements applies to all arguments to functions defined in the C + + Standard library,

unless explicitly stated otherwise

— If an argument to a function has an invalid value (such as a value outside the domain of the function, or

a pointer invalid for its intended use), the behavior is undefined

— If a function argument is described as being an array, the pointer actually passed to the function shallhave a value such that all address computations and accesses to objects (that would be valid if thepointer did point to the first element of such an array) are in fact valid

[lib.conforming] 17.3.4 Conforming implementations

1 This subclause describes the constraints upon, and latitude of, implementations of the C + + Standard library

The following subclauses describe an implementation’s use of headers (17.3.4.1), macros (17.3.4.2), globalfunctions (17.3.4.3), member functions (17.3.4.4), reentrancy (17.3.4.5), access specifiers (17.3.4.6), classderivation (17.3.4.7), and exceptions (17.3.4.8)

[lib.res.on.headers] 17.3.4.1 Headers

1 Certain types and macros are defined in more than one header For such an entity, a second or subsequent

header that also defines it may be included after the header that provides its initial definition (3.2)

2 Header inclusion is limited as follows:

— None of the C + + headers includes any of the C headers However, any of the C + + headers can includeany of the other C + + headers, and must include a C + + header that contains any needed definition.127)

— The C headers ( h form, described in Annex D, D.1) shall include only their corresponding C + +header, as described above (17.3.1.2)

— The C + + headers listed in Table 21, C + + Library Headers, shall include the header(s) listed in their

respective Synopsis subclause (18.4, 18.5, 18.6, 19.1, 20.2, 20.3, 20.4, 21.1, 22.1, 23.2, 24, 25, 26.2,

Trang 35

17– 20 Library introduction DRAFT: 28 April 1995 17.3.4.1 Headers

3 However, any of the C + + headers can include any of the other C + + headers, and must include a C + + header

that contains any needed definition.129)

[lib.res.on.macro.definitions] 17.3.4.2 Restrictions on macro definitions

1 The names or global function signatures described in subclause 17.3.1.1 are reserved to the

implementa-tion.130)

2 All object-like macros defined by the Standard C library and described in this clause as expanding to

inte-gral constant expressions are also suitable for use in#ifpreprocessing directives, unless explicitly statedotherwise

[lib.global.functions] 17.3.4.3 Global functions

1 It is unspecified whether any global functions in the C + + Standard library are defined asinline(7.1.2)

2 A call to a global function signature described in Clauses 18 through 27 behaves the same as if the

imple-mentation declares no additional global function signatures.131)

[lib.member.functions] 17.3.4.4 Member functions

1 It is unspecified whether any member functions in the C + + Standard library are defined asinline(7.1.2)

2 An implementation can declare additional non-virtual member function signatures within a class:

— by adding arguments with default values to a member function signature;132)The same latitude does not

extend to the implementation of virtual or global functions, however

— by replacing a member function signature with default values by two or more member function tures with equivalent behavior;

signa-— by adding a member function signature for a member function name

3 A call to a member function signature described in the C + + Standard library behaves the same as if the

implementation declares no additional member function signatures.133)

[lib.reentrancy] 17.3.4.5 Reentrancy

1 Which of the functions in the C + + Standard Library are not reentrant subroutines is

implementation-defined

[lib.protection.within.classes] 17.3.4.6 Protection within classes

1 It is unspecified whether a function signature or class described in Clauses 18 through 27 is afriendof

another class in the C + + Standard Library

2 It is unspecified whether a member described in this clause as private is private, protected, or public It is

unspecified whether a member described as protected is protected or public A member described as public

131)A valid C + + program always calls the expected library global function An implementation may also define additional globalfunctions that would otherwise not be called by a valid C + + program.

132)Hence, taking the address of a member function has an unspecified type.

133)A valid C + + program always calls the expected library member function, or one with equivalent behavior An implementationmay also define additional member functions that would otherwise not be called by a valid C + + program.

Trang 36

17.3.4.7 Derived classes DRAFT: 28 April 1995 Library introduction 17– 21

[lib.derivation] 17.3.4.7 Derived classes

1 Certain classes defined in the C + + Standard Library are derived from other classes in the C + + Standard

2 In any case:

— A base class described asvirtualis always virtual;

— A base class described as non-virtualis never virtual;

— Unless explicitly stated otherwise, types with distinct names are distinct types.134)

[lib.res.on.exception.handling] 17.3.4.8 Restrictions on exception handling

1 Any of the functions defined in the C + + Standard library can report a failure by throwing an exception of the

type(s) described in their Throws: paragraph and/or their exception-specification (15.4).

2 Any of the functions defined in the C + + Standard library that do not have an exception-specification

pro-hibiting it, can report a failure to allocate storage by throwing an exception of typebad_alloc, or a classderived frombad_alloc(18.4.2.1)

134) An implicit exception to this rule are types described as synonyms for basic integral types, such assize_t (18.1) and

streamoff (27.4.1).

Trang 38

1 This clause describes the function signatures that are called implicitly, and the types of objects generated

implicitly, during the execution of some C + + programs It also describes the headers that declare thesefunction signatures and define any related types

2 The following subclauses describe common type definitions used throughout the library, characteristics of

the predefined types, functions supporting start and termination of a C + + program, support for dynamicmemory management, support for dynamic type identification, support for exception processing, and otherruntime support, as summarized in Table 24:

Table 24—Language support library summary

1 Common definitons

2 Header<cstddef>(Table 25):

Table 25—Header <cstddef> synopsis

3 The contents are the same as the Standard C library, with the following changes:

4 The macro NULL is an implementation-defined C + + null-pointer constant in this International Standard

(4.10).135)

135)Possible definitions include and , but not .

Trang 39

18– 2 Language support library DRAFT: 28 April 1995 18.1 Types

5 The macrooffsetofaccepts a restricted set of typearguments in this International Standard type

shall be a POD structure or a POD union (9)

C subclause 7.1.6

[lib.support.limits] 18.2 Implementation properties

1 Characteristics of implementation-dependent fundamental types (3.9.1)

[lib.limits] 18.2.1 Numeric limits

1 Thenumeric_limitscomponent provides a C + + program with information about various properties of

the implementation’s representation of the fundamental types

2 Specializations shall be provided for each fundamental type, both floating point and integer, including

bool The member is_specialized shall be true for all such specializations ofnumeric_limits

3 Non-scalar types, such ascomplex<T>(26.2.1), shall not have specializations

Header <limits> synopsis

class numeric_limits<signed char>;

class numeric_limits<unsigned char>;

class numeric_limits<wchar_t>;

class numeric_limits<short>;

class numeric_limits<int>;

class numeric_limits<long>;

class numeric_limits<unsigned short>;

class numeric_limits<unsigned int>;

class numeric_limits<unsigned long>;

Trang 40

18.2.1.1 DRAFT: 28 April 1995 Language support library 18– 3 Template class numeric_limits

static const int digits;

static const int digits10;

static const bool is_signed;

static const bool is_integer;

static const bool is_exact;

static const int radix;

static T epsilon();

static T round_error();

static const int min_exponent;

static const int min_exponent10;

static const int max_exponent;

static const int max_exponent10;

static const bool has_infinity;

static const bool has_quiet_NaN;

static const bool has_signaling_NaN;

static const bool has_denorm;

static T infinity();

static T quiet_NaN();

static T signaling_NaN();

static T denorm_min();

static const bool is_iec559;

static const bool is_bounded;

static const bool is_modulo;

static const bool traps;

static const bool tinyness_before;

static const float_round_style round_style;

};

}

1 The member is_specializedmakes it possible to distinguish between scalar types, which have

spe-cializations, and non-scalar types, which do not

2 The membersradix,epsilon(), andround_error()shall have meaningful values for all floating

point type specializations

3 For types withhas_denorm == false, the memberdenorm_min()shall return the same value as

the membermin()

4 The defaultnumeric_limits<T>template shall have all members, but with meaningless (0 orfalse)

values

[lib.numeric.limits.members] 18.2.1.2 numeric_limits members

static T min();

1 Minimum finite value.136)

2 For floating types with denormalization, returns the minimum positive normalized value,

denorm_min()

136)Equivalent to CHAR_ MIN, SHRT _ MIN, FLT _ MIN, DBL _ MIN, etc.

Ngày đăng: 09/08/2014, 12:22

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN