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

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

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

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

Consider:void g(int) noexcept;void h(const string&) noexcept;Now, the code generated for f() can possibly be improved.No traditional C function throws an exception, so most C functions can be declared noexcept.In particular, a standard-library implementer knows that only a few standard C library functions(such as atexit() and qsort()) can throw, and can take advantage of that fact to generate better code.Before declaring a ‘‘C function’’ noexcept, take a minute to consider if it could possibly throwan exception. For example, it might have been converted to use the C++ operator new, which canthrow bad_alloc, or it might call a C++ library that throws an exception.As ever, discussions about efficiency are meaningless in the absence of measurements.Section 13.2Exception Guarantees35313.2 Exception GuaranteesTo recover from an error – that is, to catch an exception and continue executing a program – weneed to know what can be assumed about the state of the program before and after the attemptedrecovery action.

Only then can recovery be meaningful. Therefore, we call an operation exceptionsafe if that operation leaves the program in a valid state when the operation is terminated by throwing an exception. However, for that to be meaningful and useful, we have to be precise about whatwe mean by ‘‘valid state.’’ For practical design using exceptions, we must also break down theoverly general ‘‘exception-safe’’ notion into a few specific guarantees.When reasoning about objects, we assume that a class has a class invariant (§2.4.3.2, §17.2.1).We assume that this invariant is established by its constructor and maintained by all functions withaccess to the object’s representation until the object is destroyed. So, by valid state we mean that aconstructor has completed and the destructor has not yet been entered.

For data that isn’t easilyviewed as an object, we must reason similarly. That is, if two pieces of nonlocal data are assumedto have a specific relationship, we must consider that an invariant and our recovery action must preserve it. For example:namespace Points {vector<int> vx;vector<int> vy;};// (vx[i],vy[i]) is a point for all iHere it is assumed that vx.size()==vy.size() is (always) true.

However, that was only stated in a comment, and compilers do not read comments. Such implicit invariants can be very hard to discoverand maintain.Before a throw, a function must place all constructed objects in valid states. However, such avalid state may be one that doesn’t suit the caller.

For example, a string may be left as the emptystring or a container may be left unsorted. Thus, for complete recovery, an error handler may haveto produce values that are more appropriate/desirable for the application than the (valid) ones existing at the entry to a catch-clause.The C++ standard library provides a generally useful conceptual framework for design forexception-safe program components. The library provides one of the following guarantees forevery library operation:• The basic guarantee for all operations: The basic invariants of all objects are maintained,and no resources, such as memory, are leaked.

In particular, the basic invariants of everybuilt-in and standard-library type guarantee that you can destroy an object or assign to itafter every standard-library operation (§iso.17.6.3.1).• The strong guarantee for key operations: in addition to providing the basic guarantee, eitherthe operation succeeds, or it has no effect.

This guarantee is provided for key operations,such as push_back(), single-element insert() on a list, and uninitialized_copy().• The nothrow guarantee for some operations: in addition to providing the basic guarantee,some operations are guaranteed not to throw an exception. This guarantee is provided for afew simple operations, such as swap() of two containers and pop_back().354Exception HandlingChapter 13Both the basic guarantee and the strong guarantee are provided on the condition that• user-supplied operations (such as assignments and swap() functions) do not leave containerelements in invalid states,• user-supplied operations do not leak resources, and• destructors do not throw exceptions (§iso.17.6.5.12).Violating a standard-library requirement, such as having a destructor exit by throwing an exception,is logically equivalent to violating a fundamental language rule, such as dereferencing a nullpointer.

The practical effects are also equivalent and often disastrous.Both the basic guarantee and the strong guarantee require the absence of resource leaks. This isnecessary for every system that cannot afford resource leaks. In particular, an operation that throwsan exception must not only leave its operands in well-defined states but must also ensure that everyresource that it acquired is (eventually) released. For example, at the point where an exception isthrown, all memory allocated must be either deallocated or owned by some object, which in turnmust ensure that the memory is properly deallocated.

For example:void f(int i){int∗ p = new int[10];// ...if (i<0) {delete[] p;// delete before the throw or leakthrow Bad();}// ...}Remember that memory isn’t the only kind of resource that can leak. I consider anything that hasto be acquired from another part of the system and (explicitly or implicitly) given back to be aresource. Files, locks, network connections, and threads are examples of system resources. Afunction may have to release those or hand them over to some resource handler before throwing anexception.The C++ language rules for partial construction and destruction ensure that exceptions thrownwhile constructing subobjects and members will be handled correctly without special attentionfrom standard-library code (§17.2.3).

This rule is an essential underpinning for all techniques dealing with exceptions.In general, we must assume that every function that can throw an exception will throw one.This implies that we must structure our code so that we don’t get lost in a rat’s nest of complicatedcontrol structures and brittle data structures. When analyzing code for potential errors, simple,highly structured, ‘‘stylized’’ code is the ideal; §13.6 includes a realistic example of such code.13.3 Resource ManagementWhen a function acquires a resource – that is, it opens a file, allocates some memory from the freestore, acquires a mutex, etc. – it is often essential for the future running of the system that theresource be properly released. Often that ‘‘proper release’’ is achieved by having the function thatacquired it release it before returning to its caller.

For example:Section 13.3Resource Management355void use_file(const char∗ fn) // naive code{FILE∗ f = fopen(fn,"r");// ... use f ...fclose(f);}This looks plausible until you realize that if something goes wrong after the call of fopen() andbefore the call of fclose(), an exception may cause use_file() to be exited without fclose() beingcalled.

Exactly the same problem can occur in languages that do not support exception handling.For example, the standard C library function longjmp() can cause the same problem. Even an ordinary return-statement could exit use_file without closing f.A first attempt to make use_file() fault-tolerant looks like this:void use_file(const char∗ fn) // clumsy code{FILE∗ f = fopen(fn,"r");try {// ... use f ...}catch (...) {// catch every possible exceptionfclose(f);throw;}fclose(f);}The code using the file is enclosed in a try-block that catches every exception, closes the file, andrethrows the exception.The problem with this solution is that it is verbose, tedious, and potentially expensive.

Worsestill, such code becomes significantly more complex when several resources must be acquired andreleased. Fortunately, there is a more elegant solution. The general form of the problem looks likethis:void acquire(){// acquire resource 1// ...// acquire resource n// ... use resources ...// release resource n// ...// release resource 1}It is typically important that resources are released in the reverse order of their acquisition.

This356Exception HandlingChapter 13strongly resembles the behavior of local objects created by constructors and destroyed by destructors. Thus, we can handle such resource acquisition and release problems using objects of classeswith constructors and destructors. For example, we can define a class File_ptr that acts like a FILE∗:class File_ptr {FILE∗ p;public:File_ptr(const char∗ n, const char∗ a)// open file n: p{fopen(n,a)}{if (p==nullptr) throw runtime_error{"File_ptr: Can't open file"};}File_ptr(const string& n, const char∗ a) // open file n:File_ptr{n.c_str(),a}{}explicit File_ptr(FILE∗ pp)// assume ownership of pp:p{pp}{if (p==nullptr) throw runtime_error("File_ptr: nullptr"};}// ...

suitable move and copy operations ...˜File_ptr() { fclose(p); }operator FILE∗() { return p; }};We can construct a File_ptr given either a FILE∗ or the arguments required for fopen(). In either case,a File_ptr will be destroyed at the end of its scope and its destructor will close the file. File_ptrthrows an exception if it cannot open a file because otherwise every operation on the file handlewould have to test for nullptr. Our function now shrinks to this minimum:void use_file(const char∗ fn){File_ptr f(fn,"r");// ...

use f ...}The destructor will be called independently of whether the function is exited normally or exitedbecause an exception is thrown. That is, the exception-handling mechanisms enable us to removethe error-handling code from the main algorithm. The resulting code is simpler and less errorprone than its traditional counterpart.This technique for managing resources using local objects is usually referred to as ‘‘ResourceAcquisition Is Initialization’’ (RAII; §5.2). This is a general technique that relies on the propertiesof constructors and destructors and their interaction with exception handling.Section 13.3Resource Management357It is often suggested that writing a ‘‘handle class’’ (a RAII class) is tedious so that providing anicer syntax for the catch(...) action would provide a better solution.

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

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

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

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