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

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

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

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

[ Example:#define N sizeof(T)char buf[N];T obj;std::memcpy(buf, &obj, N);std::memcpy(&obj, buf, N);//////////obj initialized to its original valuebetween these two calls to std::memcpy,obj might be modifiedat this point, each subobject of obj of scalar typeholds its original value— end example ]3For any trivially copyable type T, if two pointers to T point to distinct T objects obj1 and obj2, whereneither obj1 nor obj2 is a base-class subobject, if the underlying bytes (1.7) making up obj1 are copiedinto obj2,41 obj2 shall subsequently hold the same value as obj1.

[ Example:T* t1p;T* t2p;// provided that t2p points to an initialized object ...std::memcpy(t1p, t2p, sizeof(T));// at this point, every subobject of trivially copyable type in *t1p contains// the same value as the corresponding subobject in *t2p— end example ]4The object representation of an object of type T is the sequence of N unsigned char objects taken up bythe object of type T, where N equals sizeof(T).

The value representation of an object is the set of bits thathold the value of type T. For trivially copyable types, the value representation is a set of bits in the objectrepresentation that determines a value, which is one discrete element of an implementation-defined set ofvalues.425A class that has been declared but not defined, or an array of unknown size or of incomplete element type, isan incompletely-defined object type.43 Incompletely-defined object types and the void types are incompletetypes (3.9.1). Objects shall not be defined to have an incomplete type.6A class type (such as “class X”) might be incomplete at one point in a translation unit and complete lateron; the type “class X” is the same type at both points.

The declared type of an array object might bean array of incomplete class type and therefore incomplete; if the class type is completed later on in thetranslation unit, the array type becomes complete; the array type at those two points is the same type. Thedeclared type of an array object might be an array of unknown size and therefore be incomplete at one pointin a translation unit and complete later on; the array types at those two points (“array of unknown boundof T” and “array of N T”) are different types. The type of a pointer to array of unknown size, or of a typedefined by a typedef declaration to be an array of unknown size, cannot be completed. [ Example:class X;extern X* xp;extern int arr[];typedef int UNKA[];UNKA* arrp;40)41)42)43)//////////X is an incomplete typexp is a pointer to an incomplete typethe type of arr is incompleteUNKA is an incomplete typearrp is a pointer to an incomplete typeBy using, for example, the library functions (17.6.1.2) std::memcpy or std::memmove.By using, for example, the library functions (17.6.1.2) std::memcpy or std::memmove.The intent is that the memory model of C++ is compatible with that of ISO/IEC 9899 Programming Language C.The size and layout of an instance of an incompletely-defined object type is unknown.§ 3.9© ISO/IEC 2011 – All rights reserved73ISO/IEC 14882:2011(E)UNKA** arrpp;void foo() {xp++;arrp++;arrpp++;}// ill-formed: X is incomplete// ill-formed: incomplete type// OK: sizeof UNKA* is knownstruct X { int i; };int arr[10];// now X is a complete type// now the type of arr is completeX x;void bar() {xp = &x;arrp = &arr;xp++;arrp++;}////////OK; type is “pointer to X”ill-formed: different typesOK: X is completeill-formed: UNKA can’t be completed— end example ]7[ Note: The rules for declarations and expressions describe in which contexts incomplete types are prohibited.— end note ]8An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not avoid type.9Arithmetic types (3.9.1), enumeration types, pointer types, pointer to member types (3.9.2), std::nullptr_t, and cv-qualified versions of these types (3.9.3) are collectively called scalar types.

Scalar types, PODclasses (Clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively calledPOD types. Scalar types, trivially copyable class types (Clause 9), arrays of such types, and cv-qualifiedversions of these types (3.9.3) are collectively called trivially copyable types. Scalar types, trivial class types(Clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively called trivialtypes.

Scalar types, standard-layout class types (Clause 9), arrays of such types and cv-qualified versions ofthese types (3.9.3) are collectively called standard-layout types.10A type is a literal type if it is:— a scalar type; or— a reference type; or— a class type (Clause 9) that has all of the following properties:— it has a trivial destructor,— every constructor call and full-expression in the brace-or-equal-initializers for non-static datamembers (if any) is a constant expression (5.19),— it is an aggregate type (8.5.1) or has at least one constexpr constructor or constructor templatethat is not a copy or move constructor, and— it has all non-static data members and base classes of literal types; or— an array of literal type.11If two types T1 and T2 are the same type, then T1 and T2 are layout-compatible types.

[ Note: Layoutcompatible enumerations are described in 7.2. Layout-compatible standard-layout structs and standardlayout unions are described in 9.2. — end note ]§ 3.974© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)3.9.1Fundamental types[basic.fundamental]1Objects declared as characters (char) shall be large enough to store any member of the implementation’s basic character set.

If a character from this set is stored in a character object, the integral value of that characterobject is equal to the value of the single character literal form of that character. It is implementation-definedwhether a char object can hold negative values. Characters can be explicitly declared unsigned or signed.Plain char, signed char, and unsigned char are three distinct types. A char, a signed char, and anunsigned char occupy the same amount of storage and have the same alignment requirements (3.11); thatis, they have the same object representation.

For character types, all bits of the object representation participate in the value representation. For unsigned character types, all possible bit patterns of the valuerepresentation represent numbers. These requirements do not hold for other types. In any particular implementation, a plain char object can take on either the same values as a signed char or an unsigned char;which one is implementation-defined.2There are five standard signed integer types : “signed char”, “short int”, “int”, “long int”, and “longlong int”. In this list, each type provides at least as much storage as those preceding it in the list.There may also be implementation-defined extended signed integer types.

The standard and extended signedinteger types are collectively called signed integer types. Plain ints have the natural size suggested by thearchitecture of the execution environment44 ; the other signed integer types are provided to meet specialneeds.3For each of the standard signed integer types, there exists a corresponding (but different) standard unsigned integer type: “unsigned char”, “unsigned short int”, “unsigned int”, “unsigned long int”,and “unsigned long long int”, each of which occupies the same amount of storage and has the samealignment requirements (3.11) as the corresponding signed integer type45 ; that is, each signed integer typehas the same object representation as its corresponding unsigned integer type.

Likewise, for each of theextended signed integer types there exists a corresponding extended unsigned integer type with the sameamount of storage and alignment requirements. The standard and extended unsigned integer types arecollectively called unsigned integer types. The range of non-negative values of a signed integer type is asubrange of the corresponding unsigned integer type, and the value representation of each correspondingsigned/unsigned type shall be the same. The standard signed integer types and standard unsigned integertypes are collectively called the standard integer types, and the extended signed integer types and extendedunsigned integer types are collectively called the extended integer types.4Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the numberof bits in the value representation of that particular size of integer.465Type wchar_t is a distinct type whose values can represent distinct codes for all members of the largestextended character set specified among the supported locales (22.3.1).

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

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

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

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