自C++诞生尤其是ISO/ANSI C++标准问世以来,以Bjarne Stroustrup为首的C++社群领袖一直不遗余力地倡导采用“新风格”教学和使用C++。事实证明,除了兼容于C的低阶特性外,C++提供的高级特性以及在此基础上发展的各种惯用法可以让我们编写出更加简洁、优雅、高效、健壮的程序。.
这些高级特性和惯用法包括精致且高效的标准库和各种“准标准库”,与效率、健壮性、异常安全等主题有关的各种惯用法,以及在C++的未来占据更重要地位的模板和泛型程序设计技术等。它们发展于力量强大的C++社群,并被这个社群中最负声望的专家提炼、升华成一本本精彩的著作。毫无疑问,这些学术成果必将促进C++社群创造出更多的实践成果。
我个人认为,包括操作系统、设备驱动、编译器、系统工具、图像处理、数据库系统以及通用办公软件等在内的基础软件更能够代表一个国家的软件产业发展质量,迄今为止,此类基础性的软件恰好是C++所擅长开发的,因此,可以感性地说,C++的应用水平在一定程度上可以折射出一个国家的软件产业发展水平和健康程度。..
前些年国内曾引进出版了一大批优秀的C++书籍,它们拓宽了中国C++程序员的视野,并在很大程度上纠正了长期以来存在于C++的教育、学习和使用方面的种种误解,对C++相关的产业发展起到了一定的促进作用。然而在过去的两年中,随着.NET、Java技术吸引越来越多的注意力,中国软件产业业务化、项目化的状况愈发加剧,擅长于“系统编程”的C++语言的应用领域似有进一步缩减的趋势,这也导致人们对C++的出版教育工作失去了应有的重视。
机械工业出版社华章分社决定继续为中国C++“现代化”教育推波助澜,从2006年起将陆续推出一套“C++设计新思维”丛书。这套丛书秉持精品、高端的理念,其作译者为包括Herb Sutter在内的国内外知名C++技术专家和研究者、教育者,议题紧密围绕现代C++特性,以实用性为主,兼顾实验性和探索性,形式上则是原版影印、中文译著和原创兼收并蓄。每一本书相对独立且交叉引用,篇幅短小却内容深入。作为这套丛书的特邀技术编辑,我衷心希望它们所展示的技术、技巧和理念能够为中国C++社群注入新的活力。...
荣耀
2005年12月
南京师范大学
www.royaloo.com
It came without ribbons! It came without tags! .
It came without packages, boxes or bags!
Dr. Seuss, How the Grinch Stole Christmas!, Random House, 1957
I first wrote about the Standard Template Library in 1995, when I concluded the final Item of More Effective C++ with a brief STL overview. I should have known better. Shortly thereafter, I began receiving marl asking when I'd write Effective STL.
I resisted the idea for several years. At first, I wasn't familiar enough with the STL to offer advice on it, but as time went on and my experience with it grew, this concern gave way to other reservations. There was never any question that the library represented a breakthrough in efficient and extensible design, but when it came to using the STL, there were practical problems I couldn't overlook. Porting all but the simplest STL programs was a challenge, not only because library implementations varied, but also because template support in the underlying compilers ranged from good to awful. STL tutorials were hard to come by, so learning "the STL way of programming" was difficult, and once that hurdle was overcome, finding comprehensible and accurate reference documentation was a challenge. Perhaps most daunting, even the smallest STL usage error often led to a blizzard of compfier diagnostics, each thousands of characters long, most referring to classes, functions, or templates not mentioned in the offending source code, almost all incomprehensible. Though I had great admiration for the STL and for the people behind it, I felt uncomfortable recommending it to practicing programmers. I wasn't sure it was possible to use the STL effectively.
Then I began to notice something that took me by surprise. Despite the portability problems, despite the dismal documentation, despite the compiler diagnostics resembling transmission line noise, many of my consulting clients were using the STL anyway, Furthermore, they weren't Just playing with it, they were using it in production code! That was a revelation. I knew that the STL featured an elegant design, but any library for which prograrmners are willing to endure portabll-headaches, poor documentation, and incomprehensible error messages has a lot more going for it than just good design. For an increasingly large number of professional programmers, I realized, even a bad implementation of the ST[, was preferable to no implementation at all.
Furthermore, I knew that the situation regarding the STL would only get better. Libraries and compfiers would grow more conformant with the Standard (they have), better documentation would become avafiable (it has — consult the bibliography beginning on page 225), and compfier diagnostics would improve (for the most part, we're still waiting, but Item 49. offers suggestions for how to cope whfie we wait). I therefore decided to chip in and do my part for the STL movement. This book is the result: 50 specific ways to improve your use of C++'s Standard Template Library.
My original plan was to write the book in the second half of 1999, and with that thought in mind, I put together an outline. But then I changed course. I suspended work on the book and developed an introductory training course on the STL, which I then taught several times to groups of programmers. About a year later, I returned to the book, significanfiy revising the outline based on my experiences with the training course. In the same way that my Effective C++ has been Successful by being grounded in the problems faced by real programmers, it's my hope that Effective STL similarly addresses the practical aspects of STL programming m the aspects most important to professional developers.
I am always on the lookout for ways to improve my understanding of C++. If you have suggestions for new guidelines for STL programming or if you have comments on the guidelines in this book, please let me know. In addition, it is my'continuing goal to makethis book as accurate as possible, so for each error in this book that is reported to me be it technical, grammatical, typographical, or otherwise — I will, in future printings, gladly add to the acknowledgments the name of the first person to bring that error to my attention. Send your suggeste dguide!tries, your comments, and your criticisms to estl@aristeia.com.
I maintain a list of changes to this book Since its first printing, including bug-fixes, clarifications, and technical updates. The list is ava/l,able at the Effective S'II, Errata web site, http://www.aristeia.com/Bookirrata/estlle-errata.html.
If you'd like to be notified when I make changes to this book, I encourage you to Join my mailing list. I use the list to make announcements likely to be of interest to people who follow my work on C++. For details, consult http://www.aristeia.com/MailingList/.
. SCOTT DOUGLAS MEYERS STAFFORD, OREGON
http://www.aristeia.com/ APRIL 2001
I had an enormous amount of help during the roughly two years it took me to make some sense of the STL, create a training course on it, and write this book. Of all my sources of assistance, two were particularly important. The first is Mark Rodgers. Mark generously volunteered to review my training materials as I created them, and I learned more about the STL from him than from anybody else. He also acted as a technical reviewer for this book, again providing observations and insights that improved virtually every Item.
The other outstanding source of:information was several C++-related Usenet newsgroups, especially compJang.c++.moderated ("clcm"), comp.std.c++, and microsoft, public.vc.stl. For well over a decade, I've depended on the participants in newsgroups like these to answer my questions and challenge my thinking, and it's difficult to imagine what I'd do without them. I am deeply grateful to the Usenet community for their help with both this book and my prior publications on C++.
My understanding of the STL was shaped by a variety of publications, the most important of which are listed in the Bibliography. I leaned especially heavily on Josuttis' The C++ Standard Library [3].
This book is fundamentally a summary of insights and observations made by others, though a few of the ideas are my own. I've tried to keep track of where I learned what, but the task is hopeless, because a typical Item contains information garnered from many sources over a long period of time. What follows is incomplete, but it's the best I can do. Please note that my goal here is to summarize where I first learned of an idea or technique, not where the idea or technique was originally developed or who came up with it.
In Item 1, my observation that node-based containers offer better support for transactional semantics is based on section 5.11.2 of Josuttis' The C++ Standard Library [3]. Item 2 includes an example from Mark Rodgers on how typedefs help when allocator types are changed. ..
Item 5 was motivated by Reeves' C++ Report column, "STL Gotchas" [17]. Item 8 sprang from Item 37 in Sutter's Exceptional C++ [8], and Kevlin Henney provided important details on how contalners of auto_ptrs fail in practice. In Usenet postings, Matt Austern provided examples of when allocators are useful, and I include his examples in Item 11. Item 12 is based on the discussion of thread safety at the SGI STL web site [21]. The material in Item 13 on the performance implications of reference counting in a multithreaded environment is drawn from Sutter's writings on this topic [20]. The idea for Item 15 came from Reeves' C++ Report column, "Using Standard string in the Real World, Part 2," [18]. In Item 16, Mark Rodgers came up with the technique I show for having a C API write data directly into a vector. Item 17 includes information from Usenet postings by Siemel Naran and Carl Barron. I stole Item 18 from Sutter's C++ Report column, "When Is a Container Not a Container?." [12]. In Item 20, Mark Rodgers contributed the idea of transforming a pointer into an object via a dereferencing functor, and Scott Lewandowski came up with the version of DereferenceLess I present. Item 21 originated in a Doug Harrison posting to microsoft.public.vc.stl, but the decision to restrict the focus of that Item to equality was mine. I based Item 22 on Sutter's C++ Report column, "Standard Library News: sets and maps" [13]; Matt Austern helped me understand the status of the Standardization Committee's Library Issue #103. Item 23 was inspired by Austern's C++ Report article, "Why You Shouldn't Use set -- and What to Use Instead" [15]: David Smallberg provided a neat refinement for my implementation of DataCompare. My description of Dinkumware's hashed containers is based on Plauger's C/C++ Users Journal column, "Hash Tables" [16]. Mark Rodgers doesn't agree with the overall advice of Item 26, but an early motivation for that Item was his observation that some container member functions accept only arguments- of type iterator. My treatment of Item 29 was motivated and informed by Usenet discussions involving Matt Austern and James Kanze; I was also influenced by Kreft and Langer's C++ Report article, "A Sophisticated Implementation of User-De~med Inserters and Extractors" [25].
Item 30 is due to a discussion in section 5.4.2 of Josuttis' The C++ Standard Library [3]. In Item 3 l, Marco Dalla Gasperina contributed the example use of nth_element to calculate medians, and use of that algorithm for finding percentiles comes straight out of section 18.7.1 of Stroustrup's The C++ Programming Language [7]. Item 32 was influenced by the material in section 5.6.1 of Josuttis' The C++ Standard Library [3]. Item 35 originated in Austern's C++ Report column "How to Do Case-Insensitive String Comparison" [11], and James Kanze's and John Potter's dcm postings helped me refine my understanding of the issues involved. Stroustrup's implementation for copy_if, which I show in Item 36, is from section 18.6.1 of his The C++ Programming Language [7]. Item 39 was largely motivated by the publications of Josuttis, who has written about "stateful predicates" in his The C++ Standard Library [3], in Standard Library Issue #92, and in his C++ Report article, "Predicates vs. Function Objects" [14]. In my treatment, I use his example and recommend a solution he has proposed, though the use of the term "pure function" is my own. Matt Austern confirmed my suspicion in Item 41 about the history of the terms memfun and mem_fun_ref. Item 42 can be traced to a lecture I got from Mark Rodgers when I considered violating that guideline. Mark Rodgers is also responsible for the insight in Item 44 that non-mem-ber searches over maps and multimaps examine both components of each pair, while member searches examine only the first (key) component. Item 45 contains information from various dcm contributors, including John Potter, Marcin Kasperski, Pete Becker, Dennis Yelle, and David Abrahams. David Smallberg alerted me to the utility of equal_range in performing equivalence-based searches and counts over sorted sequence containers. Andrei Alexandrescu helped me understand the conditions under which "the reference-to-reference problem" I describe in Item 50 arises, and I modeled my example of the problem on a similar example provided by Mark Rodgers at the Boost Web Site [22].
Credit for the material in Appendix A goes to Matt Austern, of course. I'm grateful that he not only gave me permission to include it in this book, he also tweaked it to make it even better than the original.
Good technical books require a thorough pre-publication vetting, and I was fortunate to benefit from the insights of an unusually talented group of technical reviewers. Brian Kernighan and Cliff Green offered early comments on a partial draft, and complete versions of the manuscript were scrutinized by Doug Harrison, Brian Kernighan, Tim Johnson, Francis Glassborow, Andrei Alexandrescu, David Smallberg, Aaron Campbell, Jared Manning, Herb Sutter, Stephen Dewhurst, Matt Austern, Gillmer Derge, Aaron Moore, Thomas Becker, Victor Von, and, of course, Mark Rodgers. Katrina Avery did the copyediting. One of the most challenging parts of preparing a book is finding good technical reviewers. I thank John Potter for introducing me to Jared Manning and Aaron Campbell.
Herb Sutter kindly agreed to act as my surrogate in compiling, running, and reporting on the behavior of some STL test programs under a beta version of Microsoft's Visual Studio .NET, while Leor Zolman undertook the herculean task of testing all the code in this book. Any errors that remain are my fault, of course, not Herb's or Leor's.
Angelika Langer opened my eyes to the indeterminate status of some aspects of STL function objects. This book has less to say about function objects than it otherwise might, but what it does say is more likely to remain true. At least I hope it is.
This printing of the book is better than earlier printingS, because I was able to address problems identified by the following sharp-eyed readers: Jon Webb, Michael Hawkins, Derek Price, Jim Scheller, Carl Manaster, Herb Sutter, Albert Franklin, George King, Dave Miller, Harold Howe, John Fuller, Tim McCarthy, John Hershberger, Igor Mikolic-Torreira, Stephan Bergmann, Robert Allan Schwartz, dohn Potter, David Grigsby, Sanjay Pattni, Jesper Andersen, Jing Tao Wang, Andre Blavier, Dan Schmidt, Bradley White, Adam Petersen, Wayne Goertel, Gabriel Netterdag, Jason Kenny, Scott Blachowicz, Seyed H. Haeri, Gareth McCaughan, Giulio Agostini, Fraser Ross, Wolfram Burkhardt, Keith Stanley, Leor Zolman, Chan Ki Lok, Motti Abramsky, Kevlin Henney, Stefan Kuhlins, Phillip Ngan, Jim Phillips, Ruediger Dreier, Guru Chandar, Charles Brockman, Day Barr, Eric Niebler, Sharad Kala, Declan Moran, Nick de Smith, David Callaway, Shlomi Frank, Andrea Grfffmi, Hans Eckardt, David Smallberg, Matt Page, and Andy Fyfe. I'm grateful for their help in improving Effective STL.
My collaborators at Addison-Wesley included John Wait (my editor and now a senior VP), Alicia Carey and Susannah Buzard (his assistants n and n+l), John Fuller (the production coordinator), Karin Hansen (the cover designer), Jason Jones (all-around technical guru, especially with respect to the demonic software spewed forth by Adobe), Marty Rabinowitz (their boss, but he works, too), and Curt Johnson, Chanda Leary-Coutu, and Robin Bruce (all marketing people, but still very nice).
Abbi Staley made Sunday lunches a routinely pleasurable experience. As she has for the six books and one CD that came before it, my wife, Nancy, tolerated the demands of my research and writing with her usual forbearance and offered me encouragement and support when I needed it most. She never fails to remind me that there's more to life than C++ and software.
And then there's our dog, Persephone. As I write this, it is her sixth birthday. Tonight, she and Nancy and I will visit Baskin-Robbins for ice cream. Persephone will have vanfila. One scoop. In a cup. To go. ...