Читаем Thinking In C++. Volume 2: Practical Programming полностью

[3] In fact, you might want to always specify exception objects by const reference in exception handlers. It’s very rare to modify and rethrow an exception. We are not dogmatic about this practice however.

[4] Only unambiguous, accessible base classes can catch derived exceptions. This rule minimizes the runtime overhead needed to validate exceptions. Remember that exceptions are checked at runtime, not at compile time, and therefore the extensive information available at compile time is not available during exception handling.

[5] For more detail on auto_ptr, see Herb Sutter’s article entitled, "Using auto_ptr Effectively" in the October 1999 issue of the C/C++ Users Journal, pp. 63–67.

[6] If you’re interested in a more in-depth analysis of exception safety issues, the definitive reference is Herb Sutter’s Exceptional C++, Addison-Wesley, 2000.

[7] The library function uncaught_exception( ) returns true in the middle of stack unwinding, so technically you can test uncaught_exception( ) for false and let an exception escape from a destructor. We’ve never seen a situation in which this constituted good design, however, so we only mention it in this footnote.

[8] Some compilers do throw exceptions in these cases, but they usually provide a compiler option to disable this (unusual) behavior.

[9] This depends, of course, on how much checking of return codes you would have to insert if you weren’t using exceptions.

[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.

[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.

[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.

[13] Among other things he invented Quicksort.

[14] As quoted in Programming Language Pragmatics, by Michael L. Scott, Morgan-Kaufmann, 2000.

[15] See his book, Object-Oriented Software Construction, Prentice-Hall, 1994.

[16] This is still an assertion conceptually, but since we don’t want to halt execution, the assert( ) macro is not appropriate. Java 1.4, for example, throws an exception when an assertion fails.

[17] There is a nice phrase to help remember this phenomenon: "Require no more; promise no less," first coined in C++ FAQs, by Marshall Cline and Greg Lomow (Addison-Wesley, 1994). Since pre-conditions can weaken in derived classes, we say that they are contravariant, and, conversely, post-conditions are covariant (which explains why we mentioned the covariance of exception specifications in Chapter 1).

[18] This section is based on Chuck’s article, "The Simplest Automated Unit Test Framework That Could Possibly Work", C/C++ Users Journal, Sept. 2000.

[19] A good book on this subject is Martin Fowler's Refactoring: Improving the Design of Existing Code (Addison-Wesley, 2000). See also www.refactoring.com. Refactoring is a crucial practice of Extreme Programming (XP).

[20] Lightweight methodologies such as XP have "joined forces" in the Agile Alliance (see http://www.agilealliance.org/home).

[21] Our Date class is also "internationalized", in that it supports wide character sets. This is introduced at the end of the next chapter.

[22] See http://sourceforge.net/projects/cppunit for more information.

[23] "Runtime Type Identification", discussed in chapter 9. Specifically, we use the name( ) member function of the typeinfo class. By the way, if you're using Microsoft Visual C++, you need to specify the compile option /GR. If you don't, you'll get an access violation at runtime.

[24] In particular, we use stringizing (via the # operator) and the predefined macros __FILE__ and __LINE__. See the code later in the chapter.

[25] Batch files and shell scripts work well for this, of course. The Suite class is a C++-based way of organizing related tests.

[26] Our key technical reviewer, Pete Becker of Dinkumware. Ltd., brought to our attention that it is illegal to use macros to replace C++ keywords. His take on this technique was as follows: ""This is a dirty trick. Dirty tricks are sometimes necessary to figure out why code isn't working, so you may want to keep this in your toolbox, but don't ship any code with it." Caveat programmer :-).

Перейти на страницу:

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных