C++23 Best Practices (Jason Turner) (Z-Library)
Author: Jason Turner
商业
No Description
📄 File Format:
PDF
💾 File Size:
822.0 KB
21
Views
0
Downloads
0.00
Total Donations
📄 Text Preview (First 20 pages)
ℹ️
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
📄 Page
1
(This page has no text content)
📄 Page
2
C++23 Best Practices Jason Turner This book is for sale at http://leanpub.com/cpp23_best_practices This version was published on 2024-01-01 This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools andmany iterations to get reader feedback, pivot until you have the right book and build traction once you do. © 2024 Jason Turner
📄 Page
3
Tweet This Book! Please help Jason Turner by spreading the word about this book on Twitter! The suggested tweet for this book is: I just bought Jason Turner’s C++23 Best Practices book! The suggested hashtag for this book is #cpp23_best_practices. Find out what other people are saying about the book by clicking on this link to search for this hashtag on Twitter: #cpp23_best_practices
📄 Page
4
For my wife, Jen.
📄 Page
5
Contents Part I: Introduction and Philosophy of Good C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1: Introduction To The C++23 Edition . . . . . . . . . . . . . . . . . . . . . . 2 2: Introduction To The Original Edition . . . . . . . . . . . . . . . . . . . . . 3 3: About Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 4: Slow Down . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 5: Use AI Coding Assistants Judiciously . . . . . . . . . . . . . . . . . . . . . 8 6: C++ Is Not Magic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 7: Remember: C++ Is Not Object-Oriented . . . . . . . . . . . . . . . . . . . 11 8: Learn Another Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 9: Know Your Standard Library . . . . . . . . . . . . . . . . . . . . . . . . . . 15 10: Use The Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 11: Don’t Invoke Undefined Behavior . . . . . . . . . . . . . . . . . . . . . . 17 12: Never Test for this To Be nullptr, It’s UB . . . . . . . . . . . . . . . . . 19 13: Never Test for A Reference To Be nullptr, It’s UB . . . . . . . . . . . . 22
📄 Page
6
CONTENTS Part II: Use The Tools . . . . . . . . . . . . . . . . . . . . . . . 24 14: Use the Tools: Automated Tests . . . . . . . . . . . . . . . . . . . . . . . 25 15: Use the Tools: Continuous Builds . . . . . . . . . . . . . . . . . . . . . . 28 16: Use the Tools: Compiler Warnings . . . . . . . . . . . . . . . . . . . . . . 30 17: Use the Tools: Static Analysis . . . . . . . . . . . . . . . . . . . . . . . . . 32 18: Use The Tools: Consider Custom Static Analysis . . . . . . . . . . . . . 34 19: Use the Tools: Sanitizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 20: Use The Tools: Hardening . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 21: Use the Tools: Multiple Compilers . . . . . . . . . . . . . . . . . . . . . . 40 22: Use The Tools: Fuzzing and Mutating . . . . . . . . . . . . . . . . . . . . 42 23: Use the Tools: Build Generators . . . . . . . . . . . . . . . . . . . . . . . 49 24: Use the Tools: Package Managers . . . . . . . . . . . . . . . . . . . . . . 52 Part III: API and Code Design Guidelines . . 53 25: Make your interfaces hard to use wrong. . . . . . . . . . . . . . . . . . . 54 26: Consider If Using the API Wrong Invokes Undefined Behavior . . . . 55 27: Be Afraid of Global State . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 28: Use Stronger Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 29: Use [[nodiscard]] Liberally . . . . . . . . . . . . . . . . . . . . . . . . . 62 30: Forget Header Files Exist . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 31: Export Module Overloads Consistently . . . . . . . . . . . . . . . . . . . 68
📄 Page
7
CONTENTS 32: Prefer Stack Over Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 33: Don’t return raw pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 34: Know Your Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 35: Be Aware of Custom Allocation And PMR . . . . . . . . . . . . . . . . . . 77 36: Constrain Your Template Parameters With Concepts . . . . . . . . . . 80 37: Understand consteval and constinit . . . . . . . . . . . . . . . . . . . 84 38: Prefer Spaceships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 39: Follow the Rule of 0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 40: If You Must Do Manual Resource Management, Follow the Rule of 5 . 92 Part IV: Code Implementation Guidelines 95 41: Don’t Copy and Paste Code . . . . . . . . . . . . . . . . . . . . . . . . . . 96 42: Prefer formatOver iostreamOr c-formatting Functions . . . . . . . . 98 43: constexpr All The Things! . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 44: Make globals in headers inline constexpr . . . . . . . . . . . . . . . . 106 45: const Everything That’s Not constexpr . . . . . . . . . . . . . . . . . . . 108 46: Always Initialize Your non-const, non-auto Values . . . . . . . . . . . 112 47: Prefer auto in Many Cases. . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 48: Use Ranges and Views For Correctness and Readability . . . . . . . . 121 49: Don’t Reuse Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 50: Prefer Algorithms Over Loops . . . . . . . . . . . . . . . . . . . . . . . . . 127 51: Use Ranged-For Loops When Views and Algorithms Cannot Help . . 129
📄 Page
8
52: Use auto in ranged for loops . . . . . . . . . . . . . . . . . . . . . . . . . . 131 53: Avoid default In switch Statements . . . . . . . . . . . . . . . . . . . . 133 54: Prefer Scoped enums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 55: Prefer if constexpr over SFINAE . . . . . . . . . . . . . . . . . . . . . . 140 56: De-template-ize Your Generic Code . . . . . . . . . . . . . . . . . . . . . 146 57: Use Lippincott Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 58: No More new! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 59: Avoid std::bind and std::function . . . . . . . . . . . . . . . . . . . . 154 60: Don’t Use initializer_list For Non-Trivial Types . . . . . . . . . . . 159 61: Consider Designated Initializers (C++20) . . . . . . . . . . . . . . . . . . 161 Part V: Bonus Chapters . . . . . . . . . . . . . . . . . . . . .164 62: Improving Build Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 63: Continue Your C++ Education . . . . . . . . . . . . . . . . . . . . . . . . . 167 64: Thank You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 65: Bonus: Understand The Lambda . . . . . . . . . . . . . . . . . . . . . . . 172
📄 Page
9
Part I: Introduction and Philosophy of Good C++
📄 Page
10
1: Introduction To The C++23 Edition It’s been about 3 years since I originally released the first edition of C++Best Prac- tices. At the time of release, the book did not contain much C++20 information. I chose to release theC++20updates (knownas the2ndEdition) for free toanyone who had purchased the Leanpub ebook version. I considered releasing this C++23 update also as a free 3rd Edition. However, as I considered the updates that needed to occur, I decided it was time for an entirely new releaseof thebook. This newbook is neededmainlybecauseC++23 changes many fundamental thingswithhowweuse the language (suchas standard library modules). But the break from the previous version also allows me to reorganize the topics for better flow. I had avoided reorganizationwith any previous update to avoid confusion (so coworkers would reference item 12 and know they were all talking about the same item). I have updated every relevant section of this book to represent how code should look in C++23, and reorganized many topics. Rest assured, this is a large update to the original C++ Best Practices book! I try to apply all Best Practices in every example where they are appropriate. This might make the examples more complex than they need to be, but it decreases the chances that an example will be seen out of context and incom- plete. 2
📄 Page
11
2: Introduction To The Original Edition My goal as a trainer and a contractor (seems to be) toworkme out of a job. I want everyone to: 1. Learn how to experiment for themselves 2. Not just believe me, but test it 3. Learn how the language works 4. Stopmaking the samemistakes of the last generation I’m thinking about changing my title from “C++ Trainer” to “C++ Guide.” I always adapt my courses and material to the class I currently have. We might agree on a class about X, but I change it to Y halfway through the first day to meet the organization’s needs. Along the way, we experiment and learn as a group. I often also learn while teaching. Every group is unique; every class has new questions. Many of the questions I get in classes are the same ones repeatedly to the point where I get to look like amind reader as I anticipate the next question that will be asked. Hence, this book, and the Twitter thread that it came from, to help spread the word on the long-standing best practices. I wrote the book I wanted to read. It is intentionally straightforward, short, to the point, and has specific action items. 3
📄 Page
12
3: About Best Practices Best Practices, quite simply, are about 1. Reducing commonmistakes 2. Finding errors quickly 3. Without sacrificing (and often improving) performance 3.1: Why Best Practices? First and foremost, let’s get this out of the way: 3.1.1: Your Project Is Not Special If you are programming in C++, you, or someone at your company, cares about performance. Otherwise, they’d probably be using some other programming language. I’ve been to many companies who all tell me they are special because they need to do things fast! Spoiler alert: they are all making the same decisions for the same reasons. There are very few exceptions. The outliers who make different decisions: they are the organizations that are already following the advice in this book. 3.2: What’s The Worst That Can Happen? I don’t want to be depressing, but let’s take a moment to ponder the worst-case scenario if your project has a critical flaw. 4
📄 Page
13
About Best Practices 5 Game Serious flaws lead to remote vulnerabilities or attack vectors. Financial Serious flaws lead to large amounts of lost money, accelerating trades, market crash1. Aerospace Serious flaws lead to lost spacecraft or human life2. Your Industry Serious flaws lead to… Lost money? Lost jobs? Remote hacks? Worse? 3.3: Examples Examples throughout this book use struct instead of class. The only difference between struct and class is that struct has all members and base classes by default public. Using structmakes examples shorter and easier to read. 3.4: Exercises Eachsectionhasoneormoreexercises. Mostdonothavea rightorwronganswer. Exercise: Look for exercises Throughout the following chapters, you’ll see exercises like this one. Look for them! Exercises are: 1https://en.wikipedia.org/wiki/2010_flash_crash 2https://spectrum.ieee.org/aerospace/aviation/how-the-boeing-737-max-disaster-looks-to-a-software- developer
📄 Page
14
About Best Practices 6 • Practical, and apply to your current code base to see immediate value. • Make you think and understand the language a little bit deeper by doing your own research. 3.5: Links and References I’ve made an effort to reference those who I learned from and link to their talks where possible. If I’ve missed something, please let me know.
📄 Page
15
4: Slow Down Dozens of solutions exist in C++ for any given problem. Dozens of more opinions exist for which of these solutions are the best. Copying and pasting from one application to another is easy. Forging aheadwith the solutions you are comfort- able with is easy. How many times have you said, “wow, this is going to take a complicated class hierarchy to implement this solution?” Or what about “I guess I need to add macros here to implement these common functions.” • If the solution seems large or complex, stop. • Now is a good time to go for a walk and ponder the solution. • When you’re done with your walk, discuss the design with a coworker, pet, or rubber duck1. Still haven’t found a more straightforward solution you are happy with? Ask on Twitter or Slack if you can. The key point is to not forge ahead blindly with the solutions with which you are comfortable. Bewilling to stop for aminute. The older I get, the less time I spend programming, and the more time I spend thinking. In the end, I implement the solution as fast or faster than I used to and with less complexity. 1https://rubberduckdebugging.com/ 7
📄 Page
16
5: Use AI Coding Assistants Judiciously AI codingassistants arebecomeubiquitous,withnearly every IDEand toolhaving something built in. They appear to be rather powerful and are able to generate convincing results. However, these results are not necessarily correct. Therefore, I suggest these Best Practices for using your AI coding assistant. 1. Always double check the results you are given. 2. Use themmostly as a “smart rubber duck”. 3. Always double check the results you are given. 4. Use them to “flatten the learning curve.” If you ask the bot to generate an example of a certain technique or API usage, you’ll likely get a meaningful answer, but one that also has somemistakes in it. 5. Always double check the results you are given. 5.1: Resources • C++ Weekly - Ep 371 - Best Practices for Using AI Code Generators1 1https://www.youtube.com/watch?v=I2c969I-KmM 8
📄 Page
17
6: C++ Is Not Magic This section is just a reminder that we can reason about all aspects of C++. It’s not a black box, and it’s not magic. If you have a question, it’s usually easy to construct an experiment that helps you answer the question for yourself. A favorite tool of mine is this simple class that prints a debugmessage whenever a special member function is called. Figure 1. Understanding object lifetime tool 1 import std; 2 3 struct S { 4 S(){ std::println("S()"); } 5 S(const S &){ std::println("S(const S &)"); } 6 S(S &&){ std::println("S(S &&)"); } 7 S &operator=(const S &){ 8 std::println("operator=(const S &)"); 9 return *this; 10 } 11 S &operator=(S &&){ 12 std::println("operator=(S &&)"); 13 return *this; 14 } 15 ~S() { std::println("~S()"); } 16 }; 9
📄 Page
18
C++ Is Not Magic 10 Exercise: Build your first C++ experiment. Do you have a question about C++ that’s been nagging you? Can you design an experiment to test it? Remember that Compiler Explorer now allows you to execute code. Exercise: Start collecting your experiments. Once you have created an experiment and test, be sure to save it. Consider using GitHub gists as a simple way to save and share your tests with others. 6.1: Resources • A quick start example with Compiler Explorer.1 1https://godbolt.org/z/3eGP56
📄 Page
19
7: Remember: C++ Is Not Object-Oriented I’m not the first person to state this, and I won’t be the last. I think this concept is nowwell accepted, but I still see learners of C++ focusing on “OOP.” Bjarne Stroustrup in The C++ Programming Language 3rd Edition states: C++ is a general-purpose programming language with a bias towards systems programming that • is a better C, • supports data abstraction, • supports object-oriented programming, and • supports generic programming. You must understand that C++ is a multi-discipline programming language to make the most of the language. C++ supports effectively all of the programming paradigms that exist today. • Procedural • Functional • Object-Oriented • Generic • Compile-Time (constexpr and template metaprogramming) Knowing when it is appropriate to use each of these tools is the key to writing goodC++. Projects that rigidly stick tooneparadigmmissouton thebest features of the language. 11
📄 Page
20
Remember: C++ Is Not Object-Oriented 12 Don’t try to use every technique possible all of the time. Youwill end up with a mess of difficult to maintain and read code. Appropriately using the appropriate techniques at the appropriate times takes discipline and practice. Exercise: Question your current design. If you could break out of the current design your project is using, whatwould you do differently? 7.1: Resources • Functional Programming in C++1 • C++ Weekly Ep 137: C++ Is Not an Object Oriented Language2 1https://www.manning.com/books/functional-programming-in-c-plus-plus?a_aid=FPinCXX&a_bid=441f12cc 2https://youtu.be/AUT201AXeJg
The above is a preview of the first 20 pages. Register to read the complete e-book.