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

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

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

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

In addition, a user can call terminate() if lessdrastic approaches are infeasible.By ‘‘tries to exit with a throw,’’ I mean that an exception is thrown somewhere and not caught sothat the run-time system tries to propagate it from a function to its caller.By default, terminate() will call abort() (§15.4.3). This default is the correct choice for mostusers – especially during debugging. If that is not acceptable, the user can provide a terminatehandler function by a call std::set_terminate() from <exception>:Section 13.5.2.5Terminationusing terminate_handler = void(∗)();// from <exception>[[noreturn]] void my_handler(){// handle termination my way}// a terminate handler cannot return373void dangerous()// very!{terminate_handler old = set_terminate(my_handler);// ...set_terminate(old); // restore the old terminate handler}The return value is the previous function given to set_terminate().For example, a terminate handler could be used to abort a process or maybe to re-initialize asystem.

The intent is for terminate() to be a drastic measure to be applied when the error recoverystrategy implemented by the exception-handling mechanism has failed and it is time to go toanother level of a fault tolerance strategy. If a terminate handler is entered, essentially nothing canbe assumed about a program’s data structures; they must be assumed to be corrupted. Even writingan error message using cerr must be assumed to be hazardous. Also, note that as dangerous() iswritten, it is not exception-safe.

A throw or even a return before set_terminate(old) will leavemy_handler in place when it wasn’t meant to be. If you must mess with terminate(), at least useRAII (§13.3).A terminate handler cannot return to its caller. If it tries to, terminate() will call abort().Note that abort() indicates abnormal exit from the program. The function exit() can be used toexit a program with a return value that indicates to the surrounding system whether the exit is normal or abnormal (§15.4.3).It is implementation-defined whether destructors are invoked when a program is terminatedbecause of an uncaught exception.

On some systems, it is essential that the destructors are notcalled so that the program can be resumed from the debugger. On other systems, it is architecturally close to impossible not to invoke the destructors while searching for a handler.If you want to ensure cleanup when an otherwise uncaught exception happens, you can add acatch-all handler (§13.5.2.2) to main() in addition to handlers for exceptions you really care about.For example:int main()try {// ...}catch (const My_error& err) {// ...

handle my error ...}catch (const std::range_error&){cerr << "range error: Not again!\n";}374Exception HandlingChapter 13catch (const std::bad_alloc&){cerr << "new ran out of memory\n";}catch (...) {// ...}This will catch every exception, except those thrown by construction and destruction of namespaceand thread-local variables (§13.5.3). There is no way of catching exceptions thrown during initialization or destruction of namespace and thread-local variables.

This is another reason to avoidglobal variables whenever possible.When an exception is caught, the exact point where it was thrown is generally not known. Thisrepresents a loss of information compared to what a debugger might know about the state of a program. In some C++ development environments, for some programs, and for some people, it mighttherefore be preferable not to catch exceptions from which the program isn’t designed to recover.See Assert (§13.4) for an example of how one might encode the location of a throw into thethrown exception.13.5.3 Exceptions and ThreadsIf an exception is not caught on a thread (§5.3.1, §42.2), std::terminate() (§13.5.2.5) is called. So, ifwe don’t want an error in a thread to stop the whole program, we must catch all errors from whichwe would like to recover and somehow report them to a part of the program that is interested in theresults of the thread.

The ‘‘catch-all’’ construct catch(...) (§13.5.2.2) comes in handy for that.We can transfer an exception thrown on one thread to a handler on another thread using thestandard-library function current_exception() (§30.4.1.2). For example:try {// ... do the work ...}catch(...) {prom.set_exception(current_exception());}This is the basic technique used by packaged_task to handle exceptions from user code (§5.3.5.2).13.6 A vector ImplementationThe standard vector provides splendid examples of techniques for writing exception-safe code: itsimplementation illustrates problems that occur in many contexts and solutions that apply widely.Obviously, a vector implementation relies on many language facilities provided to support theimplementation and use of classes. If you are not (yet) comfortable with C++’s classes and templates, you may prefer to delay studying this example until you have read Chapter 16, Chapter 25,and Chapter 26.

However, a good understanding of the use of exceptions in C++ requires a moreextensive example than the code fragments so far in this chapter.Section 13.6A vector Implementation375The basic tools available for writing exception-safe code are:• The try-block (§13.5).• The support for the ‘‘Resource Acquisition Is Initialization’’ technique (§13.3).The general principles to follow are to• Never let go of a piece of information before its replacement is ready for use.• Always leave objects in valid states when throwing or rethrowing an exception.That way, we can always back out of an error situation.

The practical difficulty in following theseprinciples is that innocent-looking operations (such as <, =, and sort()) might throw exceptions.Knowing what to look for in an application takes experience.When you are writing a library, the ideal is to aim at the strong exception-safety guarantee(§13.2) and always to provide the basic guarantee. When writing a specific program, there may beless concern for exception safety. For example, if I write a simple data analysis program for myown use, I’m usually quite willing to have the program terminate in the unlikely event of memoryexhaustion.Correctness and basic exception safety are closely related.

In particular, the techniques for providing basic exception safety, such as defining and checking invariants (§13.4), are similar to thetechniques that are useful to get a program small and correct. It follows that the overhead of providing the basic exception-safety guarantee (§13.2) – or even the strong guarantee – can be minimalor even insignificant.13.6.1 A Simple vectorA typical implementation of vector (§4.4.1, §31.4) will consist of a handle holding pointers to thefirst element, one-past-the-last element, and one-past-the-last allocated space (§31.2.1) (or theequivalent information represented as a pointer plus offsets):vector:elemspacelastallocelementsextra spaceIn addition, it holds an allocator (here, alloc), from which the vector can acquire memory for its elements. The default allocator (§34.4.1) uses new and delete to acquire and release memory.Here is a declaration of vector simplified to present only what is needed to discuss exceptionsafety and avoidance of resource leaks:template<class T, class A = allocator<T>>class vector {private:T∗ elem;// star t of allocationT∗ space;// end of element sequence, star t of space allocated for possible expansionT∗ last;// end of allocated spaceA alloc;// allocator376Exception Handlingpublic:using size_type = unsigned int;Chapter 13// type used for vector sizesexplicit vector(size_type n, const T& val = T(), const A& = A());vector(const vector& a);vector& operator=(const vector& a);// copy constructor// copy assignmentvector(vector&& a);vector& operator=(vector&& a);// move constructor// move assignment˜vector();size_type size() const { return space−elem; }size_type capacity() const { return last−elem; }void reserve(size_type n);// increase capacity to nvoid resize(size_type n, const T& = {});void push_back(const T&);// increase size to n// add an element at the end// ...};Consider first a naive implementation of the constructor that initializes atialized to val:vectortonelements ini-template<class T, class A>vector<T,A>::vector(size_type n, const T& val, const A& a) // warning: naive implementation:alloc{a}// copy the allocator{elem = alloc.allocate(n);// get memory for elements (§34.4)space = last = elem+n;for (T∗ p = elem; p!=last; ++p)a.construct(p,val);// construct copy of val in *p (§34.4)}There are two potential sources of exceptions here:[1] allocate() may throw an exception if no memory is available.[2] T’s copy constructor may throw an exception if it can’t copy val.What about the copy of the allocator? We can imagine that it throws, but the standard specificallyrequires that it does not do that (§iso.17.6.3.5).

Anyway, I have written the code so that it wouldn’tmatter if it did.In both cases of a throw, no vector object is created, so vector’s destructor is not called (§13.3).When allocate() fails, the throw will exit before any resources are acquired, so all is well.When T’s copy constructor fails, we have acquired some memory that must be freed to avoidmemory leaks. Worse still, the copy constructor for T might throw an exception after correctly constructing a few elements but before constructing them all.

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

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

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

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