- •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
};
class D1 : public MBase { public:
char* vf() const { return "D1"; }
};
class D2 : public MBase { public:
char* vf() const { return "D2"; }
};
// Causes error: ambiguous override of vf(): //! class MI : public D1, public D2 {};
int main() { vector<MBase*> b; b.push_back(new D1); b.push_back(new D2);
// Cannot upcast: which subobject?: //! b.push_back(new mi);
for(int i = 0; i < b.size(); i++) cout << b[i]->vf() << endl;
purge(b); } ///:~
Two problems occur here. First, you cannot even create the class mi because doing so would cause a clash between the two definitions of vf( ) in D1 and D2.
Second, in the array definition for b[ ] this code attempts to create a new mi and upcast the address to a MBase*. The compiler won’t accept this because it has no way of knowing whether you want to use D1’s subobject MBase or D2’s subobject MBase for the resulting address.
virtual base classes
To solve the first problem, you must explicitly disambiguate the function vf( ) by writing a redefinition in the class mi.
The solution to the second problem is a language extension: The meaning of the virtual keyword is overloaded. If you inherit a base class as virtual, only one subobject of that class will ever appear as a base class. Virtual base classes are implemented by the compiler with pointer magic in a way suggesting the implementation of ordinary virtual functions.
Chapter 15: Multiple Inheritance
346
Because only one subobject of a virtual base class will ever appear during multiple inheritance, there is no ambiguity during upcasting. Here’s an example:
//: C06:MultipleInheritance2.cpp // Virtual base classes
#include "../purge.h" #include <iostream> #include <vector> using namespace std;
class MBase { public:
virtual char* vf() const = 0; virtual ~MBase() {}
};
class D1 : virtual public MBase { public:
char* vf() const { return "D1"; }
};
class D2 : virtual public MBase { public:
char* vf() const { return "D2"; }
};
// MUST explicitly disambiguate vf(): class MI : public D1, public D2 { public:
char* vf() const { return D1::vf();}
};
int main() { vector<MBase*> b; b.push_back(new D1); b.push_back(new D2);
b.push_back(new MI); // OK for(int i = 0; i < b.size(); i++)
cout << b[i]->vf() << endl; purge(b);
} ///:~
The compiler now accepts the upcast, but notice that you must still explicitly disambiguate the function vf( ) in MI; otherwise the compiler wouldn’t know which version to use.
Chapter 15: Multiple Inheritance
347
The "most derived" class and virtual base initialization
The use of virtual base classes isn’t quite as simple as that. The above example uses the (compiler-synthesized) default constructor. If the virtual base has a constructor, things become a bit strange. To understand this, you need a new term: most-derived class.
The most-derived class is the one you’re currently in, and is particularly important when you’re thinking about constructors. In the previous example, MBase is the most-derived class inside the MBase constructor. Inside the D1 constructor, D1 is the most-derived class, and inside the MI constructor, MI is the most-derived class.
When you are using a virtual base class, the most-derived constructor is responsible for initializing that virtual base class. That means any class, no matter how far away it is from the virtual base, is responsible for initializing it. Here’s an example:
//: C06:MultipleInheritance3.cpp
//Virtual base initialization
//Virtual base classes must always be
//Initialized by the "most-derived" class #include "../purge.h"
#include <iostream> #include <vector> using namespace std;
class MBase { public:
MBase(int) {}
virtual char* vf() const = 0; virtual ~MBase() {}
};
class D1 : virtual public MBase { public:
D1() : MBase(1) {}
char* vf() const { return "D1"; }
};
class D2 : virtual public MBase { public:
D2() : MBase(2) {}
char* vf() const { return "D2"; }
};
Chapter 15: Multiple Inheritance
348
class MI : public D1, public D2 { public:
MI() : MBase(3) {} char* vf() const {
return D1::vf(); // MUST disambiguate
}
};
class X : public MI { public:
// You must ALWAYS init the virtual base: X() : MBase(4) {}
};
int main() { vector<MBase*> b; b.push_back(new D1); b.push_back(new D2);
b.push_back(new MI); // OK b.push_back(new X);
for(int i = 0; i < b.size(); i++) cout << b[i]->vf() << endl;
purge(b);
} ///:~
As you would expect, both D1 and D2 must initialize MBase in their constructor. But so must MI and X, even though they are more than one layer away! That’s because each one in turn becomes the most-derived class. The compiler can’t know whether to use D1’s initialization of MBase or to use D2’s version. Thus you are always forced to do it in the most-derived class. Note that only the single selected virtual base constructor is called.
"Tying off" virtual bases with a default constructor
Forcing the most-derived class to initialize a virtual base that may be buried deep in the class hierarchy can seem like a tedious and confusing task to put upon the user of your class. It’s better to make this invisible, which is done by creating a default constructor for the virtual base class, like this:
//: C06:MultipleInheritance4.cpp
//"Tying off" virtual bases
//so you don't have to worry about them
//in derived classes
Chapter 15: Multiple Inheritance
349
#include "../purge.h" #include <iostream> #include <vector> using namespace std;
class MBase { public:
// Default constructor removes responsibility: MBase(int = 0) {}
virtual char* vf() const = 0; virtual ~MBase() {}
};
class D1 : virtual public MBase { public:
D1() : MBase(1) {}
char* vf() const { return "D1"; }
};
class D2 : virtual public MBase { public:
D2() : MBase(2) {}
char* vf() const { return "D2"; }
};
class MI : public D1, public D2 { public:
MI() {} // Calls default constructor for MBase char* vf() const {
return D1::vf(); // MUST disambiguate
}
};
class X : public MI { public:
X() {} // Calls default constructor for MBase
};
int main() { vector<MBase*> b; b.push_back(new D1); b.push_back(new D2);
b.push_back(new MI); // OK
Chapter 15: Multiple Inheritance
350