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

Стандарт C++ 11 (1119564), страница 49

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

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

— end note ]3A pointer or reference to a cv-qualified type need not actually point or refer to a cv-qualified object, but itis treated as if it does; a const-qualified access path cannot be used to modify an object even if the objectreferenced is a non-const object and can be modified through some other access path. [ Note: Cv-qualifiersare supported by the type system so that they cannot be subverted without casting (5.2.11). — end note ]4Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a constobject during its lifetime (3.8) results in undefined behavior.

[ Example:const int ci = 3;ci = 4;// cv-qualified (initialized as required)// ill-formed: attempt to modify constint i = 2;const int* cip;cip = &i;*cip = 4;////////int* ip;ip = const_cast<int*>(cip);*ip = 4;// cast needed to convert const int* to int*// defined: *ip points to i, a non-const objectnot cv-qualifiedpointer to const intOK: cv-qualified access path to unqualifiedill-formed: attempt to modify through ptr to constconst int* ciq = new const int (3);int* iq = const_cast<int*>(ciq);*iq = 4;5// initialized as required// cast required// undefined: modifies a const objectFor another examplestruct X {mutable int i;int j;};struct Y {X x;Y();};92) There is no special provision for a decl-specifier-seq that lacks a type-specifier or that has a type-specifier that only specifiescv-qualifiers.

The “implicit int” rule of C is no longer supported.§ 7.1.6.1152© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)const Y y;y.x.i++;y.x.j++;Y* p = const_cast<Y*>(&y);p->x.i = 99;p->x.j = 99;//////////well-formed: mutable member can be modifiedill-formed: const-qualified member modifiedcast away const-ness of ywell-formed: mutable member can be modifiedundefined: modifies a const member— end example ]6If an attempt is made to refer to an object defined with a volatile-qualified type through the use of a glvaluewith a non-volatile-qualified type, the program behavior is undefined.7[ Note: volatile is a hint to the implementation to avoid aggressive optimization involving the objectbecause the value of the object might be changed by means undetectable by an implementation.

See 1.9 fordetailed semantics. In general, the semantics of volatile are intended to be the same in C++ as they arein C. — end note ]7.1.6.21Simple type specifiers[dcl.type.simple]The simple type specifiers aresimple-type-specifier:nested-name-specifieropt type-namenested-name-specifier template simple-template-idcharchar16_tchar32_twchar_tboolshortintlongsignedunsignedfloatdoublevoidautodecltype-specifiertype-name:class-nameenum-nametypedef-namesimple-template-iddecltype-specifier:decltype ( expression )2The auto specifier is a placeholder for a type to be deduced (7.1.6.4). The other simple-type-specifiers specifyeither a previously-declared user-defined type or one of the fundamental types (3.9.1).

Table 10 summarizesthe valid combinations of simple-type-specifiers and the types they specify.3When multiple simple-type-specifiers are allowed, they can be freely intermixed with other decl-specifiers inany order. [ Note: It is implementation-defined whether objects of char type and certain bit-fields (9.6) arerepresented as signed or unsigned quantities. The signed specifier forces char objects and bit-fields to besigned; it is redundant in other contexts. — end note ]§ 7.1.6.2© ISO/IEC 2011 – All rights reserved153ISO/IEC 14882:2011(E)Table 10 — simple-type-specifiers and the types they specifySpecifier(s)type-namesimple-template-idcharunsigned charsigned charchar16_tchar32_tboolunsignedunsigned intsignedsigned intintunsigned short intunsigned shortunsigned long intunsigned longunsigned long long intunsigned long longsigned long intsigned longsigned long long intsigned long longlong long intlong longlong intlongsigned short intsigned shortshort intshortwchar_tfloatdoublelong doublevoidautodecltype(expression)Typethe type namedthe type as defined in 14.2“char”“unsigned char”“signed char”“char16_t”“char32_t”“bool”“unsigned int”“unsigned int”“int”“int”“int”“unsigned short int”“unsigned short int”“unsigned long int”“unsigned long int”“unsigned long long int”“unsigned long long int”“long int”“long int”“long long int”“long long int”“long long int”“long long int”“long int”“long int”“short int”“short int”“short int”“short int”“wchar_t”“float”“double”“long double”“void”placeholder for a type to be deducedthe type as defined below§ 7.1.6.2154© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)4The type denoted by decltype(e) is defined as follows:— if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e)is the type of the entity named by e.

If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed;— otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;— otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;— otherwise, decltype(e) is the type of e.The operand of the decltype specifier is an unevaluated operand (Clause 5).[ Example:const int&& foo();int i;struct A { double x; };const A* a = new A();decltype(foo()) x1 = i;decltype(i) x2;decltype(a->x) x3;decltype((a->x)) x4 = x3;////////typetypetypetypeisisisisconst int&&intdoubleconst double&— end example ]5[ Note: in the case where the operand of a decltype-specifier is a function call and the return type of thefunction is a class type, a special rule (5.2.2) ensures that the return type is not required to be complete (asit would be if the call appeared in a sub-expression or outside of a decltype-specifier).

In this context, thecommon purpose of writing the expression is merely to refer to its type. In that sense, a decltype-specifieris analogous to a use of a typedef-name, so the usual reasons for requiring a complete type do not apply. Inparticular, it is not necessary to allocate storage for a temporary object or to enforce the semantic constraintsassociated with invoking the type’s destructor. [ Example:template<class T> struct A { ~A() = delete; };template<class T> auto h()-> A<T>;template<class T> auto i(T)// identity-> T;template<class T> auto f(T)// #1-> decltype(i(h<T>()));// forces completion of A<T> and implicitly uses// A<T>::˜A() for the temporary introduced by the// use of h(). (A temporary is not introduced// as a result of the use of i().)template<class T> auto f(T)// #2-> void;auto g() -> void {f(42);// OK: calls #2.

(#1 is not a viable candidate: type// deduction fails (14.8.2) because A<int>::~A()// is implicitly used in its decltype-specifier)}template<class T> auto q(T)-> decltype((h<T>()));// does not force completion of A<T>; A<T>::˜A() is// not implicitly used within the context of this decltype-specifiervoid r() {q(42);// Error: deduction against q succeeds, so overload resolution// selects the specialization “q(T) -> decltype((h<T>())) [with T=int]”.§ 7.1.6.2© ISO/IEC 2011 – All rights reserved155ISO/IEC 14882:2011(E)// The return type is A<int>, so a temporary is introduced and its// destructor is used, so the program is ill-formed.}— end example ] — end note ]7.1.6.3Elaborated type specifiers[dcl.type.elab]elaborated-type-specifier:class-key attribute-specifier-seqopt nested-name-specifieropt identifierclass-key nested-name-specifieropt templateopt simple-template-idenum nested-name-specifieropt identifier1An attribute-specifier-seq shall not appear in an elaborated-type-specifier unless the latter is the sole constituent of a declaration.

If an elaborated-type-specifier is the sole constituent of a declaration, the declarationis ill-formed unless it is an explicit specialization (14.7.3), an explicit instantiation (14.7.2) or it has one ofthe following forms:class-key attribute-specifier-seqopt identifier ;friend class-key ::opt identifier ;friend class-key ::opt simple-template-id ;friend class-key nested-name-specifier identifier ;friend class-key nested-name-specifier templateopt simple-template-id ;In the first case, the attribute-specifier-seq, if any, appertains to the class being declared; the attributes inthe attribute-specifier-seq are thereafter considered attributes of the class whenever it is named.23.4.4 describes how name lookup proceeds for the identifier in an elaborated-type-specifier.

If the identifierresolves to a class-name or enum-name, the elaborated-type-specifier introduces it into the declaration thesame way a simple-type-specifier introduces its type-name. If the identifier resolves to a typedef-name orthe simple-template-id resolves to an alias template specialization, the elaborated-type-specifier is ill-formed.[ Note: This implies that, within a class template with a template type-parameter T, the declarationfriend class T;is ill-formed.

However, the similar declaration friend T; is allowed (11.3). — end note ]3The class-key or enum keyword present in the elaborated-type-specifier shall agree in kind with the declaration to which the name in the elaborated-type-specifier refers. This rule also applies to the form ofelaborated-type-specifier that declares a class-name or friend class since it can be construed as referring tothe definition of the class. Thus, in any elaborated-type-specifier, the enum keyword shall be used to refer toan enumeration (7.2), the union class-key shall be used to refer to a union (Clause 9), and either the classor struct class-key shall be used to refer to a class (Clause 9) declared using the class or struct class-key.[ Example:enum class E { a, b };enum E x = E::a;// OK— end example ]7.1.6.4auto specifier[dcl.spec.auto]1The auto type-specifier signifies that the type of a variable being declared shall be deduced from its initializeror that a function declarator shall include a trailing-return-type.2The auto type-specifier may appear with a function declarator with a trailing-return-type (8.3.5) in anycontext where such a declarator is valid.§ 7.1.6.4156© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)3Otherwise, the type of the variable is deduced from its initializer.

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

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

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

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