Bruce Eckel - Thinking In C++. Volume 2 - Practical Programming

Здесь есть возможность читать онлайн «Bruce Eckel - Thinking In C++. Volume 2 - Practical Programming» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Год выпуска: 2003, ISBN: 2003, Издательство: Prentice Hall, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Thinking In C++. Volume 2: Practical Programming: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Thinking In C++. Volume 2: Practical Programming»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Best selling author Bruce Eckel has joined forces with Chuck Allison to write
, the sequel to the highly received and best selling
. Eckel is the master of teaching professional programmers how to quickly learn cutting edge topics in C++ that are glossed over in other C++ books. In
, the authors cover the finer points of exception handling, defensive programming and string and stream processing that every C++ programmer needs to know. Special attention is given to generic programming where the authors reveal little known techniques for effectively using the Standard Template Library. In addition, Eckel and Allison demonstrate how to apply RTTI, design patterns and concurrent programming techniques to improve the quality of industrial strength C++ applications. This book is targeted at programmers of all levels of experience who want to master C++.

Thinking In C++. Volume 2: Practical Programming — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Thinking In C++. Volume 2: Practical Programming», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Don’t cause exceptions in destructors

Because destructors are called in the process of throwing other exceptions, you’ll never want to throw an exception in a destructor or cause another exception to be thrown by some action you perform in the destructor. If this happens, a new exception can be thrown before the catch-clause for an existing exception is reached, which will cause a call to terminate( ) .

If you call any functions inside a destructor that can throw exceptions, those calls should be within a tryblock in the destructor, and the destructor must handle all exceptions itself. None must escape from the destructor .

Avoid naked pointers

See Wrapped.cppearlier in this chapter. A naked pointer usually means vulnerability in the constructor if resources are allocated for that pointer. A pointer doesn’t have a destructor, so those resources aren’t released if an exception is thrown in the constructor. Use auto_ptrfor pointers that reference heap memory .

Overhead

When an exception is thrown, there’s considerable runtime overhead (but it’s good overhead , since objects are cleaned up automatically!). For this reason, you never want to use exceptions as part of your normal flow-of-control, no matter how tempting and clever it may seem. Exceptions should occur only rarely, so the overhead is piled on the exception and not on the normally executing code. One of the important design goals for exception handling was that it could be implemented with no impact on execution speed when it wasn’t used; that is, as long as you don’t throw an exception, your code runs as fast as it would without exception handling. Whether this is actually true depends on the particular compiler implementation you’re using. (See the description of the "zero-cost model" later in this section.) .

You can think of a throwexpression as a call to a special system function that takes the exception object as an argument and backtracks up the chain of execution. For this to work, extra information needs to be put on the stack by the compiler, to aid in stack unwinding. To understand this, you need to know about the runtime stack. Whenever a function is called, information about that function is pushed onto the runtime stack in an activation record instance (ARI), also called a stack frame . A typical stack frame contains the address of the calling function (so execution can return to it), a pointer to the ARI of the function’s static parent (the scope that lexically contains the called function, so variables global to the function can be accessed), and a pointer to the function that called it (its dynamic parent ). The path that logically results from repetitively following the dynamic parent links is the dynamic chain , or call chain , that we’ve mentioned previously in this chapter. This is how execution can backtrack when an exception is thrown, and it is the mechanism that makes it possible for components developed without knowledge of one another to communicate errors at runtime .

To enable stack unwinding for exception handling, extra exception-related information about each function needs to be available for each stack frame. This information describes which destructors need to be called (so that local objects can be cleaned up), indicates whether the current function has a tryblock, and lists which exceptions the associated catch clauses can handle. Naturally there is space penalty for this extra information, so programs that support exception handling can be somewhat larger than those that don’t. [9] This depends, of course, on how much checking of return codes you would have to insert if you weren’t using exceptions. Even the compile-time size of programs using exception handling is greater, since the logic of how to generate the expanded stack frames during runtime must be generated by the compiler .

To illustrate this, we compiled the following program both with and without exception-handling support in Borland C++ Builder and Microsoft Visual C++ [10] Borland enables exceptions by default; to disable exceptions use the -x - compiler option. Microsoft disables support by default; to turn it on, use the -GX option. With both compilers use the -c option to compile only. .

struct HasDestructor {

~HasDestructor(){}

};

void g(); // for all we know, g may throw

void f() {

HasDestructor h;

g();

}

If exception handling is enabled, the compiler must keep information about ~HasDestructor( )available at runtime in the ARI for f( )(so it can destroy hproperly should g( )throw an exception). The following table summarizes the result of the compilations in terms of the size of the compiled (.obj) files (in bytes) .

Compiler\Mode With Exception Support Without Exception Support
Borland 616 234
Microsoft 1162 680

Don’t take the percentage differences between the two modes too seriously. Remember that exceptions (should) typically constitute a small part of a program, so the space overhead tends to be much smaller (usually between 5 and 15 percent).

You might think that this extra housekeeping would slow down execution, and you’d be correct. A clever compiler implementation can avoid that cost, however. Since information about exception-handling code and the offsets of local objects can be computed once at compile time, such information can be kept in a single place associated with each function, but not in each ARI. You essentially remove exception overhead from each ARI and, therefore, avoid the extra time to push them onto the stack. This approach is called the zero-cost model [11] The GNU C++ compiler uses the zero-cost model by default. Metrowerks Code Warrior for C++ also has an option to use the zero-cost model. of exception handling, and the optimized storage mentioned earlier is known as the shadow stack . [12] Thanks to Scott Meyers and Josee Lajoie for their insights on the zero-cost model. You can find more information on how exceptions work in Josee’s excellent article, "Exception Handling: Behind the Scenes," C++ Gems , SIGS, 1996.

Summary

Error recovery is a fundamental concern for every program you write, and it’s especially important in C++, in which one of the goals is to create program components for others to use. To create a robust system, each component must be robust .

The goals for exception handling in C++ are to simplify the creation of large, reliable programs using less code than currently possible, with more confidence that your application doesn’t have an unhandled error. This is accomplished with little or no performance penalty and with low impact on existing code .

Basic exceptions are not terribly difficult to learn; begin using them in your programs as soon as you can. Exceptions are one of those features that provide immediate and significant benefits to your project .

Exercises

4. Create a class with member functions that throw exceptions. Within this class, make a nested class to use as an exception object. It takes a single char*as its argument; this represents a description string. Create a member function that throws this exception. (State this in the function’s exception specification.) Write a tryblock that calls this function and a catchclause that handles the exception by displaying its description string.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Thinking In C++. Volume 2: Practical Programming»

Представляем Вашему вниманию похожие книги на «Thinking In C++. Volume 2: Practical Programming» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Thinking In C++. Volume 2: Practical Programming»

Обсуждение, отзывы о книге «Thinking In C++. Volume 2: Practical Programming» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x