A Practical Guide to C++

From WeChat Official Account: InfoQ

Author | Bartlomiej FilipekTranslator | Wang QiangEditor | Wan Jia

C++ is evolving rapidly! For instance, the page count of the C++ standard has increased from 879 pages in C++98/03 to 1834 pages in C++20, an increase of nearly 1000 pages! More importantly, with each revision of C++, we gain dozens of new features. Do you need to learn all of these to write good code? How can you stay sane in today’s C++ world?IntroductionYou may know that C++ is a complex language. I even found an entire page on Wiki dedicated to criticisms of C++. Modern C++ has added even more content to the ecosystem.Here is the complete data on the page count I mentioned earlier:

  • C++98/03 – 879, N1905, October 2005
  • C++11 – 1324, Final Draft, N3337, January 2012
  • C++14 – 1368, Final Draft, November 2014
  • C++17 – 1586, Draft, N4606
  • C++20 – 1834, Draft, N4861

A Practical Guide to C++It seems that C++17 is almost 80% larger than C++98/03, and the latest draft of C++ is nearly 1000 pages longer than C++03. You can complain about the increased complexity, and it can be difficult to learn all of this. But is it really that scary? What can you do in the face of such a situation?First, let’s take a look at some of the issues you might encounter in C++.Some IssuesJust to name a few:

  • Too slow pace
  • Too fast pace
  • Confusion/complexity of features
  • Slow compilation time
  • Lack of dependency management

Let’s examine these closely.Too Slow PaceIn 2017, we welcomed C++17. While having a new standard every three years is great, many developers complain that the new versions are not what everyone was hoping for.Many features, such as concepts, modules, ranges, coroutines, etc., have not been accepted, and we will have to wait at least another three years for them to enter the standard.In 2020, C++20 was ready, and these important features will be provided with the compiler! But we still complain that contracts haven’t been added, and reflection, executors, or networking are still under discussion. They may appear in C++23 or even later versions.It seems that some features are slow to be accepted… and there is always something to complain about.Too Fast PaceAs usual, we may have two conflicting opinions here. While for some, the upgrade pace is slow, for others, it is hard to keep up with the changes.You just learned C++11/14… now you need to update your knowledge to C++17, and C++20 is on the way. Three years is not that short a time, but remember, compiler consistency, company policies, and team guidelines may progress at different paces.Does your company immediately update to the latest C++ version or wait a few years?Confusion/Complexity of FeaturesJust read this comment:CallMeDonk:

I love C++. It is my language of choice, but you have to admit that its implementation of value classes is quite bizarre. Most programmers, including myself, prefer simple, well-defined language structures rather than strange and complex syntax.

Is C++ clear in all aspects? Probably not…Here are some topics that may be difficult to understand and could confuse programmers:Move SemanticsThe principle of move semantics is very clear: do not copy, but try to “steal” the internal structure of managed resources, and you should achieve good performance improvements. But the devil is in the details.I don’t write a lot of generic code, so fortunately, I don’t have to think about move semantics all the time. However, I get confused when I encounter move and const – see my previous article on the subject. I don’t believe all C++ developers will understand the rules here. Especially now you need to remember the six default operations generated by the compiler: default constructor, destructor, copy constructor, move constructor, assignment operator, and move assignment operator.Rvalues/xvalues/prvalues… myValues, fooValuesThe last one I made up… but there are so many value categories that it is really headache-inducing!In C (or C++98/03), you only needed to know about lvalues and rvalues, now it has become a bit subtle.However, the question is whether you need to remember it?Some nice comments:c0r3ntin:

It is complex, but you don’t encounter it every day. Can this value be addressed? Can it be copied? Can it be moved? Should it be moved? You only need to clarify and fully understand them in very few cases (template library writing, hot paths, etc.). Most of the time, C++ is not more complex than Java or anything else. Sadly, most people forget this. C++ may be the most complex language, but you can write very good code without worrying about the specific details. BigObject o=getBigObject();

InitializationNow there are 18 ways (since C++17)!See:Initialization in C++ is bonkershttps://www.reddit.com/r/cpp/comments/5p5ed7/initialization_in_c_is_bonkers/?fileGuid=HjDhgwWw6jPKDcCK;r/cpp threadhttps://blog.tartanllama.xyz/initialization-is-bonkers/Templates (and Template Deduction)When I saw all the changes in C++17, I was confused; there were too many details about templates.The same situation occurred in C++20, where we welcomed a significant and long-awaited improvement: concepts – it fundamentally changed C++.However, if you want to learn about templates, you may feel overwhelmed at first.ABIWith the ever-growing list of new features, “fixing” old issues in C++ design from scratch may be an enticing topic. But the principle of this language is not to break old code, so the committee is very strict and does not like to change the course of features that have already been introduced.This issue has no correct answer, but in any case, a well-discussed topic is better than a hasty action.Lack of Dependency Management ToolsWe can complain that C++ has not “delivered” a cool dependency management system. But the reality is that this may not happen in the foreseeable future. Having a “standard” package manager is a tough choice, especially since it has to handle so many available C++ platforms and systems.Not Safe EnoughSome time ago, you could read some articles mentioning this issue (this one and this one):

A Google engineer stated this week that about 70% of serious security vulnerabilities in the Chrome codebase are related to memory management and security issues.

Microsoft is the same. Since most of the code is in C or C++, everyone blames C++ for not being safe enough.Other Issues?What are the main issues you encounter with this language?So far, we have discussed some issues… so how do we deal with them? Is there a chance to solve these problems?How to Stay SaneNo programming language is perfect; every language has its issues. Here are my suggestions on how to deal with modern C++ problems:

  • Stay optimistic
  • Use the best guidelines
  • Use the best tools
  • Keep up with the latest developments
  • Don’t look under the hood
  • Use what you need
  • Incremental changes
  • The bottom line: your old code is still safe and can compile

Stay optimistic, the language is evolvingNo one wants to write code using old syntax and structures. We have seen a lot of complaints about the old versions of C++ before C++11. It took nearly 13 years (from the major C++98, excluding the minor C++03) to propose a new major version: C++11. Now we can happily say we are back on track with some changes every three years. Ultimately, you cannot say your language is dead.While some features are very large and may cause confusion or require learning more, the reality is quite simple:

  • Most of the 1000 new pages added after C++03 are for the standard library. This means you can use more helpers and subsystems without looking for third-party libraries. This will definitely make your life easier.
  • For move semantics, you can rely on library types because they will do the right work for you. For example, you can now safely return<span>std::vector</span> and ensure it may be moved or even deleted without extra copies.
  • As for templates, they are becoming easier to use. Concepts make the code safer without tricks like SFINAE. More importantly, we have<span>constexpr</span> and<span>auto</span>, which make generic code simpler (almost like regular code).
  • As for safety: check out the automated tools for the safety configuration files of the C++ guidelines. New safety rules in C++ Core Check | C++ Team Blog. We can expect new and better tools for code analysis or even detection to quickly identify potential security issues. Or check out this article: Bridging the Gap Between Rust and C++ Using Static Analysis Principles – Sunny Chatterjee – CppCon

Using GuidelinesIf you feel confused about many aspects of C++ code, you should refer to the C++ Core Guidelines. It was created by the enthusiastic C++ development community, with the main editors being Herb Sutter and Bjarne Stroustrup.Check it out here:C++ Core Guidelines @Githubhttps://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md?fileGuid=HjDhgwWw6jPKDcCKThere is a nice website:C++ Core Guidelines: Websitehttps://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines?fileGuid=HjDhgwWw6jPKDcCKJust enter the problem you are facing (for example,<span>return value</span>), and you can easily find suggestions – for example: Guidelines: Return ValuesUsing these guidelines will save you a lot of time, and you can quickly learn some good patterns.And tools!Thanks to Clang and the speed improvements on other platforms, we have the following tools:

  • ClangTidy (formerly clang-modernise)
  • Clang Format
  • Clang Static Analyzer
  • VisualAssist
  • Clion/ResharperC++
  • VisualStudio – tools like C++ Core Checker
  • PVS Studio
  • Clang Power Tools for VisualStudio
  • New C++ Core Check rules | C++ Team Blog
  • C++ Core Guidelines Checker Reference | Microsoft Documentation
  • Introducing vcperf/timetrace for C++ build time analysis | C++ Team Blog
  • New safety rules in C++ Core Check | C++ Team Blog – Is C++ as safe as Rust?

Or check out my article on other tools:C++ Ecosystem: Compilers, IDEs, Tools, Testing, etc.https://www.cppstories.com/2019/10/cppecosystem/?fileGuid=HjDhgwWw6jPKDcCKWhile it is not as good as other languages (mainly Java or .NET based), it is getting better and better. Keep in mind that due to the complexity of C++ syntax, it is difficult to implement tools that analyze code instantly.Efforts to Keep Up with the Latest DevelopmentsThe C++ community is very active. There are many blogs, books, conferences… and there may even be local communities in your city.First, I recommend visiting isocpp.org to check all events/news/articles. Then you can look at Meeting C++ and information about local C++ groups. Also, check out reddit/cpp, where you can see some of the best C++ stories.There is also CppCast – a weekly podcast for C++ developers.And refer to the following books:

  • The C++ Programming Language, 4th Edition
  • Effective Modern C++
  • Programming: Principles and Practice Using C++
  • Discovering Modern C++: An Accelerated Course for Scientists, Engineers, and Programmers
  • C++ in a Nutshell (C++ Deep Dive Series), 2nd Edition

You can also check out the recommended C++ resources list:Bartek’s Programming Blog:https://www.cppstories.com/p/resources/?fileGuid=HjDhgwWw6jPKDcCKToo Many Details?One of the reasons C++ is so powerful is that it allows you to implement code very close to the hardware. You can control all the details, memory layout, performance optimizations, etc… However, these capabilities add to the complexity of the language.However, if you don’t need to go that far, you can stay at a relatively high level of abstraction.For example, you don’t need to write optional types because you can use<span>std::optional</span> from the standard library. If you don’t want to deal with low-level and error-prone union types, you should realize that<span>std::variant</span> is a safe option.Use What You NeedC++ is a multi-paradigm language; you can use it in many different ways. Recently, I read an interesting comment that C++ programmers can perform excellently for years without touching advanced topics like template metaprogramming or exceptions. This largely depends on the coding style of the project.For example, even companies like Google restrict C++ features, such as not using exceptions.If you are not a library developer, you may not encounter the trouble of custom move operators or move constructors. Similarly, advanced metaprogramming may not be a critical part of your code.Incremental ChangesIf you are starting from scratch or have only a small codebase, then transitioning to C++11/14 should be relatively easier. But what about millions of lines of code created 20 years (or longer!) ago?Just take it step by step.At least for new code, you should start using modern C++. Additionally, by applying the “Scout Rule,” you can improve the code you come into contact with.This may lead to some mixed code, but it is still better than just keeping the old style.The bottom line: your old code can still compileOne reason the C++ standard is getting larger is that the language is backward compatible. So the committee usually introduces new features but rarely removes old ones. So… your code can still compile. If you don’t want to move forward, don’t want to use new things, then you can still maintain your current style.Sometimes you will receive warnings about deprecated or removed features (like<span>auto_ptr</span><code><span> in C++17), but even in such cases, you can switch the compiler to some older C++ standard.</span><span>Conclusion</span><span>This article has some complaints and some "beautification." I tried to identify various issues present in this language and its evolution, as well as some positive signs of improvement. While we can complain about complexity, the pace of change, etc., I believe we cannot say that this language is dead. That is a good thing! :)</span><span>I think you don't have to rush to chase new features and immediately rewrite existing code. Try to keep up with the progress, use features that genuinely improve your work, and your code should gradually improve and become more "modern" (this is definable, see related articles on meetingcpp http://meetingcpp.com/index.php/br/items/what-does-modern-c-really-mean.html?fileGuid=HjDhgwWw6jPKDcCK).</span><ul><li><span>What is your approach to adopting new features in C++11/14/17/20?</span></li><li><span>What are the main issues you face when using C++?</span></li><li><span>Do you use modern C++ in your work?</span></li></ul><span><strong><span>Original Link:</span></strong></span><span>https://www.cppstories.com/2017/02/how-to-stay-sane-with-modern-c/</span><figure><span>--- EOF ---</span></figure><span><span><strong>Recommended ↓↓↓</strong></span></span>

Leave a Comment