Jul 23, 2014

[C++] The Chromium Projects's C++ Dos and Don'ts

C++ Dos and Don'ts
Reddit discussion

Q:
what's the deal with inlining? Doesn't the compiler decide anyways what gets inlined and what doesn't?
A:

  • It does, but as the article says, even if it decides to inline, the compiler still has to emit an out-of-line function body into every .o file that that included the header, because it can never be sure that there isn't some code elsewhere that might need to take the address of that function. These duplicate function bodies are put in their own sections marked with the "linkonce" attribute, which means that the linker knows that they're all identical and it can just pick one, but it's still extra work to be done at link time.
  • And on big projects, it improves programmer productivity if you can shave a minute or two off the compile time by making the linker (and preprocessor, with headers) do less work.



  • Forward declare classes instead of including headers.
  • Move inner classes into the implementation.
  • Move static implementation details to the implementation whenever possible.
  • Stop inlining code in headers
  • Stop inlining virtual methods.
  • Stop inlining constructors and destructors. (That is this prevents class forwarding, since compiler will init data member that consumes the forwarding class inside the constructors and destructors, which prevents class forwarding.)
  • When you CAN inline constructors and destructors.
    • just think that any class type that is not POD(since no virtual table etc, compiler will not inject extra code into constructors and destructors.)
  • Be careful about your accessors. (those function has local variable that is not light weighted should not consider inline)
  • Static variables : Dynamic initialization of function-scope static variables is thread-unsafe use base::LazyInstance in Chromium

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.