- •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
//:! C10:POSTtest.html <HTML><HEAD>
<TITLE>A test of standard HTML POST</TITLE> </HEAD>Test, uses standard html POST
<Form method="POST" ACTION="/cgi-bin/CGI_POST.exe"> <P>Field1: <INPUT TYPE = "text" NAME = "Field1" VALUE = "This is a test" size = "40"></p> <P>Field2: <INPUT TYPE = "text" NAME = "Field2" VALUE = "of the emergency" size = "40"></p> <P>Field3: <INPUT TYPE = "text" NAME = "Field3" VALUE = "broadcast system" size = "40"></p> <P>Field4: <INPUT TYPE = "text" NAME = "Field4" VALUE = "this is only a test" size = "40"></p> <P>Field5: <INPUT TYPE = "text" NAME = "Field5" VALUE = "In a real emergency" size = "40"></p> <P>Field6: <INPUT TYPE = "text" NAME = "Field6" VALUE = "you will be instructed" size = "40"></p> <p><input type = "submit" name = "submit" > </p> </Form></HTML>
///:~
When you press the “submit” button, you’ll get back a simple text page containing the parsed results, so you can see that the CGI program works correctly. The server turns around and feeds the query string to the CGI program via standard input.
Handling mailing lists
Managing an email list is the kind of problem many people need to solve for their Web site. As it is turning out to be the case for everything on the Internet, the simplest approach is always the best. I learned this the hard way, first trying a variety of Java applets (which some firewalls do not allow) and even JavaScript (which isn’t supported uniformly on all browsers). The result of each experiment was a steady stream of email from the folks who couldn’t get it to work. When you set up a Web site, your goal should be to never get email from anyone complaining that it doesn’t work, and the best way to produce this result is to use plain HTML (which, with a little work, can be made to look quite decent).
The second problem was on the server side. Ideally, you’d like all your email addresses to be added and removed from a single master file, but this presents a problem. Most operating systems allow more than one program to open a file. When a client makes a CGI request, the Web server starts up a new invocation of the CGI program, and since a Web server can handle many requests at a time, this means that you can have many instances of your CGI program running at once. If the CGI program opens a specific file, then you can have many programs running at once that open that file. This is a problem if they are each reading and writing to that file.
Appendix B: Programming Guidelines
549
There may be a function for your operating system that “locks” a file, so that other invocations of your program do not access the file at the same time. However, I took a different approach, which was to make a unique file for each client. Making a file unique was quite easy, since the email name itself is a unique character string. The filename for each request is then just the email name, followed by the string “.add” or “.remove”. The contents of the file is also the email address of the client. Then, to produce a list of all the names to add, you simply say something like (in Unix):
cat *.add > addlist
(or the equivalent for your system). For removals, you say:
cat *.remove > removelist
Once the names have been combined into a list you can archive or remove the files.
The HTML code to place on your Web page becomes fairly straightforward. This particular example takes an email address to be added or removed from my C++ mailing list:
<h1 align="center"><font color="#000000"> The C++ Mailing List</font></h1>
<div align="center"><center>
<table border="1" cellpadding="4" cellspacing="1" width="550" bgcolor="#FFFFFF">
<tr>
<td width="30" bgcolor="#FF0000"> </td> <td align="center" width="422" bgcolor="#0"> <form action="/cgi-bin/mlm.exe" method="GET"> <input type="hidden" name="subject-field" value="cplusplus-email-list">
<input type="hidden" name="command-field" value="add"><p>
<input type="text" size="40" name="email-address">
<input type="submit" name="submit" value="Add Address to C++ Mailing List"> </p></form></td>
<td width="30" bgcolor="#FF0000"> </td> </tr>
<tr>
<td width="30" bgcolor="#000000"> </td> <td align="center" width="422" bgcolor="#FF0000">
<form action="/cgi-bin/mlm.exe" method="GET"> <input type="hidden" name="subject-field"
Appendix B: Programming Guidelines
550
value="cplusplus-email-list">
<input type="hidden" name="command-field" value="remove"><p>
<input type="text" size="40" name="email-address">
<input type="submit" name="submit" value="Remove Address From C++ Mailing List"> </p></form></td>
<td width="30" bgcolor="#000000"> </td> </tr>
</table>
</center></div>
Each form contains one data-entry field called email-address, as well as a couple of hidden fields which don’t provide for user input but carry information back to the server nonetheless. The subject-field tells the CGI program the subdirectory where the resulting file should be placed. The command-field tells the CGI program whether the user is requesting that they be added or removed from the list. From the action, you can see that a GET is used with a program called mlm.exe (for “mailing list manager”). Here it is:
//: C10:mlm.cpp
//A GGI program to maintain a mailing list #include "CGImap.h"
#include <fstream> using namespace std;
const string contact("Bruce@EckelObjects.com");
//Paths in this program are for Linux/Unix. You
//must use backslashes (two for each single
//slash) on Win32 servers:
const string rootpath("/home/eckel/");
int main() {
cout << "Content-type: text/html\n"<< endl; CGImap query(getenv("QUERY_STRING")); if(query["test-field"] == "on") {
cout << "map size: " << query.size() << "<br>"; query.dump(cout, "<br>");
}
if(query["subject-field"].size() == 0) { cout << "<h2>Incorrect form. Contact " << contact << endl;
return 0;
}
string email = query["email-address"];
Appendix B: Programming Guidelines
551
if(email.size() == 0) {
cout << "<h2>Please enter your email address" << endl;
return 0;
}
if(email.find_first_of(" \t") != string::npos){ cout << "<h2>You cannot use white space "
"in your email address" << endl; return 0;
}
if(email.find('@') == string::npos) {
cout << "<h2>You must use a proper email"
" address including an '@' sign" << endl; return 0;
}
if(email.find('.') == string::npos) {
cout << "<h2>You must use a proper email" " address including a '.'" << endl;
return 0;
}
string fname = email; if(query["command-field"] == "add")
fname += ".add";
else if(query["command-field"] == "remove") fname += ".remove";
else {
cout << "error: command-field not found. Contact " << contact << endl;
return 0;
}
string path(rootpath + query["subject-field"] + "/" + fname);
ofstream out(path.c_str()); if(!out) {
cout << "cannot open " << path << "; Contact" << contact << endl;
return 0;
}
out << email << endl;
cout << "<br><H2>" << email << " has been "; if(query["command-field"] == "add")
cout << "added";
else if(query["command-field"] == "remove")
Appendix B: Programming Guidelines
552