C++ Coding Standards The C++ In-Depth Series Bjarne Stroustrup, Editor “I have made this letter longer than usual, because I lack the time to make it short.” —BLAISEPASCAL The advent of the ISO/ANSI C++ standard marked the beginning of a new era for C++ programmers. The standard offers many new facilities and opportunities, but how can a real-world programmer find the time to discover the key nuggets of wisdom within this mass of information? The C++ In-Depth Seriesminimizes learning time and confusion by giving programmers concise, focused guides to specific topics. Each book in this series presents a single topic, at a technical level appropriate to that topic. The Series’ practical approach is designed to lift professionals to their next level of programming skills. Written by experts in the field, these short, in-depth monographs can be read and referenced without the distraction of unrelated material. The books are cross-referenced within the Series, and also reference The C++ Programming Languageby Bjarne Stroustrup. As you develop your skills in C++, it becomes increasingly important to separate essential information from hype and glitz, and to find the in-depth content you need in order to grow. The C++ In-Depth Series provides the tools, concepts, techniques, and new approaches to C++ that will give you a critical edge. Titles in the Series Accelerated C++:Practical Programming by Example, Andrew Koenig and Barbara E. Moo Applied C++: Practical Techniques for Building Better Software, Philip Romanik and Amy Muntz The Boost Graph Library: User Guide and Reference Manual, Jeremy G. Siek, Lie-Quan Lee, and Andrew Lumsdaine C++ Coding Standards: 101 Rules, Guidelines, and Best Practices, Herb Sutter and Andrei Alexandrescu C++ In-Depth Box Set, Bjarne Stroustrup, Andrei Alexandrescu, Andrew Koenig, Barbara E. Moo, Stanley B. Lippman, and Herb Sutter C++ Network Programming, Volume 1: Mastering Complexity with ACE and Patterns, Douglas C. Schmidt and Stephen D. Huston C++ Network Programming, Volume 2: Systematic Reuse with ACE and Frameworks, Douglas C. Schmidt and Stephen D. Huston C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond, David Abrahams and Aleksey Gurtovoy Essential C++, Stanley B. Lippman Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions, Herb Sutter Exceptional C++ Style: 40 New Engineering Puzzles, Programming Problems, and Solutions, Herb Sutter Modern C++ Design: Generic Programming and Design Patterns Applied, Andrei Alexandrescu More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions, Herb Sutter For more information, check out the series web site at www.awprofessional.com/series/indepth/ C++ Coding Standards 101 Rules, Guidelines, and Best Practices Herb Sutter Andrei Alexandrescu Boston The authors and publisher have taken care in the preparation of this book, but make no expressed or im- plied 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 pro- grams contained herein. Publisher: John Wait Editor in Chief: Don O’Hagan Acquisitions Editor: Peter Gordon Editorial Assistant: Kim Boedigheimer Marketing Manager: Chanda Leary-Coutu Cover Designer: Chuti Prasertsith Managing Editor: John Fuller Project Editor: Lara Wysong Copy Editor: Kelli Brooks Manufacturing Buyer: Carol Melville The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U. S. Corporate and Government Sales (800) 382-3419 [email protected] For sales outside the U. S., please contact: International Sales [email protected] Visit us on the Web: www.awprofessional.com Library of Congress Cataloging-in-Publication Data: Sutter, Herb. C++ coding standards : 101 rules, guidelines, and best practices / Herb Sutter, Andrei Alexandrescu. p. cm. Includes bibliographical references and index. ISBN 0-321-11358-6 (pbk. : alk. paper) C++ (Computer program language) I. Alexandrescu, Andrei. II. Title. QA76.73.C153S85 2004 005.13'3—dc22 2004022605 Copyright © 2005 Pearson Education, Inc. All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to: Pearson Education, Inc. Rights and Contracts Department One Lake Street Upper Saddle River, NJ 07458 ISBN 0-321-11358-6 Text printed in the United States on recycled paper at Courier in Stoughton, Massachusetts. Third printing, February 2005 For the millions of current C++ programmers. This page intentionally left blank Contents Preface xi Organizational and Policy Issues 1 0. Don’t sweat the small stuff. (Or: Know what not to standardize.) 2 1. Compile cleanly at high warning levels. 4 2. Use an automated build system. 7 3. Use a version control system. 8 4. Invest in code reviews. 9 Design Style 11 5. Give one entity one cohesive responsibility. 12 6. Correctness, simplicity, and clarity come first. 13 7. Know when and how to code for scalability. 14 8. Don’t optimize prematurely. 16 9. Don’t pessimize prematurely. 18 10. Minimize global and shared data. 19 11. Hide information. 20 12. Know when and how to code for concurrency. 21 13. Ensure resources are owned by objects. Use explicit RAII and smart pointers. 24 Coding Style 27 14. Prefer compile- and link-time errors to run-time errors. 28 15. Useconst proactively. 30 16. Avoid macros. 32 vii viii Contents 17. Avoid magic numbers. 34 18. Declare variables as locally as possible. 35 19. Always initialize variables. 36 20. Avoid long functions. Avoid deep nesting. 38 21. Avoid initialization dependencies across compilation units. 39 22. Minimize definitional dependencies. Avoid cyclic dependencies. 40 23. Make header files self-sufficient. 42 24. Always write internal #include guards. Never write external #include guards. 43 Functions and Operators 45 25. Take parameters appropriately by value, (smart) pointer, or reference. 46 26. Preserve natural semantics for overloaded operators. 47 27. Prefer the canonical forms of arithmetic and assignment operators. 48 28. Prefer the canonical form of ++ and --. Prefer calling the prefix forms. 50 29. Consider overloading to avoid implicit type conversions. 51 30. Avoid overloading &&,||, or , (comma) . 52 31. Don’t write code that depends on the order of evaluation of function arguments. 54 Class Design and Inheritance 55 32. Be clear what kind of class you’re writing. 56 33. Prefer minimal classes to monolithic classes. 57 34. Prefer composition to inheritance. 58 35. Avoid inheriting from classes that were not designed to be base classes. 60 36. Prefer providing abstract interfaces. 62 37. Public inheritance is substitutability. Inherit, not to reuse, but to be reused. 64 38. Practice safe overriding. 66 39. Consider making virtual functions nonpublic, and public functions nonvirtual. 68 40. Avoid providing implicit conversions. 70 41. Make data members private, except in behaviorless aggregates (C-style structs). 72 42. Don’t give away your internals. 74 43. Pimpl judiciously. 76 44. Prefer writing nonmember nonfriend functions. 79 45. Always provide new and delete together. 80 46. If you provide any class-specific new, provide all of the standard forms (plain, in-place, and nothrow). 82 Contents ix Construction, Destruction, and Copying 85 47. Define and initialize member variables in the same order. 86 48. Prefer initialization to assignment in constructors. 87 49. Avoid calling virtual functions in constructors and destructors. 88 50. Make base class destructors public and virtual, or protected and nonvirtual. 90 51. Destructors, deallocation, and swap never fail. 92 52. Copy and destroy consistently. 94 53. Explicitly enable or disable copying. 95 54. Avoid slicing. Consider Clone instead of copying in base classes. 96 55. Prefer the canonical form of assignment. 99 56. Whenever it makes sense, provide a no-fail swap (and provide it correctly). 100 Namespaces and Modules 103 57. Keep a type and its nonmember function interface in the same namespace. 104 58. Keep types and functions in separate namespaces unless they’re specifically intended to work together. 106 59. Don’t write namespace usings in a header file or before an #include. 108 60. Avoid allocating and deallocating memory in different modules. 111 61. Don’t define entities with linkage in a header file. 112 62. Don’t allow exceptions to propagate across module boundaries. 114 63. Use sufficiently portable types in a module’s interface. 116 Templates and Genericity 119 64. Blend static and dynamic polymorphism judiciously. 120 65. Customize intentionally and explicitly. 122 66. Don’t specialize function templates. 126 67. Don’t write unintentionally nongeneric code. 128 Error Handling and Exceptions 129 68. Assert liberally to document internal assumptions and invariants. 130 69. Establish a rational error handling policy, and follow it strictly. 132 70. Distinguish between errors and non-errors. 134 71. Design and write error-safe code. 137 72. Prefer to use exceptions to report errors. 140 73. Throw by value, catch by reference. 144 74. Report, handle, and translate errors appropriately. 145 75. Avoid exception specifications. 146