II ll@@vvee RRuuBBooaarrdd •• TTaabbllee ooff CCoonntteennttss EExxcceeppttiioonnaall CC++++:: 4477 EEnnggiinneeeerriinngg PPuuzzzzlleess,, PPrrooggrraammmmiinngg PPrroobblleemmss,, aanndd SSoolluuttiioonnss BByy HHeerrbb SSuutttteerr PPuubblliisshheerr :: AAddddiissoonn WWeesslleeyy PPuubb DDaattee :: NNoovveemmbbeerr 1188,, 11999999 IISSBBNN :: 00--220011--6611556622--22 PPaaggeess :: 224400 EExxcceeppttiioonnaall CC++++ sshhoowwss bbyy eexxaammppllee hhooww ttoo ggoo aabboouutt ssoouunndd ssooffttwwaarree eennggiinneeeerriinngg iinn ssttaannddaarrdd CC++++.. DDoo yyoouu eennjjooyy ssoollvviinngg tthhoorrnnyy CC++++ pprroobblleemmss aanndd ppuuzzzzlleess?? DDoo yyoouu rreelliisshh wwrriittiinngg rroobbuusstt aanndd eexxtteennssiibbllee ccooddee?? TThheenn ttaakkee aa ffeeww mmiinnuutteess aanndd cchhaalllleennggee yyoouurrsseellff wwiitthh ssoommee ttoouugghh CC++++ ddeessiiggnn aanndd pprrooggrraammmmiinngg pprroobblleemmss.. TThhee ppuuzzzzlleess aanndd pprroobblleemmss iinn EExxcceeppttiioonnaall CC++++ nnoott oonnllyy eenntteerrttaaiinn,, tthheeyy wwiillll hheellpp yyoouu hhoonnee yyoouurr sskkiillllss ttoo bbeeccoommee tthhee sshhaarrppeesstt CC++++ pprrooggrraammmmeerr yyoouu ccaann bbee.. MMaannyy ooff tthheessee pprroobblleemmss aarree ccuulllleedd ffrroomm tthhee ffaammoouuss GGuurruu ooff tthhee WWeeeekk ffeeaattuurree ooff tthhee IInntteerrnneett nneewwssggrroouupp ccoommpp..llaanngg..cc++++..mmooddeerraatteedd,, eexxppaannddeedd aanndd uuppddaatteedd ttoo ccoonnffoorrmm ttoo tthhee ooffffiicciiaall IISSOO//AANNSSII CC++++ SSttaannddaarrdd.. EEaacchh pprroobblleemm iiss rraatteedd aaccccoorrddiinngg ttoo ddiiffffiiccuullttyy aanndd iiss ddeessiiggnneedd ttoo iilllluussttrraattee ssuubbttllee pprrooggrraammmmiinngg mmiissttaakkeess oorr ddeessiiggnn ccoonnssiiddeerraattiioonnss.. AAfftteerr yyoouu''vvee hhaadd aa cchhaannccee ttoo aatttteemmpptt aa ssoolluuttiioonn yyoouurrsseellff,, tthhee bbooookk tthheenn ddiisssseeccttss tthhee ccooddee,, iilllluussttrraatteess wwhhaatt wweenntt wwrroonngg,, aanndd sshhoowwss hhooww tthhee pprroobblleemm ccaann bbee ffiixxeedd.. CCoovveerriinngg aa bbrrooaadd rraannggee ooff CC++++ ttooppiiccss,, tthhee pprroobblleemmss aanndd ssoolluuttiioonnss aaddddrreessss ccrriittiiccaall iissssuueess ssuucchh aass:: GGeenneerriicc pprrooggrraammmmiinngg aanndd hhooww ttoo wwrriittee rreeuussaabbllee tteemmppllaatteess EExxcceeppttiioonn ssaaffeettyy iissssuueess aanndd tteecchhnniiqquueess RRoobbuusstt ccllaassss ddeessiiggnn aanndd iinnhheerriittaannccee CCoommppiilleerr ffiirreewwaallllss aanndd tthhee PPiimmppll IIddiioomm Name lookup, namespaces, and the Interface Principle Memory management issues and techniques Traps, pitfalls, and anti-idioms Optimization Try your skills against the C++ masters and come away with the insight and experience to create more efficient, effective, robust, and portable C++ code. I l@ve RuBoard I l@ve RuBoard • Table of Contents Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions By Herb Sutter Publisher : Addison Wesley Pub Date : November 18, 1999 ISBN : 0-201-61562-2 Pages : 240 Copyright Foreword Preface How to Read This Book How We Got Here: GotW and PeerDirect Acknowledgments Generic Programming and the C++ Standard Library Item 1. Iterators Solution Item 2. Case-Insensitive Strings—Part 1 Solution Item 3. Case-Insensitive Strings—Part 2 Solution Item 4. Maximally Reusable Generic Containers—Part 1 Solution Item 5. Maximally Reusable Generic Containers—Part 2 Solution Alternative: The Standard Library Approach Item 6. Temporary Objects Solution Item 7. Using the Standard Library (or, Temporaries Revisited) Solution Exception-Safety Issues and Techniques Item 8. Writing Exception-Safe Code—Part 1 Solution Item 9. Writing Exception-Safe Code—Part 2 Solution Item 10. Writing Exception-Safe Code—Part 3 Solution Item 11. Writing Exception-Safe Code—Part 4 Solution Item 12. Writing Exception-Safe Code—Part 5 Solution Item 13. Writing Exception-Safe Code—Part 6 Solution Item 14. Writing Exception-Safe Code—Part 7 Solution Item 15. Writing Exception-Safe Code—Part 8 Solution Item 16. Writing Exception-Safe Code—Part 9 Solution Item 17. Writing Exception-Safe Code—Part 10 Solution Item 18. Code Complexity—Part 1 Solution Item 19. Code Complexity—Part 2 Solution Class Design and Inheritance Item 20. Class Mechanics Solution Item 21. Overriding Virtual Functions Solution Item 22. Class Relationships—Part 1 Solution Item 23. Class Relationships—Part 2 Solution Item 24. Uses and Abuses of Inheritance Solution Item 25. Object-Oriented Programming Solution Compiler Firewalls and the Pimpl Idiom Item 26. Minimizing Compile-time Dependencies—Part 1 Solution Item 27. Minimizing Compile-time Dependencies—Part 2 Solution Item 28. Minimizing Compile-time Dependencies—Part 3 Solution Item 29. Compilation Firewalls Solution Item 30. The "Fast Pimpl" Idiom Solution Name Lookup, Namespaces, and the Interface Principle Item 31. Name Lookup and the Interface Principle—Part 1 Solution Item 32. Name Lookup and the Interface Principle—Part 2 Solution Item 33. Name Lookup and the Interface Principle—Part 3 Solution Item 34. Name Lookup and the Interface Principle—Part 4 Solution Memory Management Item 35. Memory Management—Part 1 Solution Item 36. Memory Management—Part 2 Solution Item 37. AUTO_PTR Solution Traps, Pitfalls, and Anti-Idioms Item 38. Object Identity Solution Item 39. Automatic Conversions Solution Item 40. Object Lifetimes—Part 1 Solution Item 41. Object Lifetimes—Part 2 Solution Miscellaneous Topics Item 42. Variable Initialization—Or is it? Solution Item 43. Const-Correctness Solution Item 44. Casts Solution Item 45. BOOL Solution Item 46. Forwarding Functions Solution Item 47. Control Flow Solution Afterword Bibliography I l@ve RuBoard I l@ve RuBoard Copyright Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book and Addison Wesley Longman, Inc., was aware of a trademark claim, the designations have been printed in initial capital letters or all capital letters. The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. The publisher offers discounts on this book when ordered in quantity for special sales. For more information, please contact: Pearson Education Corporate Sales Division 201 W. 103rd Street Indianapolis, IN 46290 (800) 428-5331 [email protected] Library of Congress Cataloging-in-Publication Data Sutter, Herb. Exceptional C++ : 47 engineering puzzles, programming problems, and solutions / Herb Sutter. p. cm. Includes bibliographical references and index. ISBN 0-201-61562-2 (alk. paper) 1. C++ (Computer program language) I. Title. QA76.73.C153.S88 1999 005.13'3—dc21 99-046115 CIP Copyright © 2000 by Addison Wesley Longman, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. Published simultaneously in Canada. Credits Project Editor: Deborah Lafferty Production Manager: Sarah Weaver Design and Composition: Kim Arney Index: Michael Loo Text printed on recycled paper. 4 5 6 7 8 9 10—CRS—04030201 4th printing, November 2001 Dedication To my family for their patient support, and to Eric Wilson, Jeff Sumner, Juana Chang, Larry Palmer, and the rest of the core PeerDirect development team, my "extended family" for the past four years: Declan West Doug Shelley Duk Loi Ian Long Justin Karabegovic Kim Nguyen Margot Fulcher Mark Cheers Morgan Jones Violetta Lukow Thanks for everything, guys. I l@ve RuBoard I l@ve RuBoard Foreword This is a remarkable book, but it wasn't until I had nearly finished reading it that I realized just how remarkable it is. This could well be the first book ever written for people who are already familiar with C++—all of C++. From language features to components of the standard library to programming techniques, this book skips from topic to topic, always keeping you slightly off balance, always making sure you're paying attention. Just like real C++ programs. Class design bumps into the behavior of virtual functions, iterator conventions run up against name lookup rules, assignment operators sideswipe exception safety, compilation dependencies cross paths with exported templates. Just like they do in real programs. The result is a dizzying maelstrom of language features, library components, and programming techniques at once both chaotic and magnificent. Just like real programs. I pronounce GotW such that it rhymes with "Gotcha," and perhaps that's fitting. As I compared my solutions to the book's quizzes against Sutter's answers, I fell into the traps he (and C++) laid before me more often than I'd like to admit. I could almost see Herb smiling and softly saying "Gotcha!" for each error I made. Some may argue that this proves I don't know much about C++. Others may claim it demonstrates that C++ is too complex for anyone to master. I believe it shows that when you're working in C++, you have to think carefully about what you're doing. C++ is a powerful language designed to help solve demanding problems, and it's important that you hone your knowledge of the language, its library, and its programming idioms as finely as you can. The breadth of topics in this book will help you do that. So will its unique quiz- based format. Veteran readers of the C++ newsgroups know how difficult it is to be proclaimed a Guru of the Week. Veteran participants know it even better. On the Internet, of course, there can be only one guru each week, but, backed by the information in this book, you can reasonably hope to produce guru-quality code every time you program. Scott Meyers June 1999 I l@ve RuBoard