- •Thinking in C++ 2nd edition Volume 2: Standard Libraries & Advanced Topics
- •Preface
- •What’s new in the second edition
- •What’s in Volume 2 of this book
- •How to get Volume 2
- •Prerequisites
- •Learning C++
- •Goals
- •Chapters
- •Exercises
- •Exercise solutions
- •Source code
- •Language standards
- •Language support
- •The book’s CD ROM
- •Seminars, CD Roms & consulting
- •Errors
- •Acknowledgements
- •Library overview
- •1: Strings
- •What’s in a string
- •Creating and initializing C++ strings
- •Initialization limitations
- •Operating on strings
- •Appending, inserting and concatenating strings
- •Replacing string characters
- •Concatenation using non-member overloaded operators
- •Searching in strings
- •Finding in reverse
- •Finding first/last of a set
- •Removing characters from strings
- •Stripping HTML tags
- •Comparing strings
- •Using iterators
- •Iterating in reverse
- •Strings and character traits
- •A string application
- •Summary
- •Exercises
- •2: Iostreams
- •Why iostreams?
- •True wrapping
- •Iostreams to the rescue
- •Sneak preview of operator overloading
- •Inserters and extractors
- •Manipulators
- •Common usage
- •Line-oriented input
- •Overloaded versions of get( )
- •Reading raw bytes
- •Error handling
- •File iostreams
- •Open modes
- •Iostream buffering
- •Seeking in iostreams
- •Creating read/write files
- •User-allocated storage
- •Output strstreams
- •Automatic storage allocation
- •Proving movement
- •A better way
- •Output stream formatting
- •Internal formatting data
- •Format fields
- •Width, fill and precision
- •An exhaustive example
- •Formatting manipulators
- •Manipulators with arguments
- •Creating manipulators
- •Effectors
- •Iostream examples
- •Code generation
- •Maintaining class library source
- •Detecting compiler errors
- •A simple datalogger
- •Generating test data
- •Verifying & viewing the data
- •Counting editor
- •Breaking up big files
- •Summary
- •Exercises
- •3: Templates in depth
- •Nontype template arguments
- •Typedefing a typename
- •Using typename instead of class
- •Function templates
- •A string conversion system
- •A memory allocation system
- •Type induction in function templates
- •Taking the address of a generated function template
- •Local classes in templates
- •Applying a function to an STL sequence
- •Template-templates
- •Member function templates
- •Why virtual member template functions are disallowed
- •Nested template classes
- •Template specializations
- •A practical example
- •Pointer specialization
- •Partial ordering of function templates
- •Design & efficiency
- •Preventing template bloat
- •Explicit instantiation
- •Explicit specification of template functions
- •Controlling template instantiation
- •Template programming idioms
- •Summary
- •Containers and iterators
- •STL reference documentation
- •The Standard Template Library
- •The basic concepts
- •Containers of strings
- •Inheriting from STL containers
- •A plethora of iterators
- •Iterators in reversible containers
- •Iterator categories
- •Input: read-only, one pass
- •Output: write-only, one pass
- •Forward: multiple read/write
- •Bidirectional: operator--
- •Random-access: like a pointer
- •Is this really important?
- •Predefined iterators
- •IO stream iterators
- •Manipulating raw storage
- •Basic sequences: vector, list & deque
- •Basic sequence operations
- •vector
- •Cost of overflowing allocated storage
- •Inserting and erasing elements
- •deque
- •Converting between sequences
- •Cost of overflowing allocated storage
- •Checked random-access
- •list
- •Special list operations
- •list vs. set
- •Swapping all basic sequences
- •Robustness of lists
- •Performance comparison
- •A completely reusable tokenizer
- •stack
- •queue
- •Priority queues
- •Holding bits
- •bitset<n>
- •vector<bool>
- •Associative containers
- •Generators and fillers for associative containers
- •The magic of maps
- •A command-line argument tool
- •Multimaps and duplicate keys
- •Multisets
- •Combining STL containers
- •Creating your own containers
- •Summary
- •Exercises
- •5: STL Algorithms
- •Function objects
- •Classification of function objects
- •Automatic creation of function objects
- •Binders
- •Function pointer adapters
- •SGI extensions
- •A catalog of STL algorithms
- •Support tools for example creation
- •Filling & generating
- •Example
- •Counting
- •Example
- •Manipulating sequences
- •Example
- •Searching & replacing
- •Example
- •Comparing ranges
- •Example
- •Removing elements
- •Example
- •Sorting and operations on sorted ranges
- •Sorting
- •Example
- •Locating elements in sorted ranges
- •Example
- •Merging sorted ranges
- •Example
- •Set operations on sorted ranges
- •Example
- •Heap operations
- •Applying an operation to each element in a range
- •Examples
- •Numeric algorithms
- •Example
- •General utilities
- •Creating your own STL-style algorithms
- •Summary
- •Exercises
- •Perspective
- •Duplicate subobjects
- •Ambiguous upcasting
- •virtual base classes
- •The "most derived" class and virtual base initialization
- •"Tying off" virtual bases with a default constructor
- •Overhead
- •Upcasting
- •Persistence
- •MI-based persistence
- •Improved persistence
- •Avoiding MI
- •Mixin types
- •Repairing an interface
- •Summary
- •Exercises
- •7: Exception handling
- •Error handling in C
- •Throwing an exception
- •Catching an exception
- •The try block
- •Exception handlers
- •Termination vs. resumption
- •The exception specification
- •Better exception specifications?
- •Catching any exception
- •Rethrowing an exception
- •Uncaught exceptions
- •Function-level try blocks
- •Cleaning up
- •Constructors
- •Making everything an object
- •Exception matching
- •Standard exceptions
- •Programming with exceptions
- •When to avoid exceptions
- •Not for asynchronous events
- •Not for ordinary error conditions
- •Not for flow-of-control
- •You’re not forced to use exceptions
- •New exceptions, old code
- •Typical uses of exceptions
- •Always use exception specifications
- •Start with standard exceptions
- •Nest your own exceptions
- •Use exception hierarchies
- •Multiple inheritance
- •Catch by reference, not by value
- •Throw exceptions in constructors
- •Don’t cause exceptions in destructors
- •Avoid naked pointers
- •Overhead
- •Summary
- •Exercises
- •8: Run-time type identification
- •The “Shape” example
- •What is RTTI?
- •Two syntaxes for RTTI
- •Syntax specifics
- •Producing the proper type name
- •Nonpolymorphic types
- •Casting to intermediate levels
- •void pointers
- •Using RTTI with templates
- •References
- •Exceptions
- •Multiple inheritance
- •Sensible uses for RTTI
- •Revisiting the trash recycler
- •Mechanism & overhead of RTTI
- •Creating your own RTTI
- •Explicit cast syntax
- •Summary
- •Exercises
- •9: Building stable systems
- •Shared objects & reference counting
- •Reference-counted class hierarchies
- •Finding memory leaks
- •An extended canonical form
- •Exercises
- •10: Design patterns
- •The pattern concept
- •The singleton
- •Variations on singleton
- •Classifying patterns
- •Features, idioms, patterns
- •Basic complexity hiding
- •Factories: encapsulating object creation
- •Polymorphic factories
- •Abstract factories
- •Virtual constructors
- •Destructor operation
- •Callbacks
- •Observer
- •The “interface” idiom
- •The “inner class” idiom
- •The observer example
- •Multiple dispatching
- •Visitor, a type of multiple dispatching
- •Efficiency
- •Flyweight
- •The composite
- •Evolving a design: the trash recycler
- •Improving the design
- •“Make more objects”
- •A pattern for prototyping creation
- •Trash subclasses
- •Parsing Trash from an external file
- •Recycling with prototyping
- •Abstracting usage
- •Applying double dispatching
- •Implementing the double dispatch
- •Applying the visitor pattern
- •More coupling?
- •RTTI considered harmful?
- •Summary
- •Exercises
- •11: Tools & topics
- •The code extractor
- •Debugging
- •Trace macros
- •Trace file
- •Abstract base class for debugging
- •Tracking new/delete & malloc/free
- •CGI programming in C++
- •Encoding data for CGI
- •The CGI parser
- •Testing the CGI parser
- •Using POST
- •Handling mailing lists
- •Maintaining your list
- •Mailing to your list
- •A general information-extraction CGI program
- •Parsing the data files
- •Summary
- •Exercises
- •General C++
- •My own list of books
- •Depth & dark corners
- •Design Patterns
- •Index
Thinking in C++ 2nd edition Volume 2: Standard Libraries & Advanced Topics
To be informed of future releases of this document and other information about objectoriented books, documents, seminars and CDs, subscribe to my free newsletter. Just send any email to: join-eckel-oo-programming@earth.lyris.net
________________________________________________________________________
“This book is a tremendous achievement. You owe it to yourself to have a copy on your shelf. The chapter on iostreams is the most comprehensive and understandable treatment of that subject I’ve seen to date.”
Al Stevens Contributing Editor, Doctor Dobbs Journal
“Eckel’s book is the only one to so clearly explain how to rethink program construction for object orientation. That the book is also an excellent tutorial on the ins and outs of C++ is an added bonus.”
Andrew Binstock Editor, Unix Review
“Bruce continues to amaze me with his insight into C++, and Thinking in C++ is his best collection of ideas yet. If you want clear answers to difficult questions about C++, buy this outstanding book.”
Gary Entsminger Author, 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++
2nd Edition, Volume 2
Bruce Eckel
President, MindView Inc.
© 1999 by Bruce Eckel, 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 author, 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.
dedication
To the scholar, the healer, and the muse
What’s inside...
Thinking in C++ 2nd edition Volume 2: Standard Libraries & Advanced Topics Revision 1, xx 1999
............................................................ |
1 |
|
|
|
|
|
|
Preface |
13 |
|
|
What’s new in the second edition13 |
|
|
|
What’s in Volume 2 of this book ...... |
14 |
|
|
How to get Volume 2 ........................ |
14 |
|
|
Prerequisites............................... |
14 |
|
|
Learning C++............................. |
14 |
|
|
Goals .......................................... |
16 |
|
|
Chapters ..................................... |
17 |
|
|
Exercises .................................... |
18 |
|
|
Exercise solutions ............................. |
18 |
|
|
Source code................................ |
18 |
|
|
Language standards.................... |
20 |
|
|
Language support.............................. |
20 |
|
|
The book’s CD ROM ................. |
20 |
|
|
Seminars, CD Roms & consulting20 |
|
|
|
Errors ......................................... |
21 |
|
|
Acknowledgements.................... |
21 |
|
|
|
|
23 |
|
Part 1: The Standard C++ Library |
|
||
Library overview........................ |
24 |
|
|
|
|
|
|
1: Strings |
27 |
|
|
What’s in a string ....................... |
27 |
|
|
Creating and initializing C++ strings 29 |
|
|
|
Operating on strings................... |
31 |
|
|
Appending, inserting and concatenating strings 32 |
|
|
|
Replacing string characters ............... |
34 |
|
|
Concatenation using non-member overloaded operators |
37 |
|
|
Searching in strings.................... |
38 |
|
|
Finding in reverse.............................. |
43 |
|
|
Finding first/last of a set.................... |
44 |
|
|
Removing characters from strings..... |
45 |
|
|
Comparing strings............................. |
49 |
|
|
Using iterators................................... |
53 |
|
|
Strings and character traits ................ |
55 |
|
A string application.................... |
58 |
|
Summary.................................... |
61 |
|
Exercises .................................... |
62 |
|
|
|
|
2: Iostreams |
63 |
|
Why iostreams?.......................... |
63 |
|
True wrapping................................... |
65 |
|
Iostreams to the rescue............... |
67 |
|
Sneak preview of operator overloading68 |
|
|
Inserters and extractors ..................... |
69 |
|
Common usage.................................. |
70 |
|
Line-oriented input............................ |
72 |
|
File iostreams............................. |
74 |
|
Open modes ...................................... |
76 |
|
Iostream buffering...................... |
76 |
|
Using get( ) with a streambuf............ |
78 |
|
Seeking in iostreams .................. |
78 |
|
Creating read/write files .................... |
80 |
|
stringstreams .............................. |
81 |
|
strstreams ................................... |
81 |
|
User-allocated storage....................... |
81 |
|
Automatic storage allocation............. |
84 |
|
Output stream formatting........... |
87 |
|
Internal formatting data..................... |
88 |
|
An exhaustive example ..................... |
92 |
|
Formatting manipulators............ |
95 |
|
Manipulators with arguments............ |
96 |
|
Creating manipulators................ |
99 |
|
Effectors.......................................... |
100 |
|
Iostream examples ................... |
102 |
|
Code generation .............................. |
102 |
|
A simple datalogger ........................ |
110 |
|
Counting editor ............................... |
117 |
|
Breaking up big files ....................... |
118 |
|
Summary.................................. |
120 |
|
Exercises .................................. |
120 |
|
|
|
|
3: Templates in depth |
121 |
|
Nontype template arguments ... |
121 |
|
Default template arguments ..... |
122 |
|
The typename keyword............ |
122 |
|
Typedefing a typename................... |
124 |
|
Using typename instead of class ....124 |
|
|
Function templates................... |
124 |
|
A string conversion system ............. |
125 |
|
A memory allocation system........... |
126 |
|
Type induction in function templates |
129 |
Taking the address of a generated function template 130
Chapter 2: Hiding the Implementation |
7 |
Local classes in templates........ |
131 |
|
|
Applying a function to an STL sequence |
131 |
|
|
Template-templates .................. |
134 |
|
|
Member function templates ..... |
135 |
|
|
Why virtual member template functions are disallowed |
137 |
||
Nested template classes................... |
137 |
|
|
Template specializations .......... |
137 |
|
|
Full specialization ........................... |
137 |
|
|
Partial Specialization....................... |
137 |
|
|
A practical example ........................ |
137 |
|
|
Design & efficiency ........................ |
141 |
|
|
Preventing template bloat................ |
141 |
|
|
Explicit instantiation ................ |
143 |
|
|
Explicit specification of template functions |
144 |
|
|
Controlling template instantiation144 |
|
|
|
The inclusion vs. separation models145 |
|
|
|
The export keyword ........................ |
145 |
|
|
Template programming idioms 145 |
|
|
|
The “curiously-recurring template”.145 |
|
|
|
Traits............................................... |
145 |
|
|
Summary.................................. |
145 |
|
|
4: STL Containers & Iterators147
Containers and iterators ........... |
147 |
|
STL reference documentation ......... |
149 |
|
The Standard Template Library 149 |
|
|
The basic concepts ................... |
151 |
|
Containers of strings ................ |
155 |
|
Inheriting from STL containers 157 |
|
|
A plethora of iterators .............. |
159 |
|
Iterators in reversible containers ..... |
161 |
|
Iterator categories............................ |
162 |
|
Predefined iterators ......................... |
163 |
|
Basic sequences: vector, list & deque |
169 |
|
Basic sequence operations............... |
169 |
|
vector ....................................... |
172 |
|
Cost of overflowing allocated storage173 |
|
|
Inserting and erasing elements ........ |
177 |
|
deque........................................ |
179 |
|
Converting between sequences ....... |
181 |
|
Cost of overflowing allocated storage182 |
|
|
Checked random-access .................. |
184 |
|
list ............................................ |
185 |
|
Special list operations ..................... |
187 |
|
Swapping all basic sequences.......... |
191 |
|
Robustness of lists........................... |
192 |
|
Performance comparison ......... |
193 |
|
set............................................. |
198 |
|
Eliminating strtok( )....................... |
199 |
|
StreamTokenizer: a more flexible solution |
201 |
Chapter 2: Hiding the Implementation |
8 |
A completely reusable tokenizer |
..... |
203 |
|
stack ......................................... |
|
208 |
|
queue........................................ |
|
211 |
|
Priority queues ......................... |
|
216 |
|
Holding bits.............................. |
|
226 |
|
bitset<n> ........................................ |
|
226 |
|
vector<bool>.................................. |
|
230 |
|
Associative containers ............. |
|
232 |
|
Generators and fillers for associative containers |
236 |
||
The magic of maps.......................... |
|
239 |
|
Multimaps and duplicate keys......... |
|
244 |
|
Multisets ......................................... |
|
247 |
|
Combining STL containers ...... |
|
250 |
|
Cleaning up containers of pointers253 |
|
||
Creating your own containers .. |
255 |
|
|
Freely-available STL extensions257 |
|
||
Summary.................................. |
|
259 |
|
Exercises .................................. |
|
260 |
|
|
|
|
|
5: STL Algorithms |
263 |
|
|
Function objects....................... |
|
263 |
|
Classification of function objects .... |
264 |
|
|
Automatic creation of function objects265 |
|
||
SGI extensions ................................ |
|
279 |
|
A catalog of STL algorithms.... |
|
285 |
|
Support tools for example creation..287 |
|
||
Filling & generating........................ |
|
291 |
|
Counting ......................................... |
|
293 |
|
Manipulating sequences .................. |
|
294 |
|
Searching & replacing..................... |
|
299 |
|
Comparing ranges ........................... |
|
305 |
|
Removing elements......................... |
|
308 |
|
Sorting and operations on sorted ranges311 |
|
||
Heap operations .............................. |
|
322 |
|
Applying an operation to each element in a range |
323 |
||
Numeric algorithms......................... |
|
331 |
|
General utilities............................... |
|
334 |
|
Creating your own STL-style algorithms |
336 |
||
Summary.................................. |
|
337 |
|
Exercises .................................. |
|
337 |
|
|
|
|
|
Part 2: Advanced Topics |
341 |
|
|
6: Multiple inheritance |
342 |
|
|
Perspective............................... |
|
342 |
|
Duplicate subobjects ................ |
|
344 |
|
Ambiguous upcasting............... |
|
345 |
|
virtual base classes.................. |
|
346 |
|
Chapter 2: Hiding the Implementation |
9 |
The "most derived" class and virtual base initialization |
348 |
|
"Tying off" virtual bases with a default constructor 349 |
|
|
Overhead.................................. |
351 |
|
Upcasting ................................. |
352 |
|
Persistence ...................................... |
355 |
|
Avoiding MI............................. |
362 |
|
Repairing an interface .............. |
362 |
|
Summary.................................. |
367 |
|
Exercises .................................. |
368 |
|
|
|
|
7: Exception handling |
369 |
|
Error handling in C .................. |
369 |
|
Throwing an exception ............ |
372 |
|
Catching an exception.............. |
373 |
|
The try block .................................. |
373 |
|
Exception handlers.......................... |
373 |
|
The exception specification............. |
374 |
|
Better exception specifications?...... |
377 |
|
Catching any exception ................... |
377 |
|
Rethrowing an exception................. |
378 |
|
Uncaught exceptions ....................... |
378 |
|
Function-level try blocks................. |
380 |
|
Cleaning up .............................. |
380 |
|
Constructors ............................. |
384 |
|
Making everything an object........... |
386 |
|
Exception matching ................. |
388 |
|
Standard exceptions ................. |
390 |
|
Programming with exceptions . 391 |
|
|
When to avoid exceptions ............... |
391 |
|
Typical uses of exceptions .............. |
392 |
|
Overhead.................................. |
396 |
|
Summary.................................. |
397 |
|
Exercises .................................. |
397 |
|
|
|
|
8: Run-time type identification399 |
|
|
The “Shape” example .............. |
399 |
|
What is RTTI?.......................... |
400 |
|
Two syntaxes for RTTI ................... |
400 |
|
Syntax specifics ....................... |
404 |
|
typeid( ) with built-in types ............ |
404 |
|
Producing the proper type name...... |
405 |
|
Nonpolymorphic types .................... |
405 |
|
Casting to intermediate levels ......... |
406 |
|
void pointers ................................... |
408 |
|
Using RTTI with templates ............. |
408 |
|
References................................ |
409 |
|
Exceptions....................................... |
410 |
|
Multiple inheritance ................. |
411 |
|
Chapter 2: Hiding the Implementation |
10 |
Sensible uses for RTTI............. |
412 |
Revisiting the trash recycler ............ |
413 |
Mechanism & overhead of RTTI416 |
|
Creating your own RTTI.......... |
416 |
Explicit cast syntax .................. |
420 |
Summary.................................. |
421 |
Exercises .................................. |
422 |
9: Building stable systems |
423 |
|
|
|
Shared objects & reference counting |
423 |
|
||
Reference-counted class hierarchies423 |
|
|
||
The canonical object & singly-rooted hierarchies |
423 |
|||
An extended canonical form............ |
|
424 |
|
|
Design by contract ................... |
|
424 |
|
|
Integrated unit testing .............. |
|
424 |
|
|
Dynamic aggregation ............... |
|
424 |
|
|
Exercises .................................. |
|
428 |
|
|
|
|
|
|
|
10: Design patterns |
429 |
|
|
|
The pattern concept.................. |
|
429 |
|
|
The singleton................................... |
|
430 |
|
|
Classifying patterns.................. |
|
434 |
|
|
Features, idioms, patterns................ |
|
435 |
|
|
Basic complexity hiding.................. |
|
435 |
|
|
Factories: encapsulating object creation |
436 |
|
||
Polymorphic factories ..................... |
|
438 |
|
|
Abstract factories ............................ |
|
441 |
|
|
Virtual constructors......................... |
|
444 |
|
|
Callbacks.................................. |
|
449 |
|
|
Functor/Command .......................... |
|
450 |
|
|
Strategy........................................... |
|
450 |
|
|
Observer.......................................... |
|
450 |
|
|
Multiple dispatching ................ |
|
459 |
|
|
Visitor, a type of multiple dispatching463 |
|
|
||
Efficiency................................. |
|
466 |
|
|
Flyweight ........................................ |
|
466 |
|
|
The composite.......................... |
|
466 |
|
|
Evolving a design: the trash recycler |
466 |
|
||
Improving the design ............... |
|
471 |
|
|
“Make more objects”....................... |
|
471 |
|
|
A pattern for prototyping creation |
...476 |
|
|
|
Abstracting usage..................... |
|
488 |
|
|
Applying double dispatching ... |
|
492 |
|
|
Implementing the double dispatch... |
492 |
|
|
|
Applying the visitor pattern ..... |
|
497 |
|
|
RTTI considered harmful? ....... |
|
503 |
|
|
Summary.................................. |
|
506 |
|
|
Chapter 2: Hiding the Implementation |
11 |
Exercises .................................. |
|
507 |
11: Tools & topics |
509 |
|
The code extractor ................... |
|
509 |
Debugging................................ |
|
531 |
assert( )........................................... |
|
531 |
Trace macros................................... |
|
531 |
Trace file......................................... |
|
532 |
Abstract base class for debugging |
...533 |
|
Tracking new/delete & malloc/free533 |
||
CGI programming in C++........ |
|
539 |
Encoding data for CGI .................... |
|
540 |
The CGI parser................................ |
|
541 |
Using POST .................................... |
|
548 |
Handling mailing lists ..................... |
|
549 |
A general information-extraction |
CGI program 560 |
|
Parsing the data files ....................... |
|
566 |
Summary.................................. |
|
573 |
Exercises .................................. |
|
573 |
A: Recommended reading 575 |
||
C............................................... |
|
575 |
General C++............................. |
|
575 |
My own list of books....................... |
|
576 |
Depth & dark corners............... |
|
576 |
The STL................................... |
|
576 |
Design Patterns ........................ |
|
576 |
B:Compiler specifics |
577 |
|
Index |
580 |
Chapter 2: Hiding the Implementation |
12 |