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

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

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

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

Even if you prefer this ‘‘enhanced language’’ to plain C++, it will be incomprehensible to most C++ programmers. Furthermore, the preprocessor is a very simple-minded macro processor. When you try to do something nontrivial, youare likely to find it either impossible or unnecessarily hard to do. The auto, constexpr, const,decltype, enum, inline, lambda expressions, namespace, and template mechanisms can be used asbetter-behaved alternatives to many traditional uses of preprocessor constructs.

For example:const int answer = 42;template<class T>inline const T& min(const T& a, const T& b){return (a<b)?a:b;}When writing a macro, it is not unusual to need a new name for something. A string can be createdby concatenating two strings using the ## macro operator. For example:#define NAME2(a,b) a##bint NAME2(hack,cah)();will produceint hackcah();A single # before a parameter name in a replacement string means a string containing the macroargument. For example:#define printx(x) cout << #x " = " << x << '\n';int a = 7;string str = "asdf";Section 12.6void f(){printx(a);printx(str);}Macros339// cout << "a" << " = " << a << '\n';// cout << "str" << " = " << str << '\n';Writing #x " = " rather than #x << " = " is obscure ‘‘clever code’’ rather than an error.

Adjacent stringliterals are concatenated (§7.3.2).The directive#undef Xensures that no macro called X is defined – whether or not one was before the directive. Thisaffords some protection against undesired macros. However, it is not always easy to know what theeffects of X on a piece of code were supposed to be.The argument list (‘‘replacement list’’) of a macro can be empty:#define EMPTY() std::cout<<"empty\n"EMPTY();// print "empty\n"EMPTY;// error: macro replacement list missingI have a hard time thinking of uses of an empty macro argument list that are not error-prone ormalicious.Macros can even be variadic.

For example:#define err_print(...) fprintf(stderr,"error: %s %d\n", __VA_ARGS__)err_print("The answer",54);The ellipsis (...) means thatthe output is:__VA_ARGS__represents the arguments actually passed as a string, soerror: The answer 5412.6.1 Conditional CompilationOne use of macros is almost impossible to avoid. The directive#ifdef IDENTIFIERdoes nothing if IDENTIFIER is defined, but if it is not, the directive causes all input to be ignoreduntil a #endif directive is seen. For example:int f(int a#ifdef arg_two,int b#endif);Unless a macro called arg_two has been #defined , this produces:int f(int a);This example confuses tools that assume sane behavior from the programmer.340FunctionsChapter 12Most uses of #ifdef are less bizarre, and when used with restraint, #ifdef and its complement #ifndo little harm.

See also §15.3.3.Names of the macros used to control #ifdef should be chosen carefully so that they don’t clashwith ordinary identifiers. For example:defstruct Call_info {Node∗ arg_one;Node∗ arg_two;// ...};This innocent-looking source text will cause some confusion should someone write:#define arg_two xUnfortunately, common and unavoidable headers contain many dangerous and unnecessary macros.12.6.2 Predefined MacrosA few macros are predefined by the compiler (§iso.16.8, §iso.8.4.1):• __cplusplus: defined in a C++ compilation (and not in a C compilation). Its value is 201103Lin a C++11 program; previous C++ standards have lower values.• __DATE__: date in ‘‘yyyy:mm:dd’’ format.• __TIME__: time in ‘‘hh:mm:ss’’ format.• __FILE__: name of current source file.• __LINE__: source line number within the current source file.• __FUNC__: an implementation-defined C-style string naming the current function.• __STDC_HOSTED__: 1 if the implementation is hosted (§6.1.1); otherwise 0.In addition, a few macros are conditionally defined by the implementation:• __STDC__: defined in a C compilation (and not in a C++ compilation)• __STDC_MB_MIGHT_NEQ_WC__: 1 if, in the encoding for wchar_t, a member of the basiccharacter set (§6.1) might have a code value that differs from its value as an ordinary character literal• __STDCPP_STRICT_POINTER_SAFETY__: 1 if the implementation has strict pointer safety(§34.5); otherwise undefined.• __STDCPP_THREADS__: 1 if a program can have more than one thread of execution; otherwise undefined.For example:cout << __FUNC__ << "() in file " << __FILE__ << " on line " << __LINE__ << "\n";In addition, most C++ implementations allow a user to define arbitrary macros on the commandline or in some other form of compile-time environment.

For example, NDEBUG is defined unlessthe compilation is done in (some implementation-specific) ‘‘debug mode’’ and is used by theassert() macro (§13.4). This can be useful, but it does imply that you can’t be sure of the meaningof a program just by reading its source text.Section 12.6.3Pragmas34112.6.3 PragmasImplementations often provide facilities that differ from or go beyond what the standard offers.Obviously, the standard cannot specify how such facilities are provided, but one standard syntax isa line of tokens prefixed with the preprocessor directive #pragma. For example:#pragma foo bar 666 foobarIf possible, #pragmas are best avoided.12.7 Advice[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][22][23]‘‘Package’’ meaningful operations as carefully named functions; §12.1.A function should perform a single logical operation; §12.1.Keep functions short; §12.1.Don’t return pointers or references to local variables; §12.1.4.If a function may have to be evaluated at compile time, declare it constexpr; §12.1.6.If a function cannot return, mark it [[noreturn]]; §12.1.7.Use pass-by-value for small objects; §12.2.1.Use pass-by-const-reference to pass large values that you don’t need to modify; §12.2.1.Return a result as a return value rather than modifying an object through an argument;§12.2.1.Use rvalue references to implement move and forwarding; §12.2.1.Pass a pointer if ‘‘no object’’ is a valid alternative (and represent ‘‘no object’’ by nullptr);§12.2.1.Use pass-by-non-const-reference only if you have to; §12.2.1.Use const extensively and consistently; §12.2.1.Assume that a char∗ or a const char∗ argument points to a C-style string; §12.2.2.Avoid passing arrays as pointers; §12.2.2.Pass a homogeneous list of unknown length as an initializer_list<T> (or as some other container); §12.2.3.Avoid unspecified numbers of arguments (...); §12.2.4.Use overloading when functions perform conceptually the same task on different types;§12.3.When overloading on integers, provide functions to eliminate common ambiguities; §12.3.5.Specify preconditions and postconditions for your functions; §12.4.Prefer function objects (including lambdas) and virtual functions to pointers to functions;§12.5.Avoid macros; §12.6.If you must use macros, use ugly names with lots of capital letters; §12.6.This page intentionally left blank13Exception HandlingDon’t interrupt mewhile I’m interrupting.– Winston S.

Churchill•••••••Error HandlingExceptions; Traditional Error Handling; Muddling Through; Alternative Views of Exceptions; When You Can’t Use Exceptions; Hierarchical Error Handling; Exceptions and EfficiencyException GuaranteesResource ManagementFinallyEnforcing InvariantsThrowing and Catching ExceptionsThrowing Exceptions; Catching Exceptions; Exceptions and ThreadsA vector ImplementationA Simple vector; Representing Memory Explicitly; Assignment; Changing SizeAdvice13.1 Error HandlingThis chapter presents error handling using exceptions. For effective error handling, the languagemechanisms must be used based on a strategy.

Consequently, this chapter presents the exceptionsafety guarantees that are central to recovery from run-time errors and the Resource Acquisition IsInitialization (RAII) technique for resource management using constructors and destructors. Boththe exception-safety guarantees and RAII depend on the specification of invariants, so mechanismsfor enforcement of assertions are presented.The language facilities and techniques presented here address problems related to the handlingof errors in software; the handling of asynchronous events is a different topic.344Exception HandlingChapter 13The discussion of errors focuses on errors that cannot be handled locally (within a single smallfunction), so that they require separation of error-handling activities into different parts of a program.

Such parts of a program are often separately developed. Consequently, I often refer to a partof a program that is invoked to perform a task as ‘‘a library.’’ A library is just ordinary code, but inthe context of a discussion of error handling it is worth remembering that a library designer oftencannot even know what kind of programs the library will become part of:• The author of a library can detect a run-time error but does not in general have any ideawhat to do about it.• The user of a library may know how to cope with a run-time error but cannot easily detect it(or else it would have been handled in the user’s code and not left for the library to find).The discussion of exceptions focuses on problems that need to be handled in long-running systems,systems with stringent reliability requirements, and libraries.

Different kinds of programs have different requirements, and the amount of care and effort we expend should reflect that. For example,I would not apply every technique recommended here to a two-page program written just formyself. However, many of the techniques presented here simplify code, so I would use those.13.1.1 ExceptionsThe notion of an exception is provided to help get information from the point where an error isdetected to a point where it can be handled. A function that cannot cope with a problem throws anexception, hoping that its (direct or indirect) caller can handle the problem. A function that wantsto handle a kind of problem indicates that by catching the corresponding exception (§2.4.3.1):• A calling component indicates the kinds of failures that it is willing to handle by specifyingthose exceptions in a catch-clause of a try-block.• A called component that cannot complete its assigned task reports its failure to do so bythrowing an exception using a throw-expression.Consider a simplified and stylized example:void taskmaster(){try {auto result = do_task();// use result}catch (Some_error) {// failure to do_task: handle problem}}int do_task(){// ...if (/* could perform the task */)return result;elsethrow Some_error{};}Section 13.1.1Exceptions345The taskmaster() asks do_task() to do a job.

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

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

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

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