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

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

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

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

There is no const∗ declarator operator, so a const appearing before the ∗ is taken to be part of the base type. For example:char ∗const cp;char const∗ pc;const char∗ pc2;// const pointer to char// pointer to const char// pointer to const charSome people find it helpful to read such declarations right-to-left, for example, ‘‘cp is a constpointer to a char’’ and ‘‘pc2 is a pointer to a char const.’’An object that is a constant when accessed through one pointer may be variable when accessedin other ways. This is particularly useful for function arguments.

By declaring a pointer argumentconst, the function is prohibited from modifying the object pointed to. For example:const char∗ strchr(const char∗ p, char c);char∗ strchr(char∗ p, char c);// find first occurrence of c in p// find first occurrence of c in pThe first version is used for strings where the elements mustn’t be modified and returns a pointer toconst that does not allow modification. The second version is used for mutable strings.You can assign the address of a non-const variable to a pointer to constant because no harm cancome from that. However, the address of a constant cannot be assigned to an unrestricted pointerbecause this would allow the object’s value to be changed.

For example:188Pointers, Arrays, and Referencesvoid f4(){int a = 1;const int c = 2;const int∗ p1 = &c;const int∗ p2 = &a;int∗ p3 = &c;∗p3 = 7;}Chapter 7// OK// OK// error: initialization of int* with const int*// try to change the value of cIt is possible, but typically unwise, to explicitly remove the restrictions on a pointer toexplicit type conversion (§16.2.9, §11.5).constby7.6 Pointers and OwnershipA resource is something that has to be acquired and later released (§5.2). Memory acquired by newand released by delete (§11.2) and files opened by fopen() and closed by fclose() (§43.2) are examples of resources where the most direct handle to the resource is a pointer. This can be most confusing because a pointer is easily passed around in a program, and there is nothing in the type system that distinguishes a pointer that owns a resource from one that does not.

Consider:void confused(int∗ p){// delete p?}int global {7};void f(){X∗ pn = new int{7};int i {7};int q = &i;confused(pn);confused(q);confused(&global);}If confused() deletes p the program will seriously misbehave for the second two calls because wemay not delete objects not allocated by new (§11.2). If confused() does not delete p the programleaks (§11.2.1).

In this case, obviously f() must manage the lifetime of the object it creates on thefree store, but in general keeping track of what needs to be deleted in a large program requires asimple and consistent strategy.It is usually a good idea to immediately place a pointer that represents ownership in a resourcehandle class, such as vector, string, and unique_ptr. That way, we can assume that every pointer thatis not within a resource handle is not an owner and must not be deleted.

Chapter 13 discussesresource management in greater detail.Section 7.7References1897.7 ReferencesA pointer allows us to pass potentially large amounts of data around at low cost: instead of copyingthe data we simply pass its address as a pointer value. The type of the pointer determines what canbe done to the data through the pointer. Using a pointer differs from using the name of an object ina few ways:• We use a different syntax, for example, ∗p instead of obj and p−>m rather than obj.m.• We can make a pointer point to different objects at different times.• We must be more careful when using pointers than when using an object directly: a pointermay be a nullptr or point to an object that wasn’t the one we expected.These differences can be annoying; for example, some programmers find f(&x) ugly compared tof(x).

Worse, managing pointer variables with varying values and protecting code against the possibility of nullptr can be a significant burden. Finally, when we want to overload an operator, say +,we want to write x+y rather than &x+&y. The language mechanism addressing these problems iscalled a reference. Like a pointer, a reference is an alias for an object, is usually implemented tohold a machine address of an object, and does not impose performance overhead compared topointers, but it differs from a pointer in that:• You access a reference with exactly the same syntax as the name of an object.• A reference always refers to the object to which it was initialized.• There is no ‘‘null reference,’’ and we may assume that a reference refers to an object(§7.7.4).A reference is an alternative name for an object, an alias.

The main use of references is for specifying arguments and return values for functions in general and for overloaded operators (Chapter 18)in particular. For example:template<class T>class vector {T∗ elem;// ...public:T& operator[](int i) { return elem[i]; }// return reference to elementconst T& operator[](int i) const { return elem[i]; } // return reference to const elementvoid push_back(const T& a);// ...// pass element to be added by reference};void f(const vector<double>& v){double d1 = v[1];// copy the value of the double referred to by v.operator[](1) into d1v[2] = 7;// place 7 in the double referred to by the result of v.operator[](2)v.push_back(d1);// give push_back() a reference to d1 to work with}The idea of passing function arguments by reference is as old as high-level programming languages(the first version of Fortran used that).190Pointers, Arrays, and ReferencesChapter 7To reflect the lvalue/rvalue and const/non-const distinctions, there are three kinds of references:• lvalue references: to refer to objects whose value we want to change• const references: to refer to objects whose value we do not want to change (e.g., a constant)• rvalue references: to refer to objects whose value we do not need to preserve after we haveused it (e.g., a temporary)Collectively, they are called references.

The first two are both called lvalue references.7.7.1 Lvalue ReferencesIn a type name, the notation X& means ‘‘reference to X.’’ It is used for references to lvalues, so it isoften called an lvalue reference. For example:void f(){int var = 1;int& r {var};int x = r;r = 2;// r and var now refer to the same int// x becomes 1// var becomes 2}To ensure that a reference is a name for something (that is, that it is bound to an object), we mustinitialize the reference. For example:int var = 1;int& r1 {var};int& r2;extern int& r3;// OK: r1 initialized// error : initializer missing// OK: r3 initialized elsewhereInitialization of a reference is something quite different from assignment to it. Despite appearances, no operator operates on a reference.

For example:void g(){int var = 0;int& rr {var};++rr;int∗ pp = &rr;}// var is incremented to 1// pp points to varHere, ++rr does not increment the reference rr; rather, ++ is applied to the int to which rr refers, thatis, to var. Consequently, the value of a reference cannot be changed after initialization; it alwaysrefers to the object it was initialized to denote. To get a pointer to the object denoted by a referencerr, we can write &rr. Thus, we cannot have a pointer to a reference. Furthermore, we cannot definean array of references.

In that sense, a reference is not an object.The obvious implementation of a reference is as a (constant) pointer that is dereferenced eachtime it is used. It doesn’t do much harm to think about references that way, as long as one remembers that a reference isn’t an object that can be manipulated the way a pointer is:Section 7.7.1Lvalue Referencespp:191&iirr:ii:1In some cases, the compiler can optimize away a reference so that there is no object representingthat reference at run time.Initialization of a reference is trivial when the initializer is an lvalue (an object whose addressyou can take; see §6.4).

The initializer for a ‘‘plain’’ T& must be an lvalue of type T.The initializer for a const T& need not be an lvalue or even of type T. In such cases:[1] First, implicit type conversion to T is applied if necessary (see §10.5).[2] Then, the resulting value is placed in a temporary variable of type T.[3] Finally, this temporary variable is used as the value of the initializer.Consider:double& dr = 1;const double& cdr {1};// error : lvalue needed// OKThe interpretation of this last initialization might be:double temp = double{1};const double& cdr {temp};// first create a temporar y with the right value// then use the temporar y as the initializer for cdrA temporary created to hold a reference initializer persists until the end of its reference’s scope.References to variables and references to constants are distinguished because introducing a temporary for a variable would have been highly error-prone; an assignment to the variable wouldbecome an assignment to the – soon-to-disappear – temporary.

No such problem exists for references to constants, and references to constants are often important as function arguments (§18.2.4).A reference can be used to specify a function argument so that the function can change thevalue of an object passed to it. For example:void increment(int& aa){++aa;}void f(){int x = 1;increment(x);}// x = 2The semantics of argument passing are defined to be those of initialization, so when called, increment’s argument aa became another name for x. To keep a program readable, it is often best toavoid functions that modify their arguments.

Instead, you can return a value from the functionexplicitly:192Pointers, Arrays, and ReferencesChapter 7int next(int p) { return p+1; }void g(){int x = 1;increment(x);x = next(x);}// x = 2// x = 3The increment(x) notation doesn’t give a clue to the reader that x’s value is being modified, the wayx=next(x) does. Consequently, ‘‘plain’’ reference arguments should be used only where the name ofthe function gives a strong hint that the reference argument is modified.References can also be used as return types. This is mostly used to define functions that can beused on both the left-hand and right-hand sides of an assignment. A Map is a good example. Forexample:template<class K, class V>class Map {// a simple map classpublic:V& operator[](const K& v);// return the value corresponding to the key vpair<K,V>∗ begin() { return &elem[0]; }pair<K,V>∗ end() { return &elem[0]+elem.size(); }private:vector<pair<K,V>> elem;// {key,value} pairs};The standard-library map (§4.4.3, §31.4.3) is typically implemented as a red-black tree, but to avoiddistracting implementation details, I’ll just show an implementation based on linear search for akey match:template<class K, class V>V& Map<K,V>::operator[](const K& k){for (auto& x : elem)if (k == x.first)return x.second;elem.push_back({k,V{}});return elem.back().second;// add pair at end (§4.4.2)// return the (default) value of the new element}I pass the key argument, k, by reference because it might be of a type that is expensive to copy.Similarly, I return the value by reference because it too might be of a type that is expensive to copy.I use a const reference for k because I don’t want to modify it and because I might want to use a literal or a temporary object as an argument.

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

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

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

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