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

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

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

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

Here is a small example borrowed from an implementation of ostream:enum ios_base::iostate {goodbit=0, eofbit=1, failbit=2, badbit=4};The implementation of a stream can set and test its state like this:state = goodbit;// ...if (state&(badbit|failbit)) // stream not goodThe extra parentheses are necessary because & has higher precedence than | (§10.3).A function that reaches the end-of-input might report it like this:state |= eofbit;The |= operator is used to add to the state. A simple assignment, state=eofbit, would have clearedall other bits.These stream state flags are observable from outside the stream implementation. For example,we could see how the states of two streams differ like this:int old = cin.rdstate();// ... use cin ...if (cin.rdstate()ˆold) {// ...}// rdstate() returns the state// has anything changed?Computing differences of stream states is not common.

For other similar types, computing differences is essential. For example, consider comparing a bit vector that represents the set of interruptsbeing handled with another that represents the set of interrupts waiting to be handled.Section 11.1.2Bitwise Logical Operators275Please note that this bit fiddling is taken from the implementation of iostreams rather than fromthe user interface. Convenient bit manipulation can be very important, but for reliability, maintainability, portability, etc., it should be kept at low levels of a system.

For more general notions of aset, see the standard-library set (§31.4.3) and bitset (§34.2.2).Bitwise logical operations can be used to extract bit-fields from a word. For example, one couldextract the middle 16 bits of a 32-bit int like this:constexpr unsigned short middle(int a){static_assert(sizeof(int)==4,"unexpected int size");static_assert(sizeof(short)==2,"unexpected short size");return (a>>8)&0xFFFF;}int x = 0xFF00FF00; // assume sizeof(int)==4short y = middle(x); // y = 0x00FFUsing fields (§8.2.7) is a convenient shorthand for such shifting and masking.Do not confuse the bitwise logical operators with the logical operators: &&, ||, and !.

The latterreturn true or false, and they are primarily useful for writing the test in an if-, while-, or for-statement(§9.4, §9.5). For example, !0 (not zero) is the value true, which converts to 1, whereas ˜0 (complement of zero) is the bit pattern all-ones, which in two’s complement representation is the value −1.11.1.3 Conditional ExpressionsSome if-statements can conveniently be replaced by conditional-expressions. For example:if (a <= b)max = b;elsemax = a;This is more directly expressed like this:max = (a<=b) ? b : a;The parentheses around the condition are not necessary, but I find the code easier to read when theyare used.Conditional expressions are important in that they can be used in constant expressions (§10.4).A pair of expressions e1 and e2 can be used as alternatives in a conditional expression, c?e1:e2,if they are of the same type or if there is a common type T, to which they can both be implicitlyconverted.

For arithmetic types, the usual arithmetic conversions (§10.5.3) are used to find thatcommon type. For other types, either e1 must be implicitly convertible to e2’s type or vice versa.In addition, one branch may be a throw-expression (§13.5.1). For example:void fct(int∗ p){int i = (p) ? ∗p : std::runtime_error{"unexpected nullptr};// ...}276Select OperationsChapter 1111.1.4 Increment and DecrementThe ++ operator is used to express incrementing directly, rather than expressing it indirectly using acombination of an addition and an assignment.

Provided lvalue has no side effects, ++lvalue meanslvalue+=1, which again means lvalue=lvalue+1. The expression denoting the object to be incremented is evaluated once (only). Decrementing is similarly expressed by the −− operator.The operators ++ and −− can be used as both prefix and postfix operators. The value of ++x isthe new (that is, incremented) value of x. For example, y=++x is equivalent to y=(x=x+1).

The valueof x++, however, is the old value of x. For example, y=x++ is equivalent to y=(t=x,x=x+1,t), where t isa variable of the same type as x.Like adding an int to a pointer, or subtracting it, ++ and −− on a pointer operate in terms of elements of the array into which the pointer points; p++ makes p point to the next element (§7.4.1).The ++ and −− operators are particularly useful for incrementing and decrementing variables inloops. For example, one can copy a zero-terminated C-style string like this:void cpy(char∗ p, const char∗ q){while (∗p++ = ∗q++) ;}Like C, C++ is both loved and hated for enabling such terse, expression-oriented coding.

Consider:while (∗p++ = ∗q++) ;This is more than a little obscure to non-C programmers, but because the style of coding is notuncommon, it is worth examining more closely. Consider first a more traditional way of copyingan array of characters:int length = strlen(q);for (int i = 0; i<=length; i++)p[i] = q[i];This is wasteful. The length of a zero-terminated string is found by reading the string looking forthe terminating zero. Thus, we read the string twice: once to find its length and once to copy it. Sowe try this instead:int i;for (i = 0; q[i]!=0 ; i++)p[i] = q[i];p[i] = 0;// terminating zeroThe variable i used for indexing can be eliminated because p and q are pointers:while (∗q != 0) {∗p = ∗q;p++;// point to next characterq++;// point to next character}∗p = 0;// terminating zeroBecause the post-increment operation allows us first to use the value and then to increment it, wecan rewrite the loop like this:Section 11.1.4Increment and Decrement277while (∗q != 0) {∗p++ = ∗q++;}∗p = 0; // terminating zeroThe value of ∗p++ = ∗q++ is ∗q.

We can therefore rewrite the example like this:while ((∗p++ = ∗q++) != 0) { }In this case, we don’t notice that ∗q is zero until we already have copied it into ∗p and incrementedp. Consequently, we can eliminate the final assignment of the terminating zero. Finally, we canreduce the example further by observing that we don’t need the empty block and that the !=0 isredundant because the result of an integral condition is always compared to zero anyway. Thus, weget the version we set out to discover:while (∗p++ = ∗q++) ;Is this version less readable than the previous versions? Not to an experienced C or C++ programmer.

Is this version more efficient in time or space than the previous versions? Except for the firstversion that called strlen(), not really; the performance will be equivalent and often identical codewill be generated.The most efficient way of copying a zero-terminated character string is typically the standard Cstyle string copy function:char∗ strcpy(char∗, const char∗);// from <string.h>For more general copying, the standard copy algorithm (§4.5, §32.5) can be used. Whenever possible, use standard-library facilities in preference to fiddling with pointers and bytes.

Standardlibrary functions may be inlined (§12.1.3) or even implemented using specialized machine instructions. Therefore, you should measure carefully before believing that some piece of handcraftedcode outperforms library functions. Even if it does, the advantage may not exist on some otherhandware+compiler combination, and your alternative may give a maintainer a headache.11.2 Free StoreA named object has its lifetime determined by its scope (§6.3.4).

However, it is often useful to create an object that exists independently of the scope in which it was created. For example, it is common to create objects that can be used after returning from the function in which they were created.The operator new creates such objects, and the operator delete can be used to destroy them. Objectsallocated by new are said to be ‘‘on the free store’’ (also, ‘‘on the heap’’ or ‘‘in dynamic memory’’).Consider how we might write a compiler in the style used for the desk calculator (§10.2).

Thesyntax analysis functions might build a tree of the expressions for use by the code generator:struct Enode {Token_value oper;Enode∗ left;Enode∗ right;// ...};278Select OperationsChapter 11Enode∗ expr(bool get){Enode∗ left = term(get);for (;;) {switch (ts.current().kind) {case Kind::plus:case Kind::minus:left = new Enode {ts.current().kind,left,term(true)};break;default:return left;// return node}}}In cases Kind::plus and Kind::minus, a new Enode is created on the free store and initialized by thevalue {ts.current().kind,left,term(true)}. The resulting pointer is assigned to left and eventuallyreturned from expr().I used the {}-list notation for specifying arguments. Alternatively, I could have used the oldstyle ()-list notation to specify an initializer. However, trying the = notation for initializing an objectcreated using new results in an error:int∗ p = new int = 7; // errorIf a type has a default constructor, we can leave out the initializer, but built-in types are by defaultuninitialized.

For example:auto pc = new complex<double>;auto pi = new int;// the complex is initialized to {0,0}// the int is uninitializedThis can be confusing. To be sure to get default initialization, use {}. For example:auto pc = new complex<double>{}; // the complex is initialized to {0,0}auto pi = new int{};// the int is initialized to 0A code generator could use the Enodes created by expr() and delete them:void generate(Enode∗ n){switch (n−>oper) {case Kind::plus:// use ndelete n; // delete an Enode from the free store}}An object created by new exists until it is explicitly destroyed by delete. Then, the space it occupied can be reused by new.

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

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

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

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