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

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

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

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

As it happens, these are not unreasonable or uncommon values. Theassumption is that once we have seen one push_back() for a vector, we will almost certainly seemany more. The factor two is larger than the mathematically optimal factor to minimize averagememory use (1.618), so as to give better run-time performance for systems where memories are nottiny.13.6.4.4 Final ThoughtsNote the absence of try-blocks in the vector implementation (except for the one hidden inside uniniThe changes in state were done by carefully ordering the operations so that if anexception is thrown, the vector remains unchanged or at least valid.The approach of gaining exception safety through ordering and the RAII technique (§13.3)tends to be more elegant and more efficient than explicitly handling errors using try-blocks. Moreproblems with exception safety arise from a programmer ordering code in unfortunate ways thanfrom lack of specific exception-handling code.

The basic rule of ordering is not to destroy information before its replacement has been constructed and can be assigned without the possibility of anexception.Exceptions introduce possibilities for surprises in the form of unexpected control flows. For apiece of code with a simple local control flow, such as the reserve(), safe_assign(), and push_back()examples, the opportunities for surprises are limited. It is relatively simple to look at such code andask, ‘‘Can this line of code throw an exception, and what happens if it does?’’ For large functionswith complicated control structures, such as complicated conditional statements and nested loops,this can be hard. Adding try-blocks increases this local control structure complexity and can therefore be a source of confusion and errors (§13.3).

I conjecture that the effectiveness of the orderingapproach and the RAII approach compared to more extensive use of try-blocks stems from the simplification of the local control flow. Simple, stylized code is easier to understand, easier to getright, and easier to generate good code for.This vector implementation is presented as an example of the problems that exceptions can poseand of techniques for addressing those problems.

The standard does not require an implementationto be exactly like the one presented here. However, the standard does require the exception-safetyguarantees as provided by the example.tialized_copy()).13.7 Advice[1][2][3][4]Develop an error-handling strategy early in a design; §13.1.Throw an exception to indicate that you cannot perform an assigned task; §13.1.1.Use exceptions for error handling; §13.1.4.2.Use purpose-designed user-defined types as exceptions (not built-in types); §13.1.1.Section 13.7[5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][22][23][24][25][26][27][28][29][30][31][32][33][34][35]Advice387If you for some reason cannot use exceptions, mimic them; §13.1.5.Use hierarchical error handling; §13.1.6.Keep the individual parts of error handling simple; §13.1.6.Don’t try to catch every exception in every function; §13.1.6.Always provide the basic guarantee; §13.2, §13.6.Provide the strong guarantee unless there is a reason not to; §13.2, §13.6.Let a constructor establish an invariant, and throw if it cannot; §13.2.Release locally owned resources before throwing an exception; §13.2.Be sure that every resource acquired in a constructor is released when throwing an exceptionin that constructor; §13.3.Don’t use exceptions where more local control structures will suffice; §13.1.4.Use the ‘‘Resource Acquisition Is Initialization’’ technique to manage resources; §13.3.Minimize the use of try-blocks; §13.3.Not every program needs to be exception-safe; §13.1.Use ‘‘Resource Acquisition Is Initialization’’ and exception handlers to maintain invariants;§13.5.2.2.Prefer proper resource handles to the less structured finally; §13.3.1.Design your error-handling strategy around invariants; §13.4.What can be checked at compile time is usually best checked at compile time (usingstatic_assert); §13.4.Design your error-handling strategy to allow for different levels of checking/enforcement;§13.4.If your function may not throw, declare it noexcept; §13.5.1.1Don’t use exception specification; §13.5.1.3.Catch exceptions that may be part of a hierarchy by reference; §13.5.2.Don’t assume that every exception is derived from class exception; §13.5.2.2.Have main() catch and report all exceptions; §13.5.2.2, §13.5.2.4.Don’t destroy information before you have its replacement ready; §13.6.Leave operands in valid states before throwing an exception from an assignment; §13.2.Never let an exception escape from a destructor; §13.2.Keep ordinary code and error-handling code separate; §13.1.1, §13.1.4.2.Beware of memory leaks caused by memory allocated by new not being released in case ofan exception; §13.3.Assume that every exception that can be thrown by a function will be thrown; §13.2.A library shouldn’t unilaterally terminate a program.

Instead, throw an exception and let acaller decide; §13.4.A library shouldn’t produce diagnostic output aimed at an end user. Instead, throw an exception and let a caller decide; §13.1.3.This page intentionally left blank14NamespacesThe year is 787!A.D.?– Monty Python•••••Composition ProblemsNamespacesExplicit Qualification; using-Declarations; using-Directives; Argument-Dependent Lookup;Namespaces Are OpenModularization and InterfacesNamespaces as Modules; Implementations; Interfaces and ImplementationsComposition Using NamespacesConvenience vs. Safety; Namespace Aliases; Namespace Composition; Composition andSelection; Namespaces and Overloading; Versioning; Nested Namespaces; Unnamed Namespaces; C HeadersAdvice14.1 Composition ProblemsAny realistic program consists of a number of separate parts.

Functions (§2.2.1, Chapter 12) andclasses (§3.2, Chapter 16) provide relatively fine-grained separation of concerns, whereas‘‘libraries,’’ source files, and translation units (§2.4, Chapter 15) provide coarser grain. The logicalideal is modularity, that is, to keep separate things separate and to allow access to a ‘‘module’’ onlythrough a well-specified interface. C++ does not provide a single language feature supporting thenotion of a module; there is no module construct. Instead, modularity is expressed through combinations of other language facilities, such as functions, classes, and namespaces, and source codeorganization.This chapter and the next deal with the coarse structure of a program and its physical representation as source files.

That is, these two chapters are more concerned with programming in the390NamespacesChapter 14large than with the elegant expression of individual types, algorithms, and data structures.Consider some of the problems that can arise when people fail to design for modularity. Forexample, a graphics library may provide different kinds of graphical Shapes and functions to helpuse them:// Graph_lib:class Shape { /* ... */ };class Line : public Shape { /* ...

*/ };class Poly_line: public Shape { /* ... */ };class Text : public Shape { /* ... */ };// connected sequence of lines// text labelShape operator+(const Shape&, const Shape&);// composeGraph_reader open(const char∗);// open file of ShapesNow someone comes along with another library, providing facilities for text manipulation:// Text_lib:class Glyph { /* ... */ };class Word { /* ... */ };class Line { /* ... */ };class Text { /* ... */ };// sequence of Glyphs// sequence of Words// sequence of LinesFile∗ open(const char∗);// open text fileWord operator+(const Line&, const Line&);// concatenateFor the moment, let us ignore the specific design issues for graphics and text manipulation and justconsider the problems of using Graph_lib and Text_lib together in a program.Assume (realistically enough) that the facilities of Graph_lib are defined in a header (§2.4.1),Graph_lib.h, and the facilities of Text_lib are defined in another header, Text_lib.h.

Now, I can ‘‘innocently’’ #include both and try to use facilities from the two libraries:#include "Graph_lib.h"#include "Text_lib.h"// ...Just #includeing those headers causes a slurry of error messages: Line, Text, and open() are definedtwice in ways that a compiler cannot disambiguate. Trying to use the libraries would give furthererror messages.There are many techniques for dealing with such name clashes. For example, some such problems can be addressed by placing all the facilities of a library inside a few classes, by using supposedly uncommon names (e.g., Text_box rather than Text), or by systematically using a prefix fornames from a library (e.g., gl_shape and gl_line).

Each of these techniques (also known as ‘‘workarounds’’ and ‘‘hacks’’) works in some cases, but they are not general and can be inconvenient touse. For example, names tend to become long, and the use of many different names inhibitsgeneric programming (§3.4).Section 14.2Namespaces39114.2 NamespacesThe notion of a namespace is provided to directly represent the notion of a set of facilities thatdirectly belong together, for example, the code of a library. The members of a namespace are in thesame scope and can refer to each other without special notation, whereas access from outside thenamespace requires explicit notation. In particular, we can avoid name clashes by separating setsof declarations (e.g., library interfaces) into namespaces. For example, we might call the graphlibrary Graph_lib:namespace Graph_lib {class Shape { /* ...

*/ };class Line : public Shape { /* ... */ };class Poly_line: public Shape { /* ... */ };class Text : public Shape { /* ... */ };// connected sequence of lines// text labelShape operator+(const Shape&, const Shape&);// composeGraph_reader open(const char∗);// open file of Shapes}Similarly, the obvious name for our text library is Text_lib:namespace Text_lib {class Glyph { /* ... */ };class Word { /* ... */ };class Line { /* ...

*/ };class Text { /* ... */ };// sequence of Glyphs// sequence of Words// sequence of LinesFile∗ open(const char∗);// open text fileWord operator+(const Line&, const Line&);// concatenate}As long as we manage to pick distinct namespace names, such as Graph_lib and Text_lib (§14.4.2),we can now compile the two sets of declarations together without name clashes.A namespace should express some logical structure: the declarations within a namespace shouldtogether provide facilities that unite them in the eyes of their users and reflect a common set ofdesign decisions.

They should be seen as a logical unit, for example, ‘‘the graphics library’’ or‘‘the text manipulation library,’’ similar to the way we consider the members of a class. In fact, theentities declared in a namespace are referred to as the members of the namespace.A namespace is a (named) scope. You can access members defined earlier in a namespace fromlater declarations, but you cannot (without special effort) refer to members from outside the namespace.

For example:class Glyph { /* ... */ };class Line { /* ... */ };namespace Text_lib {class Glyph { /* ... */ };class Word { /* ... */ };// sequence of Glyphs392NamespacesChapter 14class Line { /* ... */ }; // sequence of Wordsclass Text { /* ... */ }; // sequence of LinesFile∗ open(const char∗);// open text fileWord operator+(const Line&, const Line&);// concatenate}Glyph glyph(Line& ln, int i);// ln[i]Here, theWord and Line in the declaration of Text_lib::operator+() refer to Text_lib::Word andText_lib::Line. That local name lookup is not affected by the global Line. Conversely, the Glyph andLine in the declaration of the global glyph() refer to the global ::Glyph and ::Line.

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

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

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

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