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

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

Интервал:

Закладка:

Сделать

5. Rewrite the Stash class from Chapter 13 of Volume 1 so that it throws out_of_rangeexceptions for operator[].

6. Write a generic main( )that takes all exceptions and reports them as errors.

7. Create a class with its own operator new. This operator should allocate ten objects, and on the eleventh object "run out of memory" and throw an exception. Also add a staticmember function that reclaims this memory. Now create a main( )with a tryblock and a catchclause that calls the memory-restoration routine. Put these inside a whileloop, to demonstrate recovering from an exception and continuing execution.

8. Create a destructor that throws an exception, and write code to prove to yourself that this is a bad idea by showing that if a new exception is thrown before the handler for the existing one is reached, terminate( )is called.

9. Prove to yourself that all exception objects (the ones that are thrown) are properly destroyed.

10. Prove to yourself that if you create an exception object on the heap and throw the pointer to that object, it will not be cleaned up.

11. Write a function with an exception specification that can throw four exception types: a char, an int, a bool, and your own exception class. Catch each in main( )and verify the catch. Derive your exception class from a standard exception. Write the function in such a way that the system recovers and tries to execute it again.

12. Modify your solution to the exercise 8 to throw a double from the function, violating the exception specification. Catch the violation with your own unexpected handler that displays a message and exits the program gracefully (meaning abort( )is not called).

13. Write a Garageclass that has a Carthat is having troubles with its Motor. Use a function-level tryblock in the Garageclass constructor to catch an exception (thrown from the Motorclass) when its Carobject is initialized. Throw a different exception from the body of the Garageconstructor’s handler and catch it in main( ).

2: Defensive programming

Writing "perfect software" may be an elusive Holy Grail for developers, but a few defensive techniques, routinely applied, can go a long way toward narrowing the gap between code and ideal.

Although the complexity of typical production software guarantees that testers will always have a job, chances are you still yearn to produce defect-free software. (At least we hope you do!) Object-oriented design techniques do much to corral the difficulty of large projects, to be sure. Eventually, however, you have to get down to writing loops and functions. These details of "programming in the small" become the building blocks of the implementation of larger components called for by your design efforts. If your loops are off by one or your functions calculate the correct values only "most" of the time, you’re in deep trouble no matter how fancy your overall methodology. In this chapter, we’re interested in coding practices that keep you on track toward a working solution regardless of the size of your project .

Your code is, among other things, an expression of your attempt to solve a problem. It should be clear to the reader (including yourself) exactly what you were thinking when you designed that loop. At certain points in your program, you should be able to make bold statements that some condition or other holds. (If you can’t, you really haven’t yet solved the problem.) Such statements are called invariants , since they should invariably be true at the point where they appear in the code; if not, either your design is faulty, or your code does not accurately reflect your design. (In other words, you’ve got bugs!) .

To illustrate, consider how to write a program that plays the guessing game of Hi-lo. You play this game by having one person think of a number between 1 and 100, and having the other person guess the number. (We’ll let the computer do the guessing.) The person who holds the number tells the guesser whether their guess is high, low or correct. The best strategy for the guesser is of course binary search , which chooses the midpoint of the range of numbers where the sought-after number resides. The high-low response tells the guesser which half of the list holds the number, and the process repeats, halving the size of the active search range on each iteration. So how do you write a loop to drive the repetition properly? It’s not sufficient to just say .

bool guessed = false;

while (!guessed) {

}

because a malicious user might respond deceitfully, and you could spend all day guessing. What assumption, however simple, are you making each time you guess? In other words, what condition should hold by design on each loop iteration? .

The simple assumption we’re after is, of course, that the secret number is within the current active range of unguessed numbers, beginning with the range [1, 100]. Suppose we label the endpoints of the range with the variables low and high . Each time you pass through the loop you need to make sure that if the number was in the range [ low, high] at the beginning of the loop, you calculate the new range so that it still contains the number at the end of the current loop iteration .

The goal is to express the loop invariant in code so that a violation can be detected at runtime. Unfortunately, since the computer doesn’t know the secret number, you can’t express this condition directly in code, but you can at least make a comment to that effect:

while (!guessed) {

// INVARIANT: the number is in the range [low, high]

}

If we were to stop this thread of discussion right here, we would have accomplished a great deal if it helps clarify how you design loops. Fortunately, we can do better than that. What happens when the user says that a guess is too high when it isn’t or that it’s too low when it in fact is not? The deception will in effect exclude the secret number from the new subrange. Because one lie always leads to another, eventually your range will diminish to nothing (since you shrink it by half each time and the secret number isn’t in there). We can easily express this condition concretely, as the following program illustrates .

//: C02:HiLo.cpp

// Plays the game of Hi-lo to illustrate a loop invariant

#include

#include

#include

using namespace std;

int main() {

cout << "Think of a number between 1 and 100\n";

cout << "I will make a guess; ";

cout << "tell me if I'm (H)igh or (L)ow\n";

int low = 1, high = 100;

bool guessed = false;

while (!guessed) {

// Invariant: the number is in the range [low, high]

if (low > high) { // Invariant violation

cout << "You cheated! I quit\n";

return EXIT_FAILURE;

}

int guess = (low + high) / 2;

cout << "My guess is " << guess << ". ";

cout << "(H)igh, (L)ow, or (E)qual? ";

string response;

cin >> response;

switch(toupper(response[0])) {

case 'H':

high = guess - 1;

break;

case 'L':

low = guess + 1;

break;

case 'E':

guessed = true;

break;

default:

cout << "Invalid response\n";

continue;

}

}

cout << "I got it!\n";

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

Интервал:

Закладка:

Сделать

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