Главная » Просмотр файлов » B. Stroustrup - The C++ Programming Language

B. Stroustrup - The C++ Programming Language (794319), страница 43

Файл №794319 B. Stroustrup - The C++ Programming Language (B. Stroustrup - The C++ Programming Language) 43 страницаB. Stroustrup - The C++ Programming Language (794319) страница 432019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

That is, analias refers to the type for which it is an alias. For example:Pchar p1 = nullptr;char∗ p3 = p1;// p1 is a char*// finePeople who would like to have distinct types with identical semantics or identical representationshould look at enumerations (§8.4) and classes (Chapter 16).An older syntax using the keyword typedef and placing the name being declared where it wouldhave been in a declaration of a variable can equivalently be used in many contexts. For example:typedef int int32_t;typedef short int16_t;typedef void(∗PtoF)(int);// equivalent to ‘‘using int32_t = int;’’// equivalent to ‘‘using int16_t = short;’’// equivalent to ‘‘using PtoF = void(*)(int);’’Aliases are used when we want to insulate our code from details of the underlying machine.

Thename int32_t indicates that we want it to represent a 32-bit integer. Having written our code interms of int32_t, rather than ‘‘plain int,’’ we can port our code to a machine with sizeof(int)==2 byredefining the single occurrence of int32_t in our code to use a longer integer:using int32_t = long;The _t suffix is conventional for aliases (‘‘typedefs’’). The int16_t, int32_t, and other such aliasescan be found in <stdint> (§43.7). Note that naming a type after its representation rather than its purpose is not necessarily a good idea (§6.3.3).The using keyword can also be used to introduce a template alias (§23.6). For example:template<typename T>using Vector = std::vector<T, My_allocator<T>>;We cannot apply type specifiers, such as unsigned, to an alias.

For example:using Char = char;using Uchar = unsigned Char;using Uchar = unsigned char;// error// OK6.6 Advice[1][2][3][4][5]For the final word on language definition issues, see the ISO C++ standard; §6.1.Avoid unspecified and undefined behavior; §6.1.Isolate code that must depend on implementation-defined behavior; §6.1.Avoid unnecessary assumptions about the numeric value of characters; §6.2.3.2, §10.5.2.1.Remember that an integer starting with a 0 is octal; §6.2.4.1.Section 6.6[6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][22][23]Advice169Avoid ‘‘magic constants’’; §6.2.4.1.Avoid unnecessary assumptions about the size of integers; §6.2.8.Avoid unnecessary assumptions about the range and precision of floating-point types; §6.2.8.Prefer plain char over signed char and unsigned char; §6.2.3.1.Beware of conversions between signed and unsigned types; §6.2.3.1.Declare one name (only) per declaration; §6.3.2.Keep common and local names short, and keep uncommon and nonlocal names longer;§6.3.3.Avoid similar-looking names; §6.3.3.Name an object to reflect its meaning rather than its type; §6.3.3.Maintain a consistent naming style; §6.3.3.Avoid ALL_CAPS names; §6.3.3.Keep scopes small; §6.3.4.Don’t use the same name in both a scope and an enclosing scope; §6.3.4.Prefer the {}-initializer syntax for declarations with a named type; §6.3.5.Prefer the = syntax for the initialization in declarations using auto; §6.3.5.Avoid uninitialized variables; §6.3.5.1.Use an alias to define a meaningful name for a built-in type in cases in which the built-in typeused to represent a value might change; §6.5.Use an alias to define synonyms for types; use enumerations and classes to define new types;§6.5.This page intentionally left blank7Pointers, Arrays, and ReferencesThe sublime and the ridiculousare often so nearly related thatit is difficult to class them separately.– Thomas Paine••••••••IntroductionPointersvoid∗; nullptrArraysArray Initializers; String LiteralsPointers into ArraysNavigating Arrays; Multidimensional Arrays; Passing ArraysPointers and constPointers and OwnershipReferencesLvalue References; Rvalue References; References to References; Pointers and ReferencesAdvice7.1 IntroductionThis chapter deals with the basic language mechanisms for referring to memory.

Obviously, wecan refer to an object by name, but in C++ (most) objects ‘‘have identity.’’ That is, they reside at aspecific address in memory, and an object can be accessed if you know its address and its type. Thelanguage constructs for holding and using addresses are pointers and references.172Pointers, Arrays, and ReferencesChapter 77.2 PointersFor a type T, T∗ is the type ‘‘pointer to T.’’ That is, a variable of type T∗ can hold the address of anobject of type T.

For example:char c = 'a';char∗ p = &c;// p holds the address of c; & is the address-of operatoror graphically:p:&cc: 'a'The fundamental operation on a pointer is dereferencing, that is, referring to the object pointed toby the pointer. This operation is also called indirection. The dereferencing operator is (prefix)unary ∗. For example:char c = 'a';char∗ p = &c; // p holds the address of c; & is the address-of operatorchar c2 = ∗p; // c2 == ’a’; * is the dereference operatorThe object pointed to by p is c, and the value stored in c is 'a', so the value of ∗p assigned to c2 is 'a'.It is possible to perform some arithmetic operations on pointers to array elements (§7.4).The implementation of pointers is intended to map directly to the addressing mechanisms of themachine on which the program runs.

Most machines can address a byte. Those that can’t tend tohave hardware to extract bytes from words. On the other hand, few machines can directly addressan individual bit. Consequently, the smallest object that can be independently allocated andpointed to using a built-in pointer type is a char. Note that a bool occupies at least as much space asa char (§6.2.8). To store smaller values more compactly, you can use the bitwise logical operations(§11.1.1), bit-fields in structures (§8.2.7), or a bitset (§34.2.2).The ∗, meaning ‘‘pointer to,’’ is used as a suffix for a type name.

Unfortunately, pointers toarrays and pointers to functions need a more complicated notation:int∗ pi;char∗∗ ppc;int∗ ap[15];int (∗fp)(char∗);int∗ f(char∗);// pointer to int// pointer to pointer to char// array of 15 pointers to ints// pointer to function taking a char* argument; returns an int// function taking a char* argument; returns a pointer to intSee §6.3.1 for an explanation of the declaration syntax and §iso.A for the complete grammar.Pointers to functions can be useful; they are discussed in §12.5. Pointers to class members arepresented in §20.6.7.2.1 void∗In low-level code, we occasionally need to store or pass along an address of a memory locationwithout actually knowing what type of object is stored there.

A void∗ is used for that. You can readvoid∗ as ‘‘pointer to an object of unknown type.’’Section 7.2.1void∗173A pointer to any type of object can be assigned to a variable of type void∗, but a pointer to function (§12.5) or a pointer to member (§20.6) cannot. In addition, a void∗ can be assigned to anothervoid∗, void∗s can be compared for equality and inequality, and a void∗ can be explicitly converted toanother type. Other operations would be unsafe because the compiler cannot know what kind ofobject is really pointed to.

Consequently, other operations result in compile-time errors. To use avoid∗, we must explicitly convert it to a pointer to a specific type. For example:void f(int∗ pi){void∗ pv = pi; // ok: implicit conversion of int* to void*∗pv;// error: can’t dereference void*++pv;// error: can’t increment void* (the size of the object pointed to is unknown)int∗ pi2 = static_cast<int∗>(pv);// explicit conversion back to int*double∗ pd1 = pv;double∗ pd2 = pi;double∗ pd3 = static_cast<double∗>(pv);// error// error// unsafe (§11.5.2)}In general, it is not safe to use a pointer that has been converted (‘‘cast’’) to a type that differs fromthe type of the object pointed to.

For example, a machine may assume that every double is allocated on an 8-byte boundary. If so, strange behavior could arise if pi pointed to an int that wasn’tallocated that way. This form of explicit type conversion is inherently unsafe and ugly. Consequently, the notation used, static_cast (§11.5.2), was designed to be ugly and easy to find in code.The primary use for void∗ is for passing pointers to functions that are not allowed to makeassumptions about the type of the object and for returning untyped objects from functions. To usesuch an object, we must use explicit type conversion.Functions using void∗ pointers typically exist at the very lowest level of the system, where realhardware resources are manipulated.

For example:void∗ my_alloc(size_t n);// allocate n bytes from my special heapOccurrences of void∗s at higher levels of the system should be viewed with great suspicion becausethey are likely indicators of design errors. Where used for optimization, void∗ can be hidden behinda type-safe interface (§27.3.1).Pointers to functions (§12.5) and pointers to members (§20.6) cannot be assigned to void∗s.7.2.2 nullptrThe literal nullptr represents the null pointer, that is, a pointer that does not point to an object. Itcan be assigned to any pointer type, but not to other built-in types:int∗ pi = nullptr;double∗ pd = nullptr;int i = nullptr;// error: i is not a pointerThere is just one nullptr, which can be used for every pointer type, rather than a null pointer foreach pointer type.174Pointers, Arrays, and ReferencesChapter 7Before nullptr was introduced, zero (0) was used as a notation for the null pointer.

For example:int∗ x = 0; // x gets the value nullptrNo object is allocated with the address 0, and 0 (the all-zeros bit pattern) is the most common representation of nullptr. Zero (0) is an int. However, the standard conversions (§10.5.2.3) allow 0 to beused as a constant of pointer or pointer-to-member type.It has been popular to define a macro NULL to represent the null pointer. For example:int∗ p = NULL; // using the macro NULLHowever, there are differences in the definition of NULL in different implementations; for example,NULL might be 0 or 0L. In C, NULL is typically (void∗)0, which makes it illegal in C++ (§7.2.1):int∗ p = NULL; // error: can’t assign a void* to an int*Using nullptr makes code more readable than alternatives and avoids potential confusion when afunction is overloaded to accept either a pointer or an integer (§12.3.1).7.3 ArraysFor a type T, T[size] is the type ‘‘array of size elements of type T.’’ The elements are indexed from 0to size−1.

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

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

Список файлов книги

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