Home > Store

More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions

Register your product to gain access to bonus material or receive a coupon.

More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions


  • Sorry, this book is no longer in print.
Not for Sale




  • Copyright 2002
  • Dimensions: 7-3/8" x 9-1/4"
  • Edition: 1st
  • Book
  • ISBN-10: 0-201-70434-X
  • ISBN-13: 978-0-201-70434-1

More Exceptional C++ continues where Herb Sutter's best-selling Exceptional C++ left off, delivering 40 puzzles that illuminate the most challenging -- and most powerful -- aspects of C++. More Exceptional C++ offers many new puzzles focused on generic programming and the C++ Standard Template Library, including important techniques such as traits and predicates, as well as key considerations in using standard containers and algorithms -- many of them never covered elsewhere. More Exceptional C++ contains a detailed new section (and two appendices) on optimization in single- and multithreaded environments. It also provides important new insights on crucial topics first introduced in Exceptional C++, including exception safety, generic programming, and memory management. For all C++ programmers.


Web Resources

Click below for Web Resources related to this title:
Author Web Site

Sample Content

Online Sample Chapter

Generic Programming and the C++ Standard Library

Downloadable Sample Chapter

Click below for Sample Chapter related to this title:




Table of Contents



Generic Programming and the C++ Standard Library.

Item 1: Switching Streams (2 / 10).

Item 2: Predicates, Part 1: What remove() Removes (4 / 10).

Item 3: Predicates, Part 2: Matters of State (7 / 10).

Item 4: Extensible Templates: Via Inheritance or Traits? (7 / 10).

Item 5: Typename (7 / 10).

Item 6: Containers, Pointers, and Containers That Aren't (5 / 10).

Item 7: Using Vector and Deque (3 / 10).

Item 8: Using Set and Map (5 / 10).

Item 9: Equivalent Code? (5 / 10).

Item 10: Template Specialization and Overloading (6 / 10).

Item 11: Mastermind (8 / 10).

Optimization and Performance.

Item 12: Inline (4 / 10).

Item 13: Lazy Optimization, Part 1: A Plain Old String (2 / 10).

Item 14: Lazy Optimization, Part 2: Introducing Laziness (3 / 10).

Item 15: Lazy Optimization, Part 3: Iterators and References (6 / 10).

Item 16: Lazy Optimization, Part 4: Multi-Threaded Environments (8 / 10).

Exception Safety Issues and Techniques.

Item 17: Constructor Failures, Part 1: Object Lifetimes (4 / 10).

Item 18: Constructor Failures, Part 2: Absorption? (7 / 10).

Item 19: Uncaught Exceptions (6 / 10).

Item 20: An Unmanaged Pointer Problem, Part 1: Parameter Evaluation (6 / 10).

Item 21: An Unmanaged Pointer Problem, Part 2: What About auto_ptr? (8 / 10).

Item 22: Exception-Safe Class Design, Part 1: Copy Assignment (7 / 10).

Item 23: Exception-Safe Class Design, Part 2: Inheritance (6 / 10).

Inheritance and Polymorphism.

Item 24: Why Multiple Inheritance? (6 / 10).

Item 25: Emulating Multiple Inheritance (5 / 10).

Item 26: Multiple Inheritance and the Siamese Twin Problem (4 / 10).

Item 27: (Im)pure Virtual Functions (7 / 10).

Item 28: Controlled Polymorphism (3 / 10).

Memory and Resource Management.

Item 29: Using auto_ptr (5 / 10).

Item 30: Smart Pointer Members, Part 1: A Problem with auto_ptr (5 / 10).

Item 31: Smart Pointer Members, Part 2: Toward a ValuePtr (6 / 10).

Free Functions and Macros.

Item 32: Recursive Declarations (6 / 10).

Item 33: Simulating Nested Functions (5 / 10).

Item 34: Preprocessor Macros (4 / 10).

Item 35: #Definition (4 / 10).

Miscellaneous Topics.

Item 36: Initialization (3 / 10).

Item 37: Forward Declarations (3 / 10).

Item 38: Typedef (3 / 10).

Item 39: Namespaces, Part 1: Using-Declarations and Using-Directives (2 / 10).

Item 40: Namespaces, Part 2: Migrating to Namespaces (4 / 10).



Appendix A. Optimizations That Aren't (In a Multithreaded World).

Appendix B. Test Results for Single- versus Multi-Thread-Safe String Implementations.


Index. 020170434XT07022001


The Greek philosopher Socrates taught by asking his students questions--questions designed to guide them and help them draw conclusions from what they already knew, and to show them how the things they were learning related to each other and to their existing knowledge. This method has become so famous that we now call it the "Socratic method." From our point of view as students, Socrates' approach involves us, makes us think, and helps us relate and apply what we already know to new information.

This book takes a page from Socrates, as did its predecessor, Exceptional C++ Sutter00. It assumes you're involved in some aspect of writing production C++ software today, and uses a question-answer format to teach you how to make effective use of standard C++ and its standard library with a particular focus on sound software engineering in modern C++. Many of the problems are drawn directly from experiences I and others have encountered while working with production C++ code. The goal of the questions is to help you draw conclusions from things you already know as well as things you've just learned, and to show how they interrelate. The puzzles will show how to reason about C++ design and programming issues--some of them common issues, some not so common; some of them plain issues, some more esoteric; and a couple because, well, just because they're fun.

This book is about all aspects of C++. I don't mean to say that it touches on every detail of C++--that would require many more pages--but rather that it draws from the wide palette of the C++ language and library features to show how apparently unrelated items can be used together to synthesize novel solutions to common problems. It also shows how apparently unrelated parts of the palette interrelate on their own, even when you don't want them to, and what to do about it. You will find material here about templates and namespaces, exceptions and inheritance, solid class design and design patterns, generic programming and macro magic--and not just as randomized tidbits, but as cohesive Items showing the interrelationships among all of these parts of modern C++.

What's "More?"

More Exceptional C++ continues where Exceptional C++ left off. This book follows in the tradition of the first: It delivers new material, organized in bite-sized Items and grouped into themed sections. Readers of the first book will find some familiar section themes, now including new material, such as exception safety, generic programming, and memory management techniques. The two books overlap in structure and theme, not in content.

Where else does More Exceptional C++ differ? This book has a much stronger emphasis on generic programming and on using the C++ standard library effectively, including coverage of important techniques such as traits and predicates. Several Items provide in-depth looks at considerations to keep in mind when using the standard containers and algorithms; many of these considerations I've not seen covered elsewhere. There's a new section and two appendixes that focus on optimization in single- and multithreaded environments--issues that are now more than ever of practical consequence for development shops writing production code.

Versions of most Items originally appeared in Internet and magazine columns, particularly as Guru of the Week GotW issues #31 to 62, and as print columns and articles I've written for C/C++ Users Journal, Dr. Dobb's Journal, the former C++ Report, and other publications. The material in this book has been significantly revised, expanded, corrected, and updated since those initial versions, and this book (along with its de rigueur errata list available at www.gotw.ca) should be treated as the current and authoritative version of that original material.

What I Assume You Know

I expect that you already know the basics of C++. If you don't, start with a good C++ introduction and overview. Good choices are a classic tome like Bjarne Stroustrup's The C++ Programming Language Stroustrup00, or Stan Lippman and Josee Lajoie's C++ Primer, Third Edition Lippman98. Next, be sure to pick up a style guide such as Scott Meyers' classic Effective C++ books Meyers96 Meyers97. I find the browser-based CD version Meyers99 convenient and useful.

How to Read This Book

Each Item in this book is presented as a puzzle or problem, with an introductory header that resembles the following:

Item #: The Topic of This Puzzle
Difficulty: X

The topic tag and difficulty rating gives you a hint of what you're in for. Note that the difficulty rating is my subjective guess at how difficult I expect most people will find each problem, so you may well find that a "7" problem is easier for you than some "5" problem. Since writing Exceptional C++, I've regularly received e-mail saying that "Item #N is easier (or harder) than that!" It's common for different people to vote "easier!" and "harder!" for the same Item. Ratings are personal; any Item's actual difficulty for you really depends on your knowledge and experience and could be easier or harder for someone else. In most cases, though, you should find the rating to be a good rule-of-thumb guide to what to expect.

You might choose to read the whole book front to back; that's great, but you don't have to. You might decide to read all the Items in a section together because you're particularly interested in that section's topic; that's cool, too. Except where there are what I call a "miniseries" of related problems which you'll see designated as "Part 1," "Part 2," and so on, the Items are pretty independent, and you should feel free to jump around, following the many cross-references among the Items in the book, as well as some references to Exceptional C++. The only guidance I'll offer is that the miniseries are designed to be read consecutively as a group; other than that, the choice is yours.

Namespaces, Typename, References, and Other Conventions

I make quite a few recommendations in this book, and I won't give you guidelines that tell you to do something I don't already do myself. That includes what I do in my own example code throughout this book. I'll also bow to existing practice and modern style, even when it really makes no material difference.

On that note, a word about namespaces: In the code examples, if you see a using-directive at file scope in one example and at function scope in another example a few pages or Items later, there's no deeper reason than that's what felt right and aesthetically pleasing to me for that particular case; for the rationale, turn to Item 40. In the narrative text itself, I've chosen to qualify standard library names with std:: when I want to emphasize that it's the standard facility I'm talking about. Once that's established, I'll generally switch back to using the unqualified name.

When it comes to declaring template parameters, I sometimes come across people who think that writing class instead of typename is old-fashioned, even though there's no functional difference between the two and the standard itself uses class most everywhere. Purely for style, and to emphasize that this book is about today's modern C++, I've switched to using typename instead of class to declare template parameters. The only exception is one place in Item 33, where I quote directly from the standard; the standard says class, so I left it in there.

Unless I call something a "complete program," it's probably not. Remember that the code examples are usually just snippets or partial programs and aren't expected to compile in isolation. You'll usually have to provide some obvious scaffolding to make a complete program out of the snippet shown.

Finally, a word about URLs: On the Web, stuff moves. In particular, stuff I have no control over moves. That makes it a real pain to publish random Web URLs in a print book lest they become out of date before the book makes it to the printer's, never mind after it's been sitting on your desk for five years. When I reference other people's articles or Web sites in this book, I do it via a URL on my own Web site, www.gotw.ca, which I can control and which contains just a straight redirect to the real Web page. If you find that a link printed in this book no longer works, send me e-mail and tell me; I'll update that redirector to point to the new page's location (if I can find the page again) or to say that the page no longer exists (if I can't). Either way, this book's URLs will stay up-to-date despite the rigors of print media in an Internet world. Whew.

Herb Sutter
Toronto, June 2001



#define, see macros
#pragma, 218
A AboutToModify, 91-114
Abrahams, David, 138, 140, 142
accumulate, 77-78
ACE, 104
Adams, Douglas, reference to, 22
Adapter pattern, 179-180
advance, example use, 10
Alexandrescu, Andrei, 25, 271
Append, 86-103, 263-269

auto_ptr and, see auto_ptr, arrays and
vector and, see vector, C array and
zero-length, 177-178
Array, 65-68
assignment, templated, see template(s),
associative containers, see containers, associative
atomic integer operations, 107-114, 256-258, 269
auto_array, 178-179
auto_ptr, 135-148, 175-199
arrays and, 175-182
example use, 93
members, issues regarding, 148, 182-187
Pimpl Idiom and, see Pimpl Idiom, auto_ptr
swap and, 145
vector versus, 181-182
auto_ptr_new, 137-140
B basic_ios, 3-4
rdbuf, 3-4
basic_istream, 1-5
basic_ostream, 1-5, 20
basic_string, 20, 113, 195, 197
copy-on-write and, 259-260
see also copy-on-write
reputation for slowness undeserved, 113, 248
bazooka, const_cast, 58
Bester, Alfred, 55
bitset, 41, 43
bitvector, 43
vector and, see vector, vector<bool>
bpred, 11-12
buffer growth strategy, see String, growth strategy
C C array,
vector and, see vector, C array and
C/C++ Users Journal, x
C++ standard, the, 271
C++ Report, x
capacity, see vector, capacity
Cargill Widget Example, 141-149
char_traits, 5, 20, 195
<cheader> style, 237-238
ChoosePeg, 71-73, 76
ci_char_traits, alluded to, 5
cin, 2
Clamage, Steve, xii, 140
local, 207-209
nested, 207-209
Clone, 19-32, 193-199
Cloneable, 19, 25-29
ColorMatch, 77-79
Colossal Cave adventure, reference to, 22
Combination, 76
concurrency, see multithreading
conservation of energy, 93
const_cast, 53, 55, 57-58
Constraints, 24-28
exceptions, see exception(s), constructor
templated, see template(s), construction
use to contain requirements-enforcing code, 22-23
container requirements, 36-45
associative, see set; map
proxied, 41-45
taking pointers and references into, 38
vector<bool>, see vector, vector<bool>
containment, see delegation
conversion operators, see operator(s), conversion
copy, example use, 9, 87-88, 92-93
copy initialization, see initialization, direct versus copy
see also String, Optimized::String
basic_string and, 259-261
historically popular, 261
multithreading and, 104-114, 248, 253-269
mutating or possibly-mutating operations and, 251
optimizing allocation versus char copying, 259
sample timings of, 263-269
count, 79
CountColor, 72, 74
CountedPtr, 17-18
CountPlace, 71, 73
coupling, 151-153
cout, 2
COW, see copy-on-write
crashes, see intermittent crashes
CreateFrom, 194-199
Customer, 58
D Death, Dreaded Diamond of, 156
debugger, launching, see DieDieDie
forward, 226-228
recursive, 201-206
Decorator pattern, 170
Decrement, 18
deep copy, 108-109
see also copy-on-write
Del Rey, Lester, 55
array form and auto_ptr, 176-182
dependent names, 33
deque, 1, 46-53
deque<bool>, 45
derivation, see inheritance
use to contain requirements-enforcing code, 22-23
pre-destructor, 131
public versus virtual, 168-169
Dewhurst, Steve, xii
direct initialization, see initialization, direct versus copy
DieDieDie, 171-172
Dining Philosophers Problem, allusion to, 252
distance, example use, 10
double delete, examples of, 184
Dr. Dobb's Journal, x
Dreaded Diamond of Death, 156
dynamic_cast, example use of, 160-162
E ECHO, 1-2
effects, see also side effects
encapsulation, 5-6, 20
EnsureUnique, 256
equal_to, example use, 77
erase, 8, 46
iterators and, see iterator(s), validity
remove and, 8
see also vector, erase
Error, variant data representation using preprocessor, 217
expressions, order of evaluation of, see order of evaluation
constructor, 115-126
destructors and, 128, 130
safety guarantees, see exception safety, guarantees
thrown from base or member constructors, 116-126
exception safety,
assignment and, 142, 146
coupling and, 151-153
design and, 147-148
guarantees, 142
Swap and, 142
extensibility, 5-6
F find, 43
find_if, 12-17, 76
FindCustomer, 47
FlagNth, 7, 9-10, 15-17
FlagNthImpl, 16-17
flip, 42
food, see Dining Philosophers Problem
for_each, example use of, 72
forward declarations, see declarations, forward
forward iterators, see iterator(s), forward
FPDoubleInt, 202
French, gratuitous use of, x, 3, 77, 77, 245
virtual function accessibility control using, 172-174
front, 42
FuncPtr, 201-206
function try blocks, see try, function try blocks
functions, nested, see nested functions, simulating
G Gamma, Erich, 271
generate, example use of, 71, 76
GetError, 249, 251
GotW, see Guru of the Week
GreaterThan, 13
GreaterThanFive, 12
growth strategy for buffers, see String, growth
guarantees, exception safety, see exception safety, guarantees
Guru of the Week, x, 245, 271
H Haldeman, Joe, 55
Has-A, 149-153
HasClone, 24
header files,
<cheader> style, 237-238
Heinlein, Robert A., 55, 114
Helm, Richard, 271
Henney, Kevlin, xii, 150, 271
Hickin, John, 14
"holey array," 125
Holmes, Sherlock, reference to, 124
Hyslop, Jim, xii
I ifstream, example use, 3-4
IIITO, see Is-Implemented-In-Terms-Of
increment(ing), see operator(s), ++
Increment, 18
indigestion, compiler, 136
delegation versus, 149-153
multiple, 155-158
simulating, 159-166
Siamese Twin Problem, 162-166
requiring, 19-32
testing for, see also IsDerivedFrom
unnecessary use of, 149-153
virtual, 156
direct versus copy, 224-226
initializer lists,
dangers of resource acquisition and, 123
inline, 83-86
inner_product, 77
instantiated_type, 32-36
instantiation of templates, see template(s), instantiation
interface classes, 158
intermittent crashes, 250
IntAtomic-, see atomic integer operations
manipulating atomically, see atomic integer operations
Is-A, 149-153
see also Liskov Substitutability Principle (LSP)
IsAnyElementGreaterThanFive, 12-13
IsDerivedFrom, 25-29
Is-Implemented-In-Terms-Of, 149-153
IsOK, 118, 121
Is-Substitutable-For-A, 149-153
see also Liskov Substitutability Principle (LSP)
istream, see basic_istream
istream_with_assign, 2


Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020