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, whats the first building that jumps out at you? Almost certainly its 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 embellishmentsand 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 Hungarys 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 were 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 dont even turn out to be swans).
Style or Substance?
Which is better?
Dont 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? Its easy to say yes unthinkinglyuntil 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 theres 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 sincefor 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 doesnt it? If youre 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 well 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 softwares favor.
Please look one more time at the front cover photo, at the top rightthats 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 cityso 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 youre 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 youve just learned, and to show how they interrelate. The puzzles will show how to reason about C++ design and programming issuessome of them common issues, some not so common; some of them plain issues, some more esoteric; and a couple because, well, just because theyre fun.
This book is about all aspects of C++. I dont mean to say that it touches on every detail of C++that would require many more pagesbut 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 dont 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 magicand 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 Ive written for C/C++ Users Journal, Dr. Dobbs 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 dont, start with a good C++ introduction and overview. Good choices are a classic tome such as Bjarne Stroustrups The C++ Programming Language Stroustrup00 or Stan Lippman and Josée Lajoies 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 youre 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, Ive regularly received e-mail saying that “Item #N is easier (or harder) than that!” Its common for different people to vote “easier!” and “harder!” for the same Item. Ratings are personal; any Items 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; thats great, but you dont have to. You might decide to read all the Items in a section together because youre particularly interested in that sections topic; thats cool too. Except where there are what I call a “miniseries” of related problems which youll 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 Ill 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, its probably not. Remember that the code examples are usually just snippets or partial programs and arent expected to compile in isolation. Youll 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 its 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 Ive 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; Ill update that redirector to point to the new pages location (if I can find the page again) or to say that the page no longer exists (if I cant). Either way, this books URLs will stay up to date despite the rigors of print media in an Internet world. Whew.
Herb Sutter
Seattle, May 2004