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

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

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

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

Note that every operator new() takes a size as its first argument andthat the size of the object allocated is implicitly supplied (§19.2.5). The operator new() used by thenew operator is chosen by the usual argument matching rules (§12.3); every operator new() has asize_t as its first argument.The ‘‘placement’’ operator new() is the simplest such allocator.

It is defined in the standardheader <new>:void∗ operator new (size_t sz, void∗ p) noexcept;void∗ operator new[](size_t sz, void∗ p) noexcept;// place object of size sz at p// place object of size sz at pvoid operator delete (void∗ p, void∗) noexcept;void operator delete[](void∗ p, void∗) noexcept;// if (p) make *p invalid// if (p) make *p invalidThe ‘‘placement delete’’ operators do nothing except possibly inform a garbage collector that thedeleted pointer is no longer safely derived (§34.5).The placement new construct can also be used to allocate memory from a specific arena:class Arena {public:virtual void∗ alloc(size_t) =0;virtual void free(void∗) =0;// ...};void∗ operator new(size_t sz, Arena∗ a){return a−>alloc(sz);}Now objects of arbitrary types can be allocated from different Arenas as needed.

For example:extern Arena∗ Persistent;extern Arena∗ Shared;void g(int i){X∗ p = new(Persistent) X(i);X∗ q = new(Shared) X(i);// ...}// X in persistent storage// X in shared memorySection 11.2.4Overloading new285Placing an object in an area that is not (directly) controlled by the standard free-store managerimplies that some care is required when destroying the object. The basic mechanism for that is anexplicit call of a destructor:void destroy(X∗ p, Arena∗ a){p−>˜X();// call destructora−>free(p);// free memory}Note that explicit calls of destructors should be avoided except in the implementation of resourcemanagement classes. Even most resource handles can be written using new and delete. However, itwould be hard to implement an efficient general container along the lines of the standard-libraryvector (§4.4.1, §31.3.3) without using explicit destructor calls.

A novice should think thrice beforecalling a destructor explicitly and also should ask a more experienced colleague before doing so.See §13.6.1 for an example of how placement new can interact with exception handling.There is no special syntax for placement of arrays. Nor need there be, since arbitrary types canbe allocated by placement new. However, an operator delete() can be defined for arrays (§11.2.3).11.2.4.1 nothrow newIn programs where exceptions must be avoided (§13.1.5), we can usedelete. For example:nothrowversions ofnewandvoid f(int n){int∗ p = new(nothrow) int[n];// allocate n ints on the free storeif (p==nullptr) {// no memory available// ... handle allocation error ...}// ...operator delete(nothrow,p);// deallocate *p}That nothrow is the name of an object of the standard-library type nothrow_t that is used for disambiguation; nothrow and nothrow_t are declared in <new>.The functions implementing this are found in <new>:void∗ operator new(size_t sz, const nothrow_t&) noexcept; // allocate sz bytes;// return nullptr if allocation failedvoid operator delete(void∗ p, const nothrow_t&) noexcept; // deallocate space allocated by newvoid∗ operator new[](size_t sz, const nothrow_t&) noexcept; // allocate sz bytes;// return nullptr if allocation failedvoid operator delete[](void∗ p, const nothrow_t&) noexcept; // deallocate space allocated by newThese operator new functions return nullptr, rather than throwing bad_alloc, if there is not sufficientmemory to allocate.286Select OperationsChapter 1111.3 ListsIn addition to their use for initializing named variables (§6.3.5.2), {}-lists can be used as expressionsin many (but not all) places.

They can appear in two forms:[1] Qualified by a type, T{...}, meaning ‘‘create an object of type T initialized by T{...}’’;§11.3.2[2] Unqualified {...}, for which the the type must be determined from the context of use;§11.3.3For example:struct S { int a, b; };struct SS { double a, b; };void f(S);// f() takes an Svoid g(S);void g(SS);// g() is overloadedvoid h(){f({1,2});g({1,2});g(S{1,2});g(SS{1,2});// OK: call f(S{1,2})// error : ambiguous// OK: call g(S)// OK: call g(SS)}As in their use for initializing named variables (§6.3.5), lists can have zero, one, or more elements.A {}-list is used to construct an object of some type, so the number of elements and their types mustbe what is required to construct an object of that type.11.3.1 Implementation ModelThe implementation model for {}-lists comes in three parts:• If the {}-list is used as constructor arguments, the implementation is just as if you had used a()-list.

List elements are not copied except as by-value constructor arguments.• If the {}-list is used to initialize the elements of an aggregate (an array or a class without aconstructor), each list element initializes an element of the aggregate. List elements are notcopied except as by-value arguments to aggregate element constructors.• If the {}-list is used to construct an initializer_list object each list element is used to initializean element of the underlying array of the initializer_list.

Elements are typically copied fromthe initializer_list to wherever we use them.Note that this is the general model that we can use to understand the semantics of a {}-list; a compiler may apply clever optimizations as long as the meaning is preserved.Consider:vector<double> v = {1, 2, 3.14};The standard-libraryvectorhas an initializer-list constructor (§17.3.4), so the initializer listSection 11.3.1{1,2,3.14}Implementation Model287is interpreted as a temporary constructed and used like this:const double temp[] = {double{1}, double{2}, 3.14 } ;const initializer_list<double> tmp(temp,sizeof(temp)/sizeof(double));vector<double> v(tmp);That is, the compiler constructs an array containing the initializers converted to the desired type(here, double).

This array is passed to vectors initializer-list constructor as an initializer_list. Theinitializer-list constructor then copies the values from the array into its own data structure for elements. Note that an initializer_list is a small object (probably two words), so passing it by valuemakes sense.The underlying array is immutable, so there is no way (within the standard’s rules) that themeaning of a {}-list can change between two uses.

Consider:void f(){initializer_list<int> lst {1,2,3};cout << ∗lst.begin() << '\n';∗lst.begin() = 2;// error : lst is immutablecout << ∗lst.begin() << '\n';}In particular, having a {}-list be immutable implies that a container taking elements from it must usea copy operation, rather than a move operation.The lifetime of a {}-list (and its underlying array) is determined by the scope in which it is used(§6.4.2). When used to initialize a variable of type initializer_list<T>, the list lives as long as thevariable.

When used in an expression (including as an initializer to a variable of some other type,such as vector<T>), the list is destroyed at the end of its full expression.11.3.2 Qualified ListsThe basic idea of initializer lists as expressions is that if you can initialize a variablenotationxusing theT x {v};then you can create an object with the same value as an expression using T{v} or new T{v}.

Usingnew places the object on the free store and returns a pointer to it, whereas ‘‘plain T{v}’’ makes atemporary object in the local scope (§6.4.2). For example:struct S { int a, b; };void f(){S v {7,8};v = S{7,8};S∗ p = new S{7,8};}// direct initialization of a variable// assign using qualified list// construct on free store using qualified listThe rules constructing an object using a qualified list are those of direct initialization (§16.2.6).288Select OperationsChapter 11One way of looking at a qualified initializer list with one element is as a conversion from onetype to another. For example:template<class T>T square(T x){return x∗x;}void f(int i){double d = square(double{i});complex<double> z = square(complex<double>{i});}That idea is explored further in §11.5.1.11.3.3 Unqualified ListsA unqualified list is used where an expected type is unambiguously known. It can be used as anexpression only as:• A function argument• A return value• The right-hand operand of an assignment operator (=, +=, ∗=, etc.)• A subscriptFor example:int f(double d, Matrix& m){int v {7};// initializer (direct initialization)int v2 = {7};// initializer (copy initialization)int v3 = m[{2,3}];// assume m takes value pairs as subscriptsv = {8};v += {88};{v} = 9;v = 7+{10};f({10.0});return {11};// right-hand operand of assignment// right-hand operand of assignment// error: not left-hand operand of assignment// error: not an operand of a non-assignment operator// function argument// return value}The reason that an unqualified list is not allowed on the left-hand side of assignments is primarilythat the C++ grammar allows { in that position for compound statements (blocks), so that readability would be a problem for humans and ambiguity resolution would be tricky for compilers.

This isnot an insurmountable problem, but it was decided not to extend C++ in that direction.When used as the initializer for a named object without the use of a = (as for v above), anunqualified {}-list performs direct initialization (§16.2.6). In all other cases, it performs copyinitialization (§16.2.6). In particular, the otherwise redundant = in an initializer restricts the set ofinitializations that can be performed with a given {}-list.Section 11.3.3Unqualified Lists289The standard-library type initializer_list<T> is used to handle variable-length {}-lists (§12.2.3).Its most obvious use is to allow initializer lists for user-defined containers (§3.2.1.3), but it can alsobe used directly; for example:int high_value(initializer_list<int> val){int high = numeric_traits<int>lowest();if (val.size()==0) return high;for (auto x : val)if (x>high) high = x;return high;}int v1 = high_value({1,2,3,4,5,6,7});int v2 = high_value({−1,2,v1,4,−9,20,v1});A {}-list is the simplest way of dealing with homogeneous lists of varying lengths.

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

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

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

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