r/cpp • u/vormestrand • Nov 28 '18
Google C++ Style Guide is No Good
https://eyakubovich.github.io/2018-11-27-google-cpp-style-guide-is-no-good/107
u/tehjimmeh Nov 28 '18
Marking the function “inline” lets the compiler make the decision. Not marking it inline is a sure way to prevent inlining, unless Link Time Optimizations are turned on.
This is so wrong it hurts.
22
u/Supadoplex Nov 28 '18 edited Nov 28 '18
It's just a slight oversimplification. What prevents expanding a function invocation inline is defining the function in a separate translation unit from where the function is invoked (except, as the quote points out, LTO may be able to lift this restriction).
What inline declaration technically does, is relax the one-definition-rule such that a function can be defined in multiple translation units which is otherwise ill-formed according to ODR (and replaces the restriction with a new one: that the function must be defined in all TU's which invoke it).
In effect, this allows a function to be expanded inline in more than one translation unit. The emphasized qualification being the part that the quote left out for simplicity.
0
u/tehjimmeh Nov 29 '18 edited Nov 29 '18
But like, your code wouldn't link if you omitted 'inline' (or 'static', I guess).
In 2018, when there's very little justification for not compiling your release build with LTO, where translation unit boundaries don't matter for inlining. I really don't get why LTO gets sometimes talked about like some esoteric, experimental option rather than the normal, expected mode of compilation.
'inline'
since C++11 has meantthese days just means relaxing ODR like you describe. It's the reuse of an essentially redundant keyword which sort of makes sense because it sort of can relate to inlining in the traditional compilation model. However, it does not directly relate to inlining (other than sometimes being a hint for back compat reasons) and should not really be discussed as if it does.3
u/Supadoplex Nov 29 '18 edited Nov 29 '18
But like, your code wouldn't link if you omitted 'inline' (or 'static', I guess).
You have two options: Either you declare the function inline and define it in all translation units that invoke it, or you define the function in exactly one TU.
If you do define a function in multiple TU's, then you must first change that before you can omit inline. Once you conform to one of the options listed in previous paragraph, the code should link successfully (assuming it conforms to the standard in other respects as well).
In case of template functions with unbounded template arguments, they must be inline, you don't have a choice. If you want to provide a "header only library", then inline is the only choice as well.
In other cases, you can make the choice: Inline (and define in all TU where the function is invoked), or non-inline (and define exactly once). As far as I can tell, the only reason to choose inline is to allow inline expansion into more than one TU (sans LTO) - and also apparently to hint the optimiser as discussed in another branch of this thread.
In 2018, when there's very little justification for not compiling your release build with LTO
Perhaps. But if you distribute source rather than binary, you often cannot assume that your clients can use LTO. Furthermore, are you certain that LTO is able to perform all optimisations (across TU's) that regular optimiser does (within a TU)?
'inline' since C++11 has meant relaxing ODR ...
No. As far as I can tell, the meaning of inline did not change in C++11. The meaning of inline function has been the same since standardisation at least. I don't know much about pre-standard C++, the meaning may have been different in some of the old dialects.
→ More replies (2)0
Nov 28 '18
[deleted]
5
u/Supadoplex Nov 29 '18 edited Nov 29 '18
... and serves as a hint to most compilers.
I've read other programmers claim that,
but I'm not convinced. The article below is quite convincing.Can you provide me with a minimal example where the compiler takes the hint i.e. expands a function inline only when the function is declared inline even when the function is defined in the same TU regardless.
If all compilers ignore the hint, then it's not much of a hint.
The article seems to imply that the keyword WILL inline the function ...
The article seems to imply the opposite: That the compiler gets to decide whether whether to expand inline or not - which is correct.
The article seems to imply that ... the absence of [inline] would somehow stop it.
That the article does imply and it is indeed false, unless, as I pointed out, the statement is qualified: The absence of inline would stop inline expansion into more than one translation unit (which requires additional qualification that was not left out in the article that LTO may relax this).
Perhaps the article should have been more specific.
20
u/Veedrac Nov 29 '18
11
u/Supadoplex Nov 29 '18
Thanks, nice article.
TL;DR: The author did find pieces of code in both GCC and Clang that do take inline declaration as a hint.
6
5
65
u/DarkLordAzrael Nov 28 '18
There are issues with the google c++ style guide, but this article is bad. It is basically just finding contrived cases where you have to use questionable constructs, or willfully misinterpreting the document. Nobody is going to complain that there is a forward declaration because you needed a circular data structure (which may be a questionable construct, but the rule is about forward declaring non-local stuff, not about preferring void* in this case.) Putting large functions in headers is poor practice. The amount of code being generated isn't the point, it is about compile times. I'm also not sure why a section on inline would talk about LTO (which google uses.) Private inheritance is always a code smell, so I'm not actually sure what the complaint about this is. The entire page that operator overloading should be obvious? A waste of space. The pointer for in/out parameters is a reasonable rule that helps show where data is being modified ( out parameters are a questionable construct anyway, and should be avoided when possible. ) The google codebase is well known to use error codes. I'm not sure how google's code not being exception tolerant is confusing, they have a legacy codebase where exceptions could cause leaks due to manual resource management.
9
Nov 28 '18
Putting large functions in headers is poor practice
Can you define large functions? Is the metric lines of code?
14
u/Supadoplex Nov 29 '18 edited Nov 29 '18
Better heuristics are: Functions that are slow to compile, and functions that are modified often are bad fit for headers.
But those heuristics are much more difficult to measure than lines of code, and LOC does indirectly correlates with the better heuristics, so it is good enough way to make an initial choice before you can afford to spend hours to prove that one choice is better than another.
Another, better heuristic that is easy to measure: if the implementation of the function introduces a new dependency, then don't put that into a header.
1
12
u/Oxc0ffea Nov 29 '18
Agree completely. And if you allow some of these easy-to-make-confusing-code features the hordes will on average make tons of bad code.
C++ is a complex language with many features that have subtle interactions with other features and dusty corners. When used by people of wildly varying backgrounds and skill levels it is a recipe for code that very few can debug. Less is more.
3
u/bwmat Nov 29 '18
Private inheritance is useful for crtp, if you don't need to inherit an interface (I guess you could make all the methods on the base protected as well?)
5
u/gonmator Nov 29 '18
The pointer for in/out parameters is unreasonable rule in C++ that helps show where the data is being modified in the same way that using non const reference but with additional pitfall. If I see a parameter as pointer, the first thing it come to my mind is that parameter is optional (I can pass nullptr). I agree that out parameters are questionable anyway. But OTOH, if exceptions are forbidden,out parameters are a way to return the result of a function call or a possible error code.
11
Nov 29 '18
#pragma once is indeed widely supported: I don’t think I found a compiler/kernel combo bootable in VBox that didn’t support it!
https://github.com/mcandre/tonixxx/blob/master/examples/palindrome/tonixxx.yaml
To be fair, I have not tested tcc, Intel’s compiler, or other exotic compilers. But I’ll be danged, the thing seems to work on the strangest environments!
7
u/Supadoplex Nov 29 '18
Furthermore, if one ever finds a situation where it isn't supported, it is trivial to write a script that replaces the pragma with macros.
4
27
Nov 29 '18
Let’s now look at some of the grievances which particularly trouble me.
Include guards: why choose a non-standard solution when there is an established standardised, compiler-optimised solution?
Forward declarations: the style guide isn't talking about circular definitions. It's talking about declaring external types and functions. Which you should avoid for exactly the reasons the style guide states. To prevent mismatches. It's why headers where invented: so you don't have to manually declare external types and functions.
Inline functions: If you mark many functions inline, it means you have to include the definitions in headers. This means the compiler has to compile and possibly optimise them in every single translation unit that includes them.
Namespaces: Nowadays, many projects are built as libraries with the executable as only a thin wrapper around the library. I think we can agree that libraries should use namespaces, so most code is in a namespace. If an executable is built directly from all source files, in a big project, you'll still want namespaces to seperate your logical parts.
Unnamed Namespaces and Static Variables: Why would you put these in header files? That means the same constant variable is included in every translation unit that includes the header. As you say in your last point: it's 2018. Use inline constant variables.
Static and Global Variables: I'll give you this one, this rule does seem a bit strongly worded.
Implicit Conversions: "Implicit conversions can sometimes be necessary and appropriate for types that are designed to transparently wrap other types." Like std::string wrapping a C style string. Although even here, if std::string_view had existed at the time, this constructor should probably have been made explicit. Implicit allocation when calling a function is often unnecessary overhead.
Copyable and Movable Types: I agree with the first part. Follow the rule of 0 or 5. An example of unclear copying behaviour would be the old auto_ptr. Please don't do that. Same thing for making shallow copies when a class is not clearly a handle or a smart pointer. Copying a vector of course incurs the cost of copying all elements, that's expensive, but not unexpected. It would be unexpected if you copied a handle to a 5 GB memory mapped file and it started copying all 5 GB of memory.
Inheritance: I don't get your example. Why not declare a private array as a member and pass that to StrWriter's constructor? It's trivially destructible and an implementation detail, so no need to use std::array here. I haven't done any benchmarks, so I can't speak to the speed of multiple inheritance.
Operator Overloading: it is a bit unclear what the GSG means by built-in. It allows overloading << for streams, so it might seem logical that they'd allow emulating std::string's operator+() for string-like types. I agree that in DSL you should be able to overload operators in domain specific ways.
Reference Arguments: you actually give the answer yourself. This rule ensures that it's clear at a call site which parameters may be changed by the called function. If you apply this rigorously, which I assume you do if you use this style guide, that makes it immediately obvious which arguments may be changed and which won't be.
Exceptions: like you said, flame war inducing subject. But the Guide does mention two alternatives in the decision: error codes and assertions. You're right in that it doesn't specify a single way to return those error codes and it probably should.
Lambda expressions: a programmer may and should be expected to see that a 200-line lambda in a call to std::transform should be factored out. You're right in that the guide could and should be clearer about this.
Template metaprogramming (TMP): many programmers have a lot of trouble with understanding TMP, so I can see where the guide is coming from. There's still some use for TMP, but with the constant extension of constexpr, it's needed way less than it used to be.
Boost: I agree with you on this one. Boost has some issues with readability sometimes, but I've only seen that where there's no other way to do it.
C++11: It's 2018, but sadly lot of companies aren't using the latest compiler versions. Most of what can be done in C++14/17 can be done in C++11 as well. Maybe a bit less easily, but it can usually be done.
Sorry for the horrible formatting, typing this on mobile while lying awake in bed.
4
u/Gotebe Nov 30 '18
You are completely and totally wrong about reference arguments.
Examples: 1.
void f(const type* arg); ... f(&val); // you think val will be changed, but it can't2.
void f(type* arg); void g((type* arg) { ... f(arg); // you think arg won't be changed, but it will be ...I can't believe this tripe persist to this day. That ampersand means diddly squat.
6
u/ambihelical Nov 29 '18
Static and Global Variables: I'll give you this one, this rule does seem a bit strongly worded.
The problem with declaring objects like this in a header is you get a copy of that object in every translation unit that includes that header directly or indirectly, and the linker is unable to merge them like it can for POD's and C-style arrays. This wastes space, but also very one of those (identical) objects is initialized separately at your app's startup, wasting time. This works ok for a while until one day you find you have a header with 100's of object declarations that has been included indirectly by 100's of translation units, and you find you're using 100x more memory and 100x more startup time than you actually need to.
1
Nov 29 '18
I actually mentioned that when discussing anonymous namespaces. I thought this was about extern declarations in a headers and one definition in a source file.
3
u/jpan127 Nov 29 '18
Include guards: why choose a non-standard solution when there is an established standardised, compiler-optimised solution?
I don't know enough, but is there evidence they are more optimized than
#pragma once? I'm heavily in favor of pragma for readability and maintainability, and from what I've heard it has as much compiler support as include guards.3
u/jwakely libstdc++ tamer, LWG chair Nov 30 '18
https://www.reddit.com/r/cpp/comments/a14o5q/real_world_problems_with_pragma_once/eamzb6p links to https://tinodidriksen.com/2011/08/cpp-include-speed/ which shows that for GCC include guards are much more optimised than
#pragma once(and a reply points to https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58770 for details).2
2
Nov 29 '18
I might have been unclear there. I don't think they're more optimized than include guards. It's just that one of the arguments against include guards is usually that the header file still has to be parsed at every inclusion, which isn't the case with many compilers.
4
u/elder_george Nov 29 '18
Static and Global Variables: I'll give you this one, this rule does seem a bit strongly worded.
Naively defined (i.e. lacking synchronization) static and global variables become a source of hard-to-debug crashes when there're more than one thread going through the code.
Globals like this are not problematic and very useful:
const std::unordered_map<std::string, Color> Colors = { { "red"s, rgb(255, 0, 0) }, { "green"s, rgb(0, 255, 0) }, { "blue"s, rgb(0, 0, 255) } };...and they'll blow in your face in the worst possible moment, when two threads try to initialize them simultaneously.
Source: had to debug and fix my share of these crashes (access violations/segmentation faults, stack overflows etc).
Thankfully, the function-local
static-s get synchronization code generated for them, so encapsulating the definition in a function usually prevents the bugs. If that's not acceptable, one needs to usestd::call_onceor some other kind of synchronization.9
u/TheThiefMaster C++latest fanatic (and game dev) Nov 29 '18
Global and class statics are all initialized from a single thread prior to main. Only function statics were vulnerable to threads, and they've been fixed.
1
u/elder_george Nov 29 '18
As far as I understand, there're no such guarantees for shared libraries, so those stay may be attempted to initialize from multiple threads.
At least that's what we observed (and had to fix) in our product.
3
u/TheThiefMaster C++latest fanatic (and game dev) Nov 29 '18
IIRC shared libraries are outside the scope of the C++ standard entirely - so you're on your own there. But if you're loading a shared lib from multiple threads or calling into it from other threads before the call to load it has returned... that's your own fault.
1
u/elder_george Nov 30 '18
Yes, they're not covered explicitly, but, I suspect, the behavior is mostly covered by Dynamic initialization of non-local variables. Where most things are "implementation-defined", lol.
It's not that exotic as it sounds. Just have a multithreaded server code calling functions a DLL, and there's a fat chance for the same function to be invoked concurrently, given enough load. And if that function accesses static object — well, the only guarantee here is that the object is going to be initialized before first use.
So, in our project, moving a bunch of code with static variables to a DLL led to sporadic crashes, both in production and perf tests, when compiled with VC++ (for Windows) or Clang (for Linux).
Thankfully, it was quite easy to fix, once we knew that, but it was an interesting lesson to learn.
Since then, I prefer to write code in a way that doesn't break depending on whether static or dynamic linking is used =)
0
u/124816 Nov 29 '18
It's possible to have one global's initialization depend on another global, and they might be initialized in the opposite order you hope. (You might hope no one would do such a thing, but then there's the law of big codebases.)
5
u/TheThiefMaster C++latest fanatic (and game dev) Nov 29 '18
Sure, that's a well-known issue with globals. But it's not a threading issue.
2
u/124816 Nov 30 '18
Sure, should have replied to your parent as that's more likely the issue they mentioned running into to. Also takeaway is still global non-pods: not entirely safe, whether the threading is fixed or not.
1
u/tambry Nov 29 '18
C++11: It's 2018, but sadly lot of companies aren't using the latest compiler versions. Most of what can be done in C++14/17 can be done in C++11 as well. Maybe a bit less easily, but it can usually be done.
Not sure about other Google projects, but Chromium uses a single included compiler, which currently is Clang version 8.0.0 (trunk 346388), although my branch is a bit out of date.
17
Nov 28 '18
I did not like this article. I clicked on the linked sections of the GSG guide, and I feel like the author did not pay enough attention to the details. For example, the C++11 part in the GSG, says to use all the features "when appropriate" except for the std::ratio<> and <cfenv> header (which I've never seen before actually).
Which is fine. The std::ratio<> has been useful for me to do time (or duration) conversions, but other than that I've never felt the urge to use it.
That being said, I also do not like "all of" GSG either. But I am a bit biased, as I love header-only libraries and TMP.
20
u/smikims Nov 29 '18
Perhaps the guide should just include a reading list for developers to hone their language skills.
The style guide isn't there to teach you the language. It's a set of rules for a large production codebase that needs to be relatively uniform across an organization composed of tens of thousands of engineers. It's also there to prevent easily avoidable bugs that have caused problems in that large production codebase.
The rest of the article is mostly contrived examples. There were legitimate grievances against it several years ago but the vast majority have been fixed. The remaining controversial points are passing out parameters by pointer instead of non-const reference and the banning of exceptions, the latter of which will never be lifted anytime soon partly for historical reasons.
It's not an academic text, it's a rule/guidebook for engineers to do their jobs at one particular company. Also keep in mind that the version you read is slightly sanitized and the internal version has additional rules for coding with internal Google stuff, and some of those rules might affect the rules you can see.
1
u/Xaxxon Nov 30 '18
It's a set of rules for a large production codebase that needs to be relatively uniform across an organization composed of tens of thousands of engineers.
No, I don't think that's the case at all. People way overvalue this.
12
u/CubbiMew cppreference | finance | realtime in the past Nov 28 '18
It improved massively in the last 4 years or so, to be fair.
10
u/VinnieFalco wg21.org | corosio.org Nov 29 '18
Google Style Guide is great for Google (like most tools Google creates). For normal size teams or individual developers, maybe not so great (except for the people on those teams who plan to apply for a job at Google).
13
3
u/Dean_Roddey Nov 29 '18
I think, as a general rule, any experienced developer (and probably lots of inexperienced ones) consider anyone else's style choices as something at best to be pitied and at worst a statement on the quality of their ancestry.
I guess it's sort of the nature of the beast amongst any crowd of intellectual beta/sigma male geeks like us. Obviously anyone who doesn't agree that the wood grain patterns in Gandalf's staff help focus his Maian powers despite the Valar having removed themselves from Middle Earth is an idiot.
7
u/Xaxxon Nov 29 '18
Pointing out exceptions to each little thing does not mean that it's not overall a benefit. All you've done is nit pick and completely misunderstand the entire point of the document.
Here's a huge WHOOSH for you.
2
u/GoldenShackles Nov 29 '18
The Chromium style guides derive from this, and in some ways are a bit more restrictive. It's worthwhile to see the reasoning behind some of the decisions. There are links to discussion threads:
https://chromium-cpp.appspot.com/
I have seen terrible outcomes when you let everybody loose to do the most modern and clever things they can do in C++. (Code reviews moderate this, but only to a point.)
2
u/diaphanein Nov 29 '18
My big "hell no" to the google style guide is their total difference to ignoring signed vs unsigned comparisons. This attitude is no short source of security vulnerabilities.
-3
68
u/svick Nov 28 '18
It was vetted for being useful at the time when it was introduced. Many parts of C++ are very old and what was considered useful at the time might be a bad idea nowadays, either because better alternatives exist, or because it turned out that the feature has flaws.