Главная » Просмотр файлов » Стандарт C++ 98

Стандарт C++ 98 (1119566), страница 26

Файл №1119566 Стандарт C++ 98 (Стандарт C++ 98) 26 страницаСтандарт C++ 98 (1119566) страница 262019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 26)

sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1; theresult 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.69) ] [Note: See 1.7 forthe definition of byte and 3.9 for the definition of object representation.

]2When applied to a reference or a reference type, the result is the size of the referenced type. When appliedto a class, the result is the number of bytes in an object of that class including any padding required forplacing 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 class subobject is the size of the base class type.70) When appliedto an array, the result is the total number of bytes in the array. This implies that the size of an array of nelements is n times the size of an element.3The sizeof operator can be applied to a pointer to a function, but shall not be applied directly to a function.4The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are notapplied to the operand of sizeof.5Types shall not be defined in a sizeof expression.6The result is a constant of type size_t.

[Note: size_t is defined in the standard header<cstddef>(18.1). ]__________________69) sizeof(bool) is not required to be 1.70) The actual size of a base class subobject may be less than the result of applying sizeof to the subobject, due to virtual baseclasses and less strict padding requirements on base class subobjects.77ISO/IEC 14882:1998(E)© ISO/IEC5.3.4 New5 Expressions5.3.4 New1[expr.new]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 abstractclass type or array thereof (1.8, 3.9, 10.4). [Note: because references are not objects, references cannot becreated by new-expressions.

] [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. ]new-expression:::opt new new-placementopt new-type-id new-initializeropt::opt new new-placementopt ( type-id ) new-initializeroptnew-placement:( expression-list )new-type-id:type-specifier-seq new-declaratoroptnew-declarator:ptr-operator new-declaratoroptdirect-new-declaratordirect-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 anentity is not necessarily restricted to the scope in which it is created. ] If the entity is a non-array object, thenew-expression returns a pointer to the object created. If it is an array, the new-expression returns a pointerto the initial element of the array.2The new-type-id in a new-expression is the longest possible sequence of new-declarators. [Note: this prevents ambiguities between declarator operators &, *, [], and their expression counterparts. ] [Example:new int * i;// syntax error: parsed as (new int*) i//not as (new int)*iThe * is the pointer declarator and not the multiplication operator. ]3[Note: parentheses in a new-type-id of a new-expression can have surprising effects.

[Example:new int(*[10])();// erroris ill-formed because the binding is(new int) (*[10])();// errorInstead, the explicitly parenthesized version of the new operator can be used to create objects of compoundtypes (3.9.2):new (int (*[10])());allocates an array of 10 pointers to functions (taking no argument and returning int). ] ]4The type-specifier-seq shall not contain class declarations, or enumeration declarations.5When the allocated object is an array (that is, the direct-new-declarator syntax is used or the new-type-id ortype-id denotes an array type), the new-expression yields a pointer to the initial element (if any) of thearray.

[Note: both new int and new int[10] have type int* and the type of new int[i][10] isint (*)[10]. ]78© ISO/IECISO/IEC 14882:1998(E)5 Expressions5.3.4 New6Every constant-expression in a direct-new-declarator shall be an integral constant expression (5.19) andevaluate to a strictly positive value. The expression in a direct-new-declarator shall have integral type(3.9.1) with a non-negative value. [Example: if n is a variable of type int, then new float[n][5] iswell-formed (because n is the expression of a direct-new-declarator), but new float[5][n] is illformed (because n is not a constant-expression).

If n is negative, the effect of new float[n][5] isundefined. ]7When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements. The pointer returned by the new-expression is non-null. [Note: If thelibrary allocation function is called, the pointer returned is distinct from the pointer to any other object. ]8A new-expression obtains storage for the object by calling an allocation function (3.7.3.1).

If the newexpression terminates 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 andthe 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 isoperator 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).

]9If the new-expression begins with a unary :: operator, the allocation function’s name is looked up in theglobal scope. Otherwise, if the allocated type is a class type T or array thereof, the allocation function’sname is looked up in the scope of T. If this lookup fails to find the name, or if the allocated type is not aclass type, the allocation function’s name is looked up in the global scope.10A new-expression passes the amount of space requested to the allocation function as the first argument oftype std::size_t.

That argument shall be no less than the size of the object being created; it may begreater than the size of the object being created only if the object is an array. For arrays of char andunsigned char, the difference between the result of the new-expression and the address returned by theallocation function shall be an integral multiple of the most stringent alignment requirement (3.9) of anyobject type whose size is no greater than the size of the array being created. [Note: Because allocationfunctions are assumed to return pointers to storage that is appropriately aligned for objects of any type, thisconstraint on array allocation overhead permits the common idiom of allocating character arrays into whichobjects of other types will later be placed.

]11The 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 theamount of space requested (the first argument) and the expressions in the new-placement part of the newexpression (the second and succeeding arguments).

The first of these arguments has type size_t and theremaining 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 thenew-expression will be offset by this amount from the value returned by operator new[]. This overhead may be applied in all array new-expressions, including those referencing the library functionoperator new[](std::size_t, void*) and other placement allocation functions. The amountof overhead may vary from one invocation of new to another.

]13[Note: unless an allocation function is declared with an empty exception-specification (15.4), throw(), itindicates failure to allocate storage by throwing a bad_alloc exception (clause 15, 18.4.2.1); it returns anon-null pointer otherwise. If the allocation function is declared with an empty exception-specification,79ISO/IEC 14882:1998(E)5.3.4 New© ISO/IEC5 Expressionsthrow(), it returns null to indicate failure to allocate storage and a non-null pointer otherwise. ] If theallocation 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 storagein which space for the object has been reserved.

The block of storage is assumed to be appropriatelyaligned and of the requested size. The address of the created object will not necessarily be the same as thatof the block if the object is an array. ]15A 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 defaultinitialized (8.5) If T is a const-qualified type, the underlying class type shall have a user-declareddefault constructor.— Otherwise, the object created has indeterminate value.

If T is a const-qualified type, or a (possiblycv-qualified) POD class type (or array thereof) containing (directly or indirectly) a member ofconst-qualified type, the program is ill-formed;— If the new-initializer is of the form (), default-initialization shall be performed (8.5);— If the new-initializer is of the form (expression-list) and T is a class type, the appropriate constructor iscalled, 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, orpointer-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.16If the new-expression creates an object or an array of objects of class type, access and ambiguity control aredone for the allocation function, the deallocation function (12.5), and the constructor (12.1).

Характеристики

Тип файла
PDF-файл
Размер
2,05 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов учебной работы

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6367
Авторов
на СтудИзбе
309
Средний доход
с одного платного файла
Обучение Подробнее