C++ Coding Standards - Book Home Page

Home Blog Talks Books & Articles Training & Consulting


On the
RSS feed November 4: Other Concurrency Sessions at PDC
November 3
: PDC'09: Tutorial & Panel
October 26: Hoare on Testing
October 23
: Deprecating export Considered for ISO C++0x

View current errata list

View the Bibliography

C++ Coding Standards by Herb Sutter and Andrei Alexandrescu, the newest book in Bjarne Stroustrup's C++ In Depth series, is the authoritative reference for C++ software development teams. It's the only C++ coding standard with Stroustrup's name on it, and the only one written by two of the top names C++. Both authors draw on their personal extensive real-world project experience at commercial software companies ranging in size from small successful start-ups to RealNetworks to Microsoft. That concrete, in-the-trenches experience shines through in Item after Item as the book covers not only many issues of note in Standard C++ itself, but also includes important material on how Standard C++ interacts with nonstandard but real-world topics like dealing with threading and concurrency, handling application scalability, and correctly designing and deploying modules (including shared libraries and DLLs).

Overview: This book delivers a valuable set of tried-and-true rules, guidelines, and best practices condensed into 101 concise one- and two-page Items. But this book is something more: It also acts as an index into the worldís C++ literature because each Item includes copious references that, in all, cite nearly 100 different top books and articlesófrom Brooksí classic The Mythical Man-Month to Vandevoorde and Josuttisí cutting-edge C++ Templates to the authorsí own previous booksóand distill the scattered advice and guidelines into one authoritative handbook.

Contents: The topical sections it covers are: Organizational and Policy Issues; Design Style; Coding Style; Functions and Operators; Class Design and Inheritance; Construction, Destruction, and Copying; Namespaces and Modules; Templates and Genericity; Error Handing and Exceptions; STL: Containers; STL: Algorithms; and Type Safety.

Each Item is laid out as follows:

Item title: The simplest meaningful sound bite we could come up with as a mnemonic for the rule.

Summary: The most essential points, briefly stated.

Discussion: An extended explanation of the guideline. This often includes brief rationale, but remember that the bulk of the rationale is intentionally left in the References.

Examples (if applicable): Examples that demonstrate a rule or make it memorable.

Exceptions (if applicable): Any (and usually rare) cases when a rule doesn't apply. But beware the trap of being too quick to think: "Oh, I'm special; this doesn't apply in my situation" -- that rationalization is common, and commonly wrong.

References: See these parts of the C++ literature for the full details and analysis.

A landmark book that belongs on every C++ development team's bookshelf and reading list.


Reviewers Say

Chuck Allison, on Amazon.com:

You have never seen a book quite like this before. When the authors of this book speak, the C++ community listens, but together they have outdone themselves, and you and I are the happy beneficiaries. This is the first ďcoding standardsĒ book Iíve seen that works. The organization is clear and intuitive, the topics are pertinent, and the content is of the highest quality. All the standards contained herein have been rigorously scrutinized (I have hundreds of emails to prove it!) by a generous sampling of the leading contributors in the C++ world, as attested by the acknowledgements in the Preface.

More than just style guidelines and ďgotchaĒ warnings, C++ Coding Standards clarifies the idioms and practices that pertain specifically to successful C++ software. Even better, you canít avoid deepening your mastery of the finer points of C++ as you read. This is the singularly authoritative Writ of Common Wisdom for the entire C++ development experience.

-- Chuck Allison Editor, The C++ Source

Thanks, Chuck!

Table of Contents


Organizational and Policy Issues

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

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

14. Prefer compile- and link-time errors to run-time errors. 28

15. Use const proactively. 30

16. Avoid macros. 32

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

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

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

Construction, Destruction, and Copying

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

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

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

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

STL: Containers

76. Use vector by default. Otherwise, choose an appropriate container. 150

77. Use vector and string instead of arrays. 152

78. Use vector (and string::c_str) to exchange data with non-C++ APIs. 153

79. Store only values and smart pointers in containers. 154

80. Prefer push_back to other ways of expanding a sequence. 155

81. Prefer range operations to single-element operations. 156

82. Use the accepted idioms to really shrink capacity and really erase elements. 157

STL: Algorithms

83. Use a checked STL implementation. 160

84. Prefer algorithm calls to handwritten loops. 162

85. Use the right STL search algorithm. 165

86. Use the right STL sort algorithm. 166

87. Make predicates pure functions. 168

88. Prefer function objects over functions as algorithm and comparer arguments. 170

89. Write function objects correctly. 172

Type Safety

90. Avoid type switching; prefer polymorphism. 174

91. Rely on types, not on representations. 176

92. Avoid using reinterpret_cast. 177

93. Avoid using static_cast on pointers. 178

94. Avoid casting away const. 179

95. Donít use C-style casts. 180

96. Donít memcpy or memcmp non-PODs. 182

97. Donít use unions to reinterpret representation. 183

98. Donít use varargs (ellipsis). 184

99. Donít use invalid objects. Donít use unsafe functions. 185

100. Donít treat arrays polymorphically. 186

Bibliography (7 pages)

Summary of Summaries (13 pages)

Index (12 pages)

Copyright © 2009 Herb Sutter