Beautiful C++: 30 Core Guidelines for Writing Clean, Safe, and Fast Code
Conquer the Complexity of Modern C++
” Beautiful C++ presents the C++ Core Guidelines from a developer’s point of view with an emphasis on what benefits can be obtained from following the rules and what nightmares can result from ignoring them. For true geeks, it is an easy and entertaining read. For most software developers, it offers something new and useful.”
–Bjarne Stroustrup, inventor of C++ and co-editor of the C++ Core Guidelines
Writing great C++ code needn’t be difficult. The C++ Core Guidelines can help every C++ developer design and write C++ programs that are exceptionally reliable, efficient, and well-performing. But the Guidelines are so jam-packed with excellent advice that it’s hard to know where to start. Start here, with Beautiful C++.
Expert C++ programmers Guy Davidson and Kate Gregory identify 30 Core Guidelines you’ll find especially valuable, and offer detailed practical knowledge for improving your C++ style. For easy reference, this book is structured to align closely with the official C++ Core Guidelines website.
Throughout, Davidson and Gregory offer useful conceptual insights and expert sample code, illuminate proven ways to use both new and longstanding language features more successfully, and show how to write programs that are more robust and performant by default.
- Avoid “bikeshedding”: stop wasting valuable time on trivia
- Don’t hurt yourself by writing code that will cause problems later
- Know which legacy features to avoid and the modern features to use instead
- Use newer features properly, to get their benefits without creating new problems
- Default to higher-quality code that’s statically type-safe, leak resistant, and easier to evolve
- Use the Core Guidelines with any modern version of C++: C++20, C++17, C++14 or C++11
Whether you’ve worked with C++ for decades or you’ve only recently focused on it, there’s something here to improve virtually every program you write, design, or maintain.
Cover Page About This eBook Halftitle Page Title Page Copyright Page Pearson’s Commitment to Diversity, Equity, and Inclusion Contents Selected C++ Core Guidelines Foreword Preface About This Book Access the Code Acknowledgments About the Authors Section 1: Bikeshedding is bad Chapter 1.1. P.2: Write in ISO Standard C++ What is ISO Standard C++? Encapsulating variations Learning the old ways Staying on top of developments to the standard Chapter 1.2. F.51: Where there is a choice, prefer default arguments over overloading Introduction Refining your abstraction: Additional arguments or overloading? The subtleties of overload resolution Back to the example The unambiguous nature of default arguments Alternatives to overloading Sometimes you must overload Summary Chapter 1.3. C.45: Don’t define a default constructor that only initializes data members; use in-class member initializers instead Why have default constructors anyway? How do you initialize a data member? What happens when two people maintain a class? Summary Chapter 1.4. C.131: Avoid trivial getters and setters An archaic idiom Abstraction Mere Encapsulation Class Invariants Nouns and Verbs Summary Chapter 1.5. ES.10: Declare one name (only) per declaration Let me introduce you Backward compatibility Writing clearer declarations Structured binding Summary Chapter 1.6. NR.2: Don’t insist to have only a single return-statement in a function Rules evolve Ensuring cleanup Using RAII Writing good functions Summary Section 2: Don’t hurt yourself Chapter 2.1. P.11: Encapsulate messy constructs, rather than spreading through the code All in one gulp What it means to encapsulate a messy construct The purpose of language and the nature of abstraction Levels of abstraction Abstraction by refactoring and drawing the line Summary Chapter 2.2. I.23: Keep the number of function arguments low How much should they earn? Simplifying matters through abstraction Do as little as possible, but no less Real-life examples Summary Chapter 2.3. I.26: If you want a cross-compiler ABI, use a C-style subset Creating libraries What is an ABI? Paring back to the absolute minimum Exception propagation Summary Chapter 2.4. C.47: Define and initialize member variables in the order of member declaration Summary Chapter 2.5. CP.3: Minimize explicit sharing of writable data Traditional execution model Wait, there’s more Avoiding deadlocks and data races Setting aside locks and mutexes Summary Chapter 2.6. T.120: Use template metaprogramming only when you really need to std::enable_if => requires Summary Section 3: Stop using that Chapter 3.1. I.11: Never transfer ownership by a raw pointer (T*) or reference (T&) Using the free store The performance cost of smart pointers Using unadorned reference semantics gsl::owner Summary Chapter 3.2. I.3: Avoid singletons Global objects are bad Singleton Design Pattern Static initialization order fiasco How to hide a singleton But only one of these should ever exist Wait a moment… Summary Chapter 3.3. C.90: Rely on constructors and assignment operators, not memset and memcpy Chasing maximum performance The horrendous overhead of the constructor The simplest possible class What is the standard talking about anyway? But what about memcpy? Never underestimate the compiler Summary Chapter 3.4. ES.50: Don’t cast away const Story time Dealing with rather more data The const firewall Implementing a dual interface Caching and lazy evaluation Two types of const Surprises with const Summary Chapter 3.5. E.28: Avoid error handling based on global state (e.g. errno) Error handling is hard C and errno Return codes Exceptions <system_error> Boost.Outcome Why is error handling so hard? Light at the end of the tunnel Summary Chapter 3.6. SF.7: Don’t write using namespace at global scope in a header file Don’t do this Disambiguation Using using Where do the symbols go? An altogether more insidious problem Solving the problem of cluttered scope resolution operators The temptation and The Fall Summary Section 4: Use this new thing properly Chapter 4.1. F.21: To return multiple “out” values, prefer returning a struct or tuple The shape of a function signature Documenting and annotating Now you can return an object You can also return a tuple Passing and returning by non-const reference Summary Chapter 4.2. Enum.3: Prefer class enums over “plain” enums Constants Scoped enumerations Underlying type Implicit conversion Summary Postscript Chapter 4.3. ES.5: Keep scopes small The nature of scope Block scope Namespace scope Class scope Function parameter scope Enumeration scope Template parameter scope Scope as context Summary Chapter 4.4. Con.5: Use constexpr for values that can be computed at compile time From const to constexpr Default C++ Using constexpr inline consteval constinit Summary Chapter 4.5. T.1: Use templates to raise the level of abstraction of code Story time Raising the level of abstraction Function templates and abstraction Class templates and abstraction Naming is hard Summary Chapter 4.6. T.10: Specify concepts for all template arguments How did we get here? Constraining your parameters How to abstract your concepts Factoring via concepts Summary Section 5: Write code well by default Chapter 5.1. P.4: Ideally, a program should be statically type safe Type safety is a security feature of C++ Union Casting Unsigned Buffers and sizes Summary Chapter 5.2. P.10: Prefer immutable data to mutable data The wrong defaults constness in function declarations Summary Chapter 5.3. I.30: Encapsulate rule violations Hiding the unsightly things in life Keeping up appearances Summary Chapter 5.4. ES.22: Don’t declare a variable until you have a value to initialize it with The importance of expressions and statements C-style declaration Declare-then-initialize Maximally delayed declaration Localization of context-specific functionality Eliminating state Summary Chapter 5.5. Per.7: Design to enable optimization Maximizing the frame rate Working further from the metal Optimization through abstraction Summary Chapter 5.6. E.6: Use RAII to prevent leaks Deterministic destruction Leaking away files Why are we bothering? This all seems a bit much: Future possibilities Where can I get this? Envoi Afterword Index Code Snippets
1. Disable the AdBlock plugin. Otherwise, you may not get any links.
2. Solve the CAPTCHA.
3. Click download link.
4. Lead to download server to download.