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

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

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

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

For example:float v[3];char∗ a[32];// an array of three floats: v[0], v[1], v[2]// an array of 32 pointers to char: a[0] .. a[31]You can access an array using the subscript operator, [], or through a pointer (using operatoroperator []; §7.4). For example:∗orvoid f(){int aa[10];aa[6] = 9;// assign to aa’s 7th elementint x = aa[99]; // undefined behavior}Access out of the range of an array is undefined and usually disastrous. In particular, run-timerange checking is neither guaranteed nor common.The number of elements of the array, the array bound, must be a constant expression (§10.4). Ifyou need variable bounds, use a vector (§4.4.1, §31.4). For example:void f(int n){int v1[n];vector<int> v2(n);}// error: array size not a constant expression// OK: vector with n int elementsMultidimensional arrays are represented as arrays of arrays (§7.4.2).An array is C++’s fundamental way of representing a sequence of objects in memory.

If whatyou want is a simple fixed-length sequence of objects of a given type in memory, an array is theideal solution. For every other need, an array has serious problems.Section 7.3Arrays175An array can be allocated statically, on the stack, and on the free store (§6.4.2). For example:int a1[10];// 10 ints in static storagevoid f(){int a2 [20];int∗p = new int[40];// ...}// 20 ints on the stack// 40 ints on the free storeThe C++ built-in array is an inherently low-level facility that should primarily be used inside theimplementation of higher-level, better-behaved, data structures, such as the standard-library vectoror array.

There is no array assignment, and the name of an array implicitly converts to a pointer toits first element at the slightest provocation (§7.4). In particular, avoid arrays in interfaces (e.g., asfunction arguments; §7.4.3, §12.2.2) because the implicit conversion to pointer is the root cause ofmany common errors in C code and C-style C++ code. If you allocate an array on the free store, besure to delete[] its pointer once only and only after its last use (§11.2.2). That’s most easily andmost reliably done by having the lifetime of the free-store array controlled by a resource handle(e.g., string (§19.3, §36.3), vector (§13.6, §34.2), or unique_ptr (§34.3.1)). If you allocate an arraystatically or on the stack, be sure never to delete[] it.

Obviously, C programmers cannot followthese pieces of advice because C lacks the ability to encapsulate arrays, but that doesn’t make theadvice bad in the context of C++.One of the most widely used kinds of arrays is a zero-terminated array of char. That’s the wayC stores strings, so a zero-terminated array of char is often called a C-style string. C++ string literals follow that convention (§7.3.2), and some standard-library functions (e.g., strcpy() and strcmp();§43.4) rely on it. Often, a char∗ or a const char∗ is assumed to point to a zero-terminated sequenceof characters.7.3.1 Array InitializersAn array can be initialized by a list of values. For example:int v1[] = { 1, 2, 3, 4 };char v2[] = { 'a', 'b', 'c', 0 };When an array is declared without a specific size, but with an initializer list, the size is calculatedby counting the elements of the initializer list.

Consequently, v1 and v2 are of type int[4] andchar[4], respectively. If a size is explicitly specified, it is an error to give surplus elements in an initializer list. For example:char v3[2] = { 'a', 'b', 0 };char v4[3] = { 'a', 'b', 0 };// error : too many initializers// OKIf the initializer supplies too few elements for an array, 0 is used for the rest. For example:int v5[8] = { 1, 2, 3, 4 };is equivalent toint v5[] = { 1, 2, 3, 4 , 0, 0, 0, 0 };176Pointers, Arrays, and ReferencesChapter 7There is no built-in copy operation for arrays. You cannot initialize one array with another (noteven of exactly the same type), and there is no array assignment:int v6[8] = v5; // error: can’t copy an array (cannot assign an int* to an array)v6 = v5;// error : no array assignmentSimilarly, you can’t pass arrays by value.

See also §7.4.When you need assignment to a collection of objects, use a vector (§4.4.1, §13.6, §34.2), anarray (§8.2.4), or a valarray (§40.5) instead.An array of characters can be conveniently initialized by a string literal (§7.3.2).7.3.2 String LiteralsA string literal is a character sequence enclosed within double quotes:"this is a string"A string literal contains one more character than it appears to have; it is terminated by the null character, '\0', with the value 0. For example:sizeof("Bohr")==5The type of a string literal is ‘‘array of the appropriate number of const characters,’’ so "Bohr" is oftype const char[5].In C and in older C++ code, you could assign a string literal to a non-const char∗:void f(){char∗ p = "Plato";p[4] = 'e';}// error, but accepted in pre-C++11-standard code// error: assignment to constIt would obviously be unsafe to accept that assignment.

It was (and is) a source of subtle errors, soplease don’t grumble too much if some old code fails to compile for this reason. Having string literals immutable is not only obvious but also allows implementations to do significant optimizationsin the way string literals are stored and accessed.If we want a string that we are guaranteed to be able to modify, we must place the characters ina non-const array:void f(){char p[] = "Zeno";p[0] = 'R';}// p is an array of 5 char// OKA string literal is statically allocated so that it is safe to return one from a function. For example:const char∗ error_message(int i){// ...return "range error";}Section 7.3.2String Literals177The memory holding "range error" will not go away after a call of error_message().Whether two identical string literals are allocated as one array or as two is implementationdefined (§6.1).

For example:const char∗ p = "Heraclitus";const char∗ q = "Heraclitus";void g(){if (p == q) cout << "one!\n";// ...}// the result is implementation-definedNote that == compares addresses (pointer values) when applied to pointers, and not the valuespointed to.The empty string is written as a pair of adjacent double quotes, "", and has the type constchar[1]. The one character of the empty string is the terminating '\0'.The backslash convention for representing nongraphic characters (§6.2.3.2) can also be usedwithin a string.

This makes it possible to represent the double quote (") and the escape characterbackslash (\) within a string. The most common such character by far is the newline character, '\n'.For example:cout<<"beep at end of message\a\n";The escape character, '\a', is the ASCII character BEL (also known as alert), which causes a soundto be emitted.It is not possible to have a ‘‘real’’ newline in a (nonraw) string literal:"this is not a stringbut a syntax error"Long strings can be broken by whitespace to make the program text neater. For example:char alpha[] = "abcdefghijklmnopqrstuvwxyz""ABCDEFGHIJKLMNOPQRSTUVWXYZ";The compiler will concatenate adjacent strings, so alpha could equivalently have been initialized bythe single string"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";It is possible to have the null character in a string, but most programs will not suspect that there arecharacters after it.

For example, the string "Jens\000Munk" will be treated as "Jens" by standardlibrary functions such as strcpy() and strlen(); see §43.4.7.3.2.1 Raw Character StringsTo represent a backslash (\) or a double quote (") in a string literal, we have to precede it with abackslash. That’s logical and in most cases quite simple. However, if we need a lot of backslashesand a lot of quotes in string literals, this simple technique becomes unmanageable. In particular, inregular expressions a backslash is used both as an escape character and to introduce characters178Pointers, Arrays, and ReferencesChapter 7representing character classes (§37.1.1).

This is a convention shared by many programming languages, so we can’t just change it. Therefore, when you write regular expressions for use with thestandard regex library (Chapter 37), the fact that a backslash is an escape character becomes anotable source of errors. Consider how to write the pattern representing two words separated by abackslash (\):string s = "\\w\\\\w";// I hope I got that rightTo prevent the frustration and errors caused by this clash of conventions, C++ provides raw stringliterals. A raw string literal is a string literal where a backslash is just a backslash (and a doublequote is just a double quote) so that our example becomes:string s = R"(\w\\w)";// I’m pretty sure I got that rightRaw string literals use the R"(ccc)" notation for a sequence of characters ccc. The initial R is thereto distinguish raw string literals from ordinary string literals.

The parentheses are there to allow(‘‘unescaped’’) double quotes. For example:R"("quoted string")"// the string is "quoted string"So, how do we get the character sequence )" into a raw string literal? Fortunately, that’s a rareproblem, but "( and )" is only the default delimiter pair.

We can add delimiters before the ( and afterthe ) in "(...)". For example:R"∗∗∗("quoted string containing the usual terminator ("))")∗∗∗"// "quoted string containing the usual terminator ("))"The character sequence after the ) must be identical to the sequence before the (. This way we cancope with (almost) arbitrarily complicated patterns.Unless you work with regular expressions, raw string literals are probably just a curiosity (andone more thing to learn), but regular expressions are useful and widely used.

Consider a real-worldexample:"('(?:[ˆ\\\\']|\\\\.)∗'|\"(?:[ˆ\\\\\"]|\\\\.)∗\")|"// Are the five backslashes correct or not?With examples like that, even experts easily become confused, and raw string literals provide a significant service.In contrast to nonraw string literals, a raw string literal can contain a newline. For example:string counts {R"(122333)"};is equivalent tostring x {"1\n22\n333"};7.3.2.2 Larger Character SetsA string with the prefix L, such as L"angst", is a string of wide characters (§6.2.3). Its type is constwchar_t[]. Similarly, a string with the prefix LR, such as LR"(angst)", is a raw string (§7.3.2.1) ofwide characters of type const wchar_t[].

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

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

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

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