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

Paperback (Print)
Used and New from Other Sellers
Used and New from Other Sellers
from $20.75
Usually ships in 1-2 business days
(Save 58%)
Other sellers (Paperback)
  • All (11) from $20.75   
  • New (5) from $35.69   
  • Used (6) from $20.75   


Software "style" is about finding the perfect balance between overhead and functionality... elegance and maintainability... flexibility and excess. In Exceptional C++ Style, legendary C++ guru Herb Sutter presents 40 new programming scenarios designed to analyze not only the what but the why and help you find just the right balance in your software.

Organized around practical problems and solutions, this book offers new insight into crucial C++ details and interrelationships, and new strategies for today's key C++ programming techniques—including generic programming, STL, exception safety, and more. You'll find answers to questions like:

  • What can you learn about library design from the STL itself?
  • How do you avoid making templated code needlessly non-generic?
  • Why shouldn't you specialize function templates? What should you do instead?
  • How does exception safety go beyond try and catch statements?
  • Should you use exception specifications, or not?
  • When and how should you "leak" the private parts of a class?
  • How do you make classes safer for versioning?
  • What's the real memory cost of using standard containers?
  • How can using const really optimize your code?
  • How does writing inline affect performance?
  • When does code that looks wrong actually compile and run perfectly, and why should you care?
  • What's wrong with the design of std::string?

Exceptional C++ Style will help you design, architect, and code with style—and achieve greater robustness and performance in all your C++ software.

Read More Show Less

Product Details

  • ISBN-13: 9780201760422
  • Publisher: Addison-Wesley
  • Publication date: 8/2/2004
  • Series: C++ In-Depth Series
  • Edition description: New Edition
  • Pages: 352
  • Sales rank: 867,563
  • Product dimensions: 7.37 (w) x 9.14 (h) x 0.71 (d)

Meet the Author

Herb Sutter is the author of three highly acclaimed books, Exceptional C++ Style, Exceptional C++, and More Exceptional C++ (Addison-Wesley). He chairs the ISO C++ standards committee, and is contributing editor and columnist for C/C++ Users Journal. As a software architect for Microsoft, Sutter leads the design of C++ language extensions for .NET programming.

Read More Show Less

Read an Excerpt

The scene: Budapest. A hot summer evening. Looking across the Danube, with a view of the eastern bank.

In the cover photo showing this pastel-colored European scene, what’s the first building that jumps out at you? Almost certainly it’s the Parliament building on the left. The massive neo-Gothic building catches the eye with its graceful dome, thrusting spires, dozens of exterior statues and other ornate embellishments—and catches the eye all the more so because it stands in stark contrast to the more utilitarian buildings around it on the Danube waterfront.

Why the difference? For one thing, the Parliament building was completed in 1902; the other stark, utilitarian buildings largely date from Hungary’s stark and utilitarian Communist era, between World War II and 1989.

“Aha,” you might think, “that explains the difference. All very nice, of course, but what on earth does this have to do with Exceptional C++ Style?”

Certainly the expression of style has much to do with the philosophy and mindset that goes into it, and that is true whether we’re talking about building architecture or software architecture. I feel certain that you have seen software designed on the scale and ornateness of the Parliament building; I feel equally sure that you have seen utilitarian blocky (or should that be “bloc-y”?) software buildings. On the extremes, I am just as convinced that you have seen many gilded lilies that err on the side of style, and many ugly ducklings that err on the side of pushing code out the door (and don’t even turn out to be swans). Style or Substance?

Which is better?

Don’t be too sure you know the answer. For one thing, “better” is an unuseful term unless you define specific measures. Better for what? Better in which cases? For another, the answer is almost always a balance of the two and begins with: “It depends...”

This book is about finding that balance in many detailed aspects of software design and implementation in C++, and knowing your tools and materials well to know when they are appropriate.

Quick: Is the Parliament building a better building, crafted with better style, than the comparatively drab ones around it? It’s easy to say yes unthinkingly—until you have to consider building and maintaining it:

  • Construction. When it was completed in 1902, this was the largest Parliament building in the world. It also cost a horrendous amount of time, effort, and money to produce and was considered by many to be a “white elephant,” which means a beautiful thing that comes at too high a cost. Consider: By comparison, how many of the ugly, drab, and perhaps outright boring concrete buildings could have been built for the same investment? And you work in an industry where the time-to-market pressure is far fiercer than the time pressure was in the age of this Parliament.
  • Maintenance. Those of you familiar with the Parliament will note that in this picture the Parliament building was under renovation and had been in that state for a number of years, at a controversial and arguably ruinous cost. But there’s more to the maintenance story than just this recent round of expensive renovations: Sadly, the beautiful sculptures you can see on the exterior of the building were made of the wrong materials, materials that were too soft. Soon after the building was originally completed, those sculptures became the subjects of a continual repair program under which they have been replaced with successively harder and more durable materials, and the heavy maintenance of the “bells and whistles” begun in the early 1900s has gone on continuously ever since—for the past century.

Likewise in software, it is important to find the right balance between construction cost and functionality, between elegance and maintainability, between the potential for growth and excessive ornateness.

We deal with these and similar tradeoffs every day as we go about software design and architecture in C++. Among the questions this book tackles are the following: Does making your code exception-safe make it better? If so, for what meanings of “better,” and when might it not be better? That question is addressed specifically in this book. What about encapsulation; does it make your software better? Why? When doesn’t it? If you’re wondering, read on. Is inlining a good optimization, and when is it done? (Be very very careful when you answer this one.) What does C++’s export feature have in common with the Parliament building? What does std::string have in common with the monolithic architecture of the Danube waterfront in our idyllic little scene?

Finally, after considering many C++ techniques and features, at the end of this book we’ll spend our last section looking at real examples of published code and see what the authors did well, what they did poorly, and what alternatives would perhaps have struck a better balance between workmanlike substance and exceptional C++ style.

What do I hope that this and the other Exceptional C++ books will help to do for you? I hope they will add perspective, add knowledge of details and interrelationships, and add understanding of how balances can be struck in your software’s favor.

Please look one more time at the front cover photo, at the top right—that’s it, right there. We should want to be in the balloon flying over the city, enjoying the full perspective of the whole view, seeing how style and substance coexist and interact and interrelate and intermingle, knowing how to make the tradeoffs and strike the right balances, each choice in its place in the integral and thriving whole.

Yes, I think Budapest is a great city—so rich with history, so replete with metaphor. The Exceptional Socrates

The Greek philosopher Socrates taught by asking his students questionsNquestions 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’ legendary ap-proach 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 predecessors, Exceptional C++ Sutter00 and More Exceptional C++ Sutter02. It assumes you’re involved in some aspect of writing production C++ software today, and it uses a question-answer format to teach 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 prob-lems 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 these parts of modern C++.

Exceptional C++ Style continues where Exceptional C++ and More Exceptional C++ left off. This book follows in the tradition of the first two: 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 optimization and memory management techniques. The books overlap in structure and theme but not in content. This book continues the strong emphasis on generic programming and on using the C++ standard library effectively, including coverage of important template and generic programming techniques.

Versions of most Items originally appeared in magazine columns and on the Internet, particularly as print columns and articles I’ve written for C/C++ Users Journal, Dr. Dobb’s Journal, the former C++ Report, and other publications, and also as Guru of the Week GotW issues #63 to #86. 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 such as Bjarne Stroustrup’s The C++ Programming Language Stroustrup00 or Stan Lippman and Josée 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:

##. The Topic of This Item Difficulty: # A few words about what this Item will cover.

The topic tag and difficulty rating gives you a hint of what you’re in for, and typically there are both introductory/review questions (“JG,” a term for a new junior-grade military officer) leading to the main questions (“Guru”). Note that the difficulty rating is my subjective guess at how difficult I expect most people will find each problem, so you might well find that a “7” problem is easier for you than some “5” problem. Since writing Exceptional C++ Sutter00 and More Exceptional C++ Sutter02, 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 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 reasonable 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 the many references to the first two Exceptional C++ books. 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.

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, never mind after it’s been sitting on your desk for five years. When I reference other peoples’ 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. Nearly all the other works I reference are listed in the Bibliography, and I’ve provided an online version with active hyperlinks. 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
Seattle, May 2004

Read More Show Less

Table of Contents

Generic programming and the C++ standard library 1
1 Uses and abuses of vector 2
2 The string formatters of Manor Farm, part 1 : sprintf 10
3 The string formatters of Manor Farm, part 2 : standard (or blindingly elegant) alternatives 16
4 Standard library member functions 27
5 Flavors of genericity, part 1 : covering the basis [sic] 31
6 Flavors of genericity, part 2 : generic enough? 35
7 Why not specialize function templates? 42
8 Befriending templates 49
9 Export restrictions, part 1 : fundamentals 59
10 Export restrictions, part 2 : interactions, usability issues, and guidelines 68
Exception safety issues and techniques 79
11 Try and catch me 80
12 Exception safety : is it worth it? 85
13 A pragmatic look at exception specifications 89
Class design, inheritance, and polymorphism 99
14 Order, order! 100
15 Uses and abuses of access rights 104
16 (Mostly) private 110
17 Encapsulation 119
18 Virtuality 129
19 Enforcing rules for derived classes 139
Memory and resource management 151
20 Containers in memory, part 1 : levels of memory management 152
21 Containers in memory, part 2 : how big is it really? 156
22 To new, perchance to throw, part 1 : the many faces of new 164
23 To new, perchance to throw, part 2 : pragmatic issues in memory management 173
Optimization and efficiency 183
24 Constant optimization? 184
25 Inline redux 190
26 Data formats and efficiency, part 1 : when compression is the name of the game 199
27 Data formats and efficiency, part 2 : (even less) bit-twiddling 204
Traps, pitfalls, and puzzlers 213
28 Keywords that aren't (or, comments by another name) 214
29 Is it initialization? 221
30 Double or nothing 227
31 Amok code 230
32 Slight typos? : graphic language and other curiosities 235
33 Operators, operators everywhere 239
Style case studies 245
34 Index tables 246
35 Generic callbacks 258
36 Construction unions 267
37 Monoliths "unstrung," part 1 : a look at std::string 286
38 Monoliths "unstrung," part 2 : refactoring std::string 292
39 Monoliths "unstrung," part 3 : std::string diminishing 301
40 Monoliths "unstrung," part 4 : std::string redux 305
Read More Show Less

Customer Reviews

Be the first to write a review
( 0 )
Rating Distribution

5 Star


4 Star


3 Star


2 Star


1 Star


Your Rating:

Your Name: Create a Pen Name or

Barnes & Noble.com Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & Noble.com that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & Noble.com does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at BN.com or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation


  • - By submitting a review, you grant to Barnes & Noble.com and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Noble.com Terms of Use.
  • - Barnes & Noble.com reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & Noble.com also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on BN.com. It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously
Sort by: Showing 1 Customer Reviews
  • Anonymous

    Posted June 13, 2004

    Stretching exercises

    A good set of mental stretching exercises for the C++ programmer who wants to deepen an appreciation of the language. Sutter assumes you are already conversant with the basic syntax, and that by now, you can easily write and compile a straightforward computational task. But what lies beyond? Of necessity, what Sutter does is somewhat subjective. (Unlike, say, a book on syntax.) Not so much in the opinions he offers in the solutions to the problems he poses. Most C++ programmers will probably regard his assessments as valid and cogent. If you tackle the problems, without peeking at the answers till you have given it a hard try, then you should derive some benefit from most problems. Like when he asks when try and catch should be used, and when not? Basically, it is possible to overuse try and catch. Something that an introductory book would be unlikely to discuss. The real subjectivity in the book is of course his choice of problems. But Sutter readily explains that he makes no claim to comprehensiveness. and he does indeed cover many aspects of the language. Quite possibly to your benefit.

    Was this review helpful? Yes  No   Report this review
Sort by: Showing 1 Customer Reviews

If you find inappropriate content, please report it to Barnes & Noble
Why is this product inappropriate?
Comments (optional)