1 z 516
Note: This document requires the installation of the fonts Georgia, Verdana and Andale Mono
(code font) for proper viewing. These can be found at:
/>Revision 19—(August 23, 2003)
Finished Chapter 11, which is now going through review and copyediting. Modified a number of
examples throughout the book so that they will compile with Linux g++ (basically fixing case-
sensitive naming issues).
Revision 18—(August 2, 2003)
Chapter 5 is complete. Chapter 11 is updated and is near completion. Updated the front matter
and index entries. Home stretch now.
Revision 17—(July 8, 2003)
Chapters 5 and 11 are 90% done!
Revision 16—(June 25, 2003)
Chapter 5 text is almost complete, but enough is added to justify a separate posting. The example
programs for Chapter 11 are also fairly complete. Added a matrix multiplication example to the
valarray material in chapter 7. Chapter 7 has been tech-edited. Many corrections due to
comments from users have been integrated into the text (thanks!).
Revision 15—(March 1 ,2003)
Fixed an omission in C10:CuriousSingleton.cpp. Chapters 9 and 10 have been tech-edited.
Revision 14—(January ,2003)
Fixed a number of fuzzy explanations in response to reader feedback (thanks!). Chapter 9 has
been copy-edited.
Revision 13—(December 31, 2002)
Updated the exercises for Chapter 7. Finished rewriting Chapter 9. Added a template variation of
Singleton to chapter 10. Updated the build directives. Fixed lots of stuff. Chapters 5 and 11 still
await rewrite.
Revision 12—(December 23, 2002)
Added material on Design Patterns as Chapter 10 (Concurrency will move to Chapter 11). Added
exercises for Chapter 6. Here is the status of all chapters:
100% complete: 1-4, 6, 8
Copy-edited, waiting for tech edit: 7, 10
z Reordered the material in Chapter 1:
{ Placed exception specifications last, and warned of their dangers with
template classes
{ Added a section on Exception Safety.
{ Added material on auto_ptr
{ Added material illustratin
g
b
ad_exce
p
tion
3 z 516
g
p
{ Explained the internal implementation of exceptions and the Zero-cost
Model
z Merged Chapter 3 (Debugging) into Chapter 2:
{ Added material on invariants, assertions and Design-by-contract
{ Placed the TestSuite in its own namespace
{ Finished the MemCheck system for tracking memory errors
z Removed Chapter 11 (Design Patterns)
{ Will be replaced by Chapter 10 (Concurrent Programming)
Revision 4, August 19, 2001
z Restructured the book; this is the first version with Chuck Allison coauthoring.
Incorporated Chuck's testing framework, which will be used throughout the book and
automatically included as part of the book's build process in the makefiles.
z In the code subdirectory of the unpacked distribution, you can now use make to
compile for Borland, Microsoft, Gnu g++2.95 (distributed with Cygwin) and Gnu
g++3.0 (tested under Linux).
z Under Windows98/NT/2000, you will get best results running under the free Cygwin
The Tao of Objects
“Thinking in C++ patiently and methodically explores the issues of when and how to use inlines,
references, operator overloading, inheritance and dynamic objects, as well as advanced topics
such as the proper use of templates, exceptions and multiple inheritance. The entire effort is
woven in a fabric that includes Eckel’s own philosophy of object and program design. A must for
every C++ developer’s bookshelf, Thinking in C++ is the one C++ book you must have if you’re
doing serious development with C++.”
Richard Hale Shaw
Contributing Editor, PC Magazine
Thinking
In
C++
Volume 2: Practical Programming
Bruce Eckel, President, MindView, Inc.
Chuck Allison, Utah Valley State College©2004 MindView, Inc.
The information in this book is distributed on an “as is” basis, without warranty. While every
precaution has been taken in the preparation of this book, neither the author nor the publisher
shall have any liability to any person or entitle with respect to any liability, loss or damage caused
or alleged to be caused directly or indirectly by instructions contained in this book or by the
computer software or hardware products described herein.
All rights reserved. No part of this book may be reproduced in any form or by any electronic or mechanical means
including information storage and retrieval systems without permission in writing from the publisher or authors,
except by a reviewer who may quote brief passages in a review. Any of the names used in the examples and text of
this book are fictional; any relationship to persons living or dead or to fictional characters in other works is purely
coincidental.
Resource management 47
Making everything an object 49
auto_ptr 52
Function-level try blocks 53
Standard exceptions 55
Exception specifications 58
Better exception specifications? 64
Exception specifications and inheritance 64
When not to use exception specifications 66
Exception safety 66
Programming with exceptions 71
When to avoid exceptions 71
Typical uses of exceptions. 73
Overhead 77
Summary 79
Exercises 80
2: Defensive programming 83
Assertions 86
A simple unit test framework 90
6 z 516
Automated testing 92
The TestSuite Framework 97
Test suites 101
The test framework code. 102
Debugging techniques 110
Trace macros 110
Trace file 111
Finding memory leaks 112
Summary 119
Exercises 120
Input string streams 203
Output string streams 205
Output stream formatting 209
Format flags 209
Format fields 211
Width, fill, and precision 213
An exhaustive example 214
Manipulators 218
Manipulators with arguments 219
Creating manipulators 223
7 z 516
Effectors 224
Iostream examples 227
Maintaining class library source code 227
Detecting compiler errors 232
A simple datalogger 235
Internationalization 240
Wide Streams 240
Locales 243
Summary 246
Exercises 246
5: Templates in depth 251
Template parameters 251
Non-type template parameters 252
Default template arguments 254
Template template parameters 256
The typename keyword 263
Using the template keyword as a hint 266
Member Templates 268
Function template issues 271
Algorithm complexity 364
Function objects 365
8 z 516
Classification of function objects 367
Automatic creation of function objects 368
Adaptable function objects 372
More function object examples 374
Function pointer adapters 383
Writing your own function object adapters 390
A catalog of STL algorithms 394
Support tools for example creation 397
Filling and generating 401
Counting 403
Manipulating sequences 404
Searching and replacing 410
Comparing ranges 419
Removing elements 423
Sorting and operations on sorted ranges 427
Heap operations 438
Applying an operation to each element in a range 440
Numeric algorithms 449
General utilities 453
Creating your own STL-style algorithms 455
Summary 457
Exercises 457
7: Generic containers 465
Containers and iterators 465
STL reference documentation 467
A first look 468
Containers of strings 474
STL extensions 579
Non-STL containers 581
Summary 586
Exercises 587
Special Topics 591
8: Runtime type identification 593
Runtime casts 593
The typeid operator 599
Casting to intermediate levels 602
void pointers 603
Using RTTI with templates 604
Multiple inheritance 605
Sensible uses for RTTI 606
A trash recycler 607
Mechanism and overhead of RTTI 612
Summary 613
Exercises 614
9: Multiple inheritance 615
Perspective 615
Interface inheritance 617
Implementation inheritance 621
Duplicate subobjects 628
Virtual base classes 633
Name lookup issues 643
Avoiding MI 647
Extending an interface 648
Summary 653
Exercises 653
10: Design patterns 655
The pattern concept 655
Controlling access 738
Simplified coding with Guards 740
Thread local storage 744
Terminating tasks 747
Preventing iostream collision 747
The Ornamental Garden 748
Terminating when blocked 754
Interruption 755
Cooperation between threads 761
Wait and signal 762
Producer-Consumer relationships 767
Solving Threading problems with Queues 770
Broadcast 777
Deadlock 784
Summary 791
Exercises 793
A: Recommended reading 797
General C++ 797
Bruce’s books 798
Chuck’s books 798
In-depth C++ 798
Design Patterns 800
B: Etc 801
Index 809
Preface
In Volume 1 of this book, you learn the fundamentals of C and C++. In
this volume, we look at more advanced features, with an eye towards
developing techniques and ideas that produce robust C++ programs.
11 z 516
that isn’t compiled and tested is probably broken, so in this volume we’ve instrumented the
examples with test code. In addition, the code that you can download from
has been extracted directly from the text of the book using
programs that also automatically create makefiles to compile and run the tests. This way
we know that the code in the book is correct.
Chapters
Here is a brief description of the chapters contained in this book:
Part 1: Building Stable Systems
1. Exception handling. Error handling has always been a problem in programming. Even if you
dutifully return error information or set a flag, the function caller may simply ignore it. Exception
handling is a primary feature in C++ that solves this problem by allowing you to “throw” an object
out of your function when a critical error happens. You throw different types of objects for
different errors, and the function caller “catches” these objects in separate error handling
routines. If you throw an exception, it cannot be ignored, so you can guarantee that something
will happen in response to your error. The decision to use exceptions (a good one!) affects code
design in fundamental ways.
Comment
2. Defensive Programming. Many software problems can be prevented. To program
defensively is to craft code in such a way that bugs can be found and fixed early before they have a
chance to do damage in the field. The use of assertions is the single most important thing you can
do to validate your code during development, while at the same time leaving an executable
documentation trail in your code that reveals what you were thinking when you wrote the code in
the first place. Before you let your code out of your hands it should be rigorously tested. A
12 z 516
framework for automated unit testing is an indispensable tool for successful, everyday software
development.
Part 2: The Standard C++ Library
3. Strings in Depth. Text processing is the most common programming activity by far. The C++
string class relieves the programmer from memory management issues, while at the same time
delivering a powerhouse of text processing capability. C++ also supports the use of wide
pointer; often this information allows you to perform a special-case operation more efficiently.
This chapter explains what RTTI is for and how to use it.
Comment
9. Multiple inheritance. This sounds simple at first: A new class is inherited from more than
one existing class. However, you can end up with ambiguities and multiple copies of base-class
objects. That problem is solved with virtual base classes, but the bigger issue remains: When do
you use it? Multiple inheritance is only essential when you need to manipulate an object through
more than one common base class. This chapter explains the syntax for multiple inheritance, and
shows alternative approaches—in particular, how templates solve one common problem. The use
of multiple inheritance to repair a “damaged” class interface is demonstrated as a genuinely
valuable use of this feature.
Comment
13 z 516
10. Design Patterns. The most revolutionary advance in programming since objects is the
introduction of design patterns. A design pattern is a language-independent codification of a
solution to a common programming problem, expressed in such a way that it can apply to many
contexts. Patterns such as Singleton, Factory Method, and Visitor now find their way into daily
discussions around the keyboard. This chapter shows how to implement and use some of the
more useful design patterns in C++.
11. Concurrent Programming. Users have long been used to responsive user interfaces that
(seem to) process multiple tasks simultaneously. Modern operating systems allow processes to
have multiple threads that share the process address space. Multi-threaded programming
requires a different mindset, however, and comes with its own set of “gotchas.” This chapter uses
a freely available library (the ZThread library by Eric Crahen of IBM) to show how to effectively
manage multi-threaded applications in C++.
Exercises
We have discovered that simple exercises are exceptionally useful during a seminar to complete a
student’s understanding, so you’ll find a set at the end of each chapter.
Comment
These are fairly simple, so they can be finished in a reasonable amount of time in a classroom
distribution point is
(and official mirror sites) where it is
14 z 516
freely available. You cannot remove this
copyright and notice. You cannot distribute
modified versions of the source code in this
package. You cannot use this file in printed
media without the express permission of the
author. The authors makes no representation about
the suitability of this software for any purpose.
It is provided "as is" without express or implied
warranty of any kind, including any implied
warranty of merchantability, fitness for a
particular purpose or non-infringement. The entire
risk as to the quality and performance of the
software is with you. The authors and publisher shall not be liable for any damages suffered by you or any
third party as a result of using or distributing software. In no event will the authors or the publisher be liable
for any
lost revenue, profit, or data, or for direct,
indirect, special, consequential, incidental, or
punitive damages, however caused and regardless of
the theory of liability, arising out of the use of
or inability to use software, even if Bruce Eckel
and the publisher have been advised of the
possibility of such damages. Should the software
prove defective, you assume the cost of all
necessary servicing, repair, or correction. If you
think you've found an error, please submit the
correction using the form you will find at
www.MindView.net. (Please use the same
sample program, we have so indicated in comments in the source code.
Comment
Seminars, CD-ROMs & consulting
Bruce Eckel’s company, MindView, Inc., provides public hands-on training seminars based on the
material in this book, and also for advanced topics. Selected material from each chapter
represents a lesson, which is followed by a monitored exercise period so each student receives
personal attention. We also provide on-site training, consulting, mentoring, and design & code
walkthroughs. Information and sign-up forms for upcoming seminars and other contact
information can be found at .
Comment
Errors
No matter how many tricks a writer uses to detect errors, some always creep in and these often
leap off the page for a fresh reader. If you discover anything you believe to be an error, please use
the feedback system built into the electronic version of this book, which you will find at
. The feedback system uses unique identifiers on the paragraphs in
the book, so click on the identifier next to the paragraph that you wish to comment on. Your help
is appreciated.
Comment
About the cover
The cover artwork was painted by Larry O’Brien’s wife, Tina Jensen (yes, the Larry O’Brien who
was the editor of Software Development Magazine for so many years). Not only are the pictures
beautiful, but they are excellent suggestions of polymorphism. The idea for using these images
came from Daniel Will-Harris, the cover designer (www.Will-Harris.com), working with Bruce
Eckel.
Acknowledgements
Volume 2 of this book languished in a half-completed state for a long time while Bruce got
distracted with other things, notably Java, Design Patterns and especially Python (see
www.Python.org). If Chuck hadn’t been willing (foolishly, he has sometimes thought) to finish the
other half and bring things up-to-date, this book almost certainly wouldn’t have happened. There
aren’t that many people whom Bruce would have felt comfortable entrusting this book to. Chuck’s
awaited the invention of computers and desktop publishing. However, we produced the camera-
ready pages ourselves, so the typesetting errors are ours. Microsoft
®
Word XP was used to write
the book and to create camera-ready pages. The body typeface is Georgia and the headlines are in
Verdana. The code type face is Andale Mono.
Comment
We also wish to thank the generous professionals at the Edison Design Group and Dinkumware,
Ltd., for giving us complimentary copies of their compiler and library (respectively). Without their
assistance some of the examples in this book could not have been tested. We also wish to thank
Howard Hinnant and the folks at Metrowerks for a copy of their compiler, and Sandy Smith and
the folks at SlickEdit for keeping Chuck supplied with a world-class editing environment for so
many years. Greg Comeau also provided a copy of his successful EDG-based compiler, Comeau
C++.
A special thanks to all our teachers, and all our students (who are our teachers as well).
Evan Cofsky () provided all sorts of assistance on the server as well as
development of programs in his now-favorite language, Python. Sharlynn Cobaugh and Paula
Steuer were instrumental assistants, preventing Bruce from being washed away in a flood of
projects.
Dawn McGee provided much-appreciated inspiration and enthusiasm during this project. The
supporting cast of friends includes, but is not limited to: Mark Western, Gen Kiyooka, Kraig
Brockschmidt, Zack Urlocker, Andrew Binstock, Neil Rubenking, Steve Sinofsky, JD Hildebrandt,
Brian McElhinney, Brinkley Barr, Bill Gates at Midnight Engineering Magazine, Larry
Constantine & Lucy Lockwood, Tom Keffer, Greg Perry, Dan Putterman, Christi Westphal, Gene
Wang, Dave Mayer, David Intersimone, Claire Sawyers, The Italians (Andrea Provaglio, Laura
Fallai, Marco Cantu, Michael Seaver, Huston Franklin, David Wagstaff, Corrado, Ilsa and
Christina Giustozzi), Chris & Laura Strand, The Almquists, Brad Jerbic, John Kruth & Marilyn
Cvitanic, Holly Payne (yes, the famous novelist!), Mark Mabry, The Robbins Families, The
Moelter Families (& the McMillans), The Wilks, Dave Stoner, Laurie Adams, The Cranstons, Larry
Fogg, Mike & Karen Sequeira, Gary Entsminger & Allison Brody, Chester Andersen, Joe Lordi,
One of the major features in C++ is exception handling, which is a better way of thinking about
and handling errors. With exception handling the following statements apply:
Comment
1. Error-handling code is not nearly so tedious to write, and it doesn't become mixed up with
your "normal" code. You write the code you want to happen; later in a separate section you
write the code to cope with the problems. If you make multiple calls to a function, you
handle the errors from that function once, in one place.
2.
Errors cannot be ignored. If a function needs to send an error message to the caller of that
function, it “throws” an object representing that error out of the function. If the caller
doesn’t “catch” the error and handle it, it goes to the next enclosing dynamic scope, and so
on until the error is either caught or the program terminates because there was no handler
to catch that type of exception.
This chapter examines C’s approach to error handling (such as it is), discusses why it did not work
well for C, and explains why it won’t work at all for C++. This chapter also covers try, throw, and
catch, the C++ keywords that support exception handling.
Comment
Traditional error handling
18 z 516
In most of the examples in these volumes, we use assert( ) as it was intended: for debugging
during development with code that can be disabled with #define NDEBUG for the shipping
product. Runtime error checking uses the require.h functions (assure( ) and require( ))
developed in Chapter 9 in Volume 1. These functions are a convenient way to say, “There’s a
problem here you’ll probably want to handle with some more sophisticated code, but you don’t
need to be distracted by it in this example.” The require.h functions might be enough for small
programs, but for complicated products you might need to write more sophisticated error-
handling code.
Comment
Error handling is quite straightforward in situations in which you know exactly what to do
because you have all the necessary information in that context. Of course, you just handle the
this with setjmp/longjmp:
Comment
//: C01:Nonlocal.cpp
// setjmp() & longjmp()
#include <iostream>
#include <csetjmp>
using namespace std;
class Rainbow {
public:
Rainbow() { cout << "Rainbow()" << endl; }
~Rainbow() { cout << "~Rainbow()" << endl; }
};
jmp_buf kansas;
void oz() {
19 z 516
Rainbow rb;
for(int i = 0; i < 3; i++)
cout << "there's no place like home\n";
longjmp(kansas, 47);
}
int main() {
if(setjmp(kansas) == 0) {
cout << "tornado, witch, munchkins \n";
oz();
} else {
cout << "Auntie Em! "
const char* const data;
public:
MyError(const char* const msg = 0) : data (msg) {}
};
void f() {
// Here we "throw" an exception object:
throw MyError("something bad happened");
}
int main() {
// As you’ll see shortly,
// we’ll want a "try block" here:
f();
[1]
20 z 516
} ///:~
MyError is an ordinary class, which in this case takes a char* as a constructor argument. You
can use any type when you throw (including built-in types), but usually you’ll create special
classes for throwing exceptions.
Comment
The keyword throw causes a number of relatively magical things to happen. First, it creates a
copy of the object you’re throwing and, in effect, “returns” it from the function containing the
throw expression, even though that object type isn’t normally what the function is designed to
return. A naive way to think about exception handling is as an alternate return mechanism
(although you find you can get into trouble if you take the analogy too far). You can also exit from
ordinary scopes by throwing an exception. In any case, a value is returned, and the function or
scope exits.
Comment
after the try block. Thus, your code is a lot easier to write and easier to read because the goal of
the code is not confused with the error checking.
Comment
Exception handlers
Of course, the thrown exception must end up some place. This place is the exception handler, and
you need one exception handler for every exception type you want to catch. Exception handlers
immediately follow the try block and are denoted by the keyword catch:
Comment
try {
21 z 516
// Code that may generate exceptions
} catch(type1 id1) {
// Handle exceptions of type1
} catch(type2 id2) {
// Handle exceptions of type2
} catch(type3 id3)
// Etc
} catch(typeN idN)
// Handle exceptions of typeN
}
// Normal execution resumes here
The syntax of a catch clause resembles functions that take a single argument. The identifier (id1,
id2, and so on) can be used inside the handler, just like a function argument, although you can
omit the identifier if it’s not needed in the handler. The exception type usually gives you enough
information to deal with it.
Comment
The handlers must appear directly after the try block. If an exception is thrown, the exception-
handling mechanism goes hunting for the first handler with an argument that matches the type of
the exception. It then enters that catch clause, and the exception is considered handled. (The
oz();
}
catch (int) {
cout << "Auntie Em! "
<< "I had the strangest dream "
<< endl;
}
} ///:~
22 z 516
When the throw statement in oz( ) executes, program control backtracks until it finds the catch
clause that takes an int parameter, at which point execution resumes with the body of that catch
clause. The most important difference between this program and Nonlocal.cpp is that the
destructor for the object rb is called when the throw statement causes execution to leave the
function oz( ).
Comment
There are two basic models in exception-handling theory: termination and resumption. In
termination (which is what C++ supports), you assume the error is so critical that there’s no way
to automatically resume execution at the point where the exception occurred. In other words,
“whoever” threw the exception decided there was no way to salvage the situation, and they don’t
want to come back.
Comment
The alternative error-handling model is called resumption, first introduced with the PL/I
language in the 1960s. Using resumption semantics means that the exception handler is
expected to do something to rectify the situation, and then the faulting code is automatically
retried, presuming success the second time. If you want resumption in C++, you must explicitly
transfer execution back to the code where the error occurred, usually by repeating the function
call that sent you there in the first place. It is not unusual, therefore, to place your try block inside
a while loop that keeps reentering the try block until the result is satisfactory.
Comment
Except2(const Except1&) {}
};
void f() { throw Except1(); }
[2]
[3]
23 z 516
int main() {
try { f();
} catch (Except2&) {
cout << "inside catch(Except2)" << endl;
} catch (Except1&) {
cout << "inside catch(Except1)" << endl;
}
} ///:~
Even though you might think the first handler could be used by converting an Except1 object into
an Except2 using the constructor conversion, the system will not perform such a conversion
during exception handling, and you’ll end up at the Except1 handler.
Comment
The following example shows how a base-class handler can catch a derived-class exception:
Comment
//: C01:Basexcpt.cpp
// Exception hierarchies
#include <iostream>
using namespace std;
class X {
public:
Catching any exception
Sometimes you want to create a handler that catches any type of exception. You do this using the
ellipsis in the argument list:
Comment
catch( ) {
cout << "an exception was thrown" << endl;
[4]
24 z 516
}
An ellipsis catches any exception, so you’ll want to put it at the end of your list of handlers to avoid
pre-empting any that follow it.
Comment
Because the ellipsis gives you no possibility to have an argument, you can’t know anything about
the exception or its type. It’s a “catchall.” Such a catch clause is often used to clean up some
resources and then rethrow the exception.
Comment
Re-throwing an exception
You usually want to re-throw an exception when you have some resource that needs to be
released, such as a network connection or heap memory that needs to be deallocated. (See the
section “Resource Management” later in this chapter for more detail). If an exception occurs, you
don’t necessarily care what error caused the exception—you just want to close the connection you
opened previously. After that, you’ll want to let some other context closer to the user (that is,
higher up in the call chain) handle the exception. In this case the ellipsis specification is just what
you want. You want to catch any exception, clean up your resource, and then re-throw the
exception so that it can be handled elsewhere. You re-throw an exception by using throw with no
argument inside a handler:
Comment
catch( ) {
cout << "an exception was thrown" << endl;
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
25 z 516
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 void return 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.
Comment
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:
Comment
//: C01:Terminator.cpp
// Use of set_terminate()
// Also shows uncaught exceptions
#include <exception>
#include <iostream>
#include <cstdlib>
using namespace std;
void terminator() {
cout << "I'll be back!" << endl;
exit(0);
}
void (*old_terminate)()
= set_terminate(terminator);
class Botch {
public:
Cleaning up