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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

You can install your own terminate( )function using the standard set_terminate( )function, which returns a pointer to the terminate( )function you are replacing (which will be the default library version the first time you call it), so you can restore it later if you want. Your custom terminate( )must take no arguments and have a voidreturn value. In addition, any terminate( )handler you install must not return or throw an exception, but instead must execute some sort of program-termination logic. If terminate( )is called, the problem is unrecoverable .

The following example shows the use of set_terminate( ). Here, the return value is saved and restored so that the terminate( )function can be used to help isolate the section of code in which the uncaught exception is occurring: .

//: C01:Terminator.cpp

// Use of set_terminate()

// Also shows uncaught exceptions

#include

#include

#include

using namespace std;

void terminator() {

cout << "I'll be back!" << endl;

exit(0);

}

void (*old_terminate)()

= set_terminate(terminator);

class Botch {

public:

class Fruit {};

void f() {

cout << "Botch::f()" << endl;

throw Fruit();

}

~Botch() { throw 'c'; }

};

int main() {

try {

Botch b;

b.f();

} catch(...) {

cout << "inside catch(...)" << endl;

}

} ///:~

The definition of old_terminatelooks a bit confusing at first: it not only creates a pointer to a function, but it initializes that pointer to the return value of set_terminate( ). Even though you might be familiar with seeing a semicolon right after a pointer-to-function declaration, here it’s just another kind of variable and can be initialized when it is defined .

The class Botchnot only throws an exception inside f( ), but also in its destructor. As we explained earlier, this situation causes a call to terminate( ), as you can see in main( ). Even though the exception handler says catch(...), which would seem to catch everything and leave no cause for terminate( )to be called, terminate( )is called anyway. In the process of cleaning up the objects on the stack to handle one exception, the Botchdestructor is called, and that generates a second exception, forcing a call to terminate( ). Thus, a destructor that throws an exception or causes one to be thrown is usually a sign of poor design or sloppy coding .

Cleaning up

Part of the magic of exception handling is that you can pop from normal program flow into the appropriate exception handler. Doing so wouldn’t be useful, however, if things weren’t cleaned up properly as the exception was thrown. C++ exception handling guarantees that as you leave a scope, all objects in that scope whose constructors have been completed will have destructors called .

Here’s an example that demonstrates that constructors that aren’t completed don’t have the associated destructors called. It also shows what happens when an exception is thrown in the middle of the creation of an array of objects: .

//: C01:Cleanup.cpp

// Exceptions clean up complete objects only

#include

using namespace std;

class Trace {

static int counter;

int objid;

public:

Trace() {

objid = counter++;

cout << "constructing Trace #" << objid << endl;

if(objid == 3) throw 3;

}

~Trace() {

cout << "destructing Trace #" << objid << endl;

}

};

int Trace::counter = 0;

int main() {

try {

Trace n1;

// Throws exception:

Trace array[5];

Trace n2; // won't get here

} catch(int i) {

cout << "caught " << i << endl;

}

} ///:~

The class Tracekeeps track of objects so that you can trace program progress. It keeps a count of the number of objects created with a staticdata member counterand tracks the number of the particular object with objid .

The main program creates a single object, n1( objid0), and then attempts to create an array of five Traceobjects, but an exception is thrown before the third object is fully created. The object n2is never created. You can see the results in the output of the program: .

constructing Trace #0

constructing Trace #1

constructing Trace #2

constructing Trace #3

destructing Trace #2

destructing Trace #1

destructing Trace #0

caught 3

Three array elements are successfully created, but in the middle of the constructor for the fourth element, an exception is thrown. Because the fourth construction in main( )(for array[2]) never completes, only the destructors for objects array[1]and array[0]are called. Finally, object n1is destroyed, but not object n2, because it was never created .

Resource management

When writing code with exceptions, it’s particularly important that you always ask, "If an exception occurs, will my resources be properly cleaned up?" Most of the time you’re fairly safe, but in constructors there’s a particular problem: if an exception is thrown before a constructor is completed, the associated destructor will not be called for that object. Thus, you must be especially diligent while writing your constructor .

The general difficulty is allocating resources in constructors. If an exception occurs in the constructor, the destructor doesn’t get a chance to deallocate the resource. This problem occurs most often with "naked" pointers. For example: .

//: C01:Rawp.cpp

// Naked pointers

#include

using namespace std;

class Cat {

public:

Cat() { cout << "Cat()" << endl; }

~Cat() { cout << "~Cat()" << endl; }

};

class Dog {

public:

void* operator new(size_t sz) {

cout << "allocating a Dog" << endl;

throw 47;

}

void operator delete(void* p) {

cout << "deallocating a Dog" << endl;

::operator delete(p);

}

};

class UseResources {

Cat* bp;

Dog* op;

public:

UseResources(int count = 1) {

cout << "UseResources()" << endl;

bp = new Cat[count];

op = new Dog;

}

~UseResources() {

cout << "~UseResources()" << endl;

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

Интервал:

Закладка:

Сделать

Похожие книги на «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