For Developers‎ > ‎Coding Style‎ > ‎

C++ Dos and Don'ts

A Note About Usage

Unlike the style guide, the content of this page is advisory, not required. You can always deviate from something on this page, if the relevant author/reviewer/OWNERS agree that another course is better.

Minimize Code in Headers

Don't include unneeded headers

If a file isn't using the symbols from some header, remove the header.  It turns out that this happens frequently in the Chromium codebase due to refactoring.

Move inner classes into the implementation

You can also forward declare classes inside a class:

class Whatever {
  /* ... */
  struct DataStruct;
  std::vector<DataStruct> data_;

Any headers that DataStruct needed no longer need to be included in the header file and only need to be included in the implementation. This will often let you pull includes out of the header. For reference, the syntax in the implementation file is:

struct Whatever::DataStruct {

Note that sometimes you can't do this because certain STL data structures require the full definition at declaration time (most notably, std::deque and the STL adapters that wrap it).

Move static implementation details to the implementation whenever possible

If you have the class in a header file:

#include "BigImplementationDetail.h"
class PublicInterface {
   /* ... */
   static BigImplementationDetail detail_;

You should try to move that from a class member into the anonymous namespace in the implementation file:

namespace {
BigImplementationDetail g_detail;
}  // namespace

That way, people who don't use your interface don't need to know about or care about BigImplementationDetail.

You can do this for helper functions, too.  Note that if there is more than one class in the .cc file, it can aid clarity to define your file-scope helpers in an anonymous namespace just above the class that uses them, instead of at the top of the file.

Stop inlining code in headers

BACKGROUND: Unless something is a cheap accessor or you truly need it to be inlined, don't ask for it to be inlined.  Remember that definitions inside class declarations are implicitly requested to be inlined.

class InlinedMethods {
  InlinedMethods() {
    // This constructor is equivalent to having the inline keyword in front
    // of it!
  void Method() {
    // Same here!

Stop inlining complex methods.

class DontDoThis {
  int ComputeSomething() {
    int sum =0;
    for (int i = 0; i < limit; ++i) {
      sum += OtherMethod(i, ... );
    return sum;

A request to inline is merely a suggestion to the compiler, and anything more than a few operations on integral data types will probably not be inlined.  However, every file that has to use an inline method will also emit a function version in the resulting .o, even if the method was inlined. (This is to support function pointer behavior properly.)  Therefore, by requesting an inline in this case, you're likely just adding crud to the .o files which the linker will need to do work to resolve.

If the method has significant implementation, there's also a good chance that by not inlining it, you could eliminate some includes.

Stop inlining virtual methods

You can't inline virtual methods under most circumstances, even if the method would otherwise be inlined because it's very short. The compiler must do runtime dispatch on any virtual method where the compiler doesn't know the object's complete type, which rules out the majority of cases where you have an object.

Stop inlining constructors and destructors

Constructors and destructors are often significantly more complex than you think they are, especially if your class has any non-POD data members. Many STL classes have inlined constructors/destructors which may be copied into your function body. Because the bodies of these appear to be empty, they often seem like trivial functions that can safely be inlined.  Don't give in to this temptation.  Define them in the implementation file unless you really need them to be inlined.  Even if they do nothing now, someone could later add something seemingly-trivial to the class and make your hundreds of inlined destructors much more complex.

Even worse, inlining constructors/destructors prevents you from using forward declared variables:

class Forward;
class WontCompile {
   // The compiler needs the definition of Forward to call the
   // vector/scoped_ptr ctors/dtors.
   Example() { }
   ~Example() { }

  std::vector<Forward> examples_;
  scoped_ptr<Forward> super_example_;

For more information, read Item 30 in Effective C++.

When you CAN inline constructors and destructors

C++ has the concept of a trivial destructor. If your class has only POD types and does not explicitly declare a destructor, then the compiler will not bother to generate or run a destructor.

struct Data {
  Data() : count_one(0), count_two(0) {}
  // No explicit destructor, thus no implicit destructor either.

  // The members must all be POD for this trick to work.
  int count_one;
  int count_two;

In this example, since there is no inheritance and only a few POD members, the constructor will be only a few trivial integer operations, and thus OK to inline.

For abstract base classes with no members, it's safe to define the (trivial) destructor inline:

class Interface {
  virtual ~Interface() {}
  virtual void DoSomething(int parameter) = 0;
  virtual int GetAValue() = 0; 

But be careful; these two "interfaces" don't count:

class ClaimsToBeAnInterface : public base:RefCounted<ClaimsToBeAnInterface> {
  virtual ~ClaimsToBeAnInterface() { /* But derives from a template! */ }

class HasARealMember {
  virtual void InterfaceMethod() = 0;
  virtual ~HasARealMember() {}

  vector<string> some_data_;

If in doubt, don't rely on these sorts of exceptions.  Err on the side of not inlining.

Be careful about your accessors

Not all accessors are light weight. Compare:

class Foo {
  int count() const { return count_; }

  int count_;

Here the accessor is trivial and safe to inline.  But the following code is probably not, even though it also looks simple:

struct MyData {
  vector<GURL> urls_;
  base::Time last_access_;

class Manager {
  MyData get_data() { return my_data_; }

  MyData my_data_;

The underlying copy constructor calls for MyData are going to be complex. (Also, they're going to be synthesized, which is bad.)

What about code outside of headers?

For classes declared in .cc files, there's no risk of bloating several .o files with the definitions of the same "inlined" function.  While there are other, weaker arguments to continue to avoid inlining, the primary remaining consideration is simply what would make code most readable.

This is especially true in testing code.  Test framework classes don't tend to be instantiated separately and passed around as objects; they're effectively just bundles of file-scope functionality coupled with a mechanism to reset state between tests.  In these cases, defining the test functions inline at their declaration sites has little negative effect and can reduce the amount of "boilerplate" in the test file.

Different reviewers may have different opinions here; use good judgment.

Static variables

Dynamic initialization of function-scope static variables is now threadsafe in Chromium (per standard C++11 behavior). Before 2017, this was thread-unsafe, and base::LazyInstance was widely used. This is no longer necessary. Background can be found in this thread and this thread.

void foo() {
    static int OK_COUNT = ComputeTheCount();  // OK now, previously a problem.
    static int GOOD_COUNT = 42;  // C++03 3.6.2 says this is done before dynamic initialization, so probably thread-safe.
    static constexpr int BETTER_COUNT = 42;  // Even better, as this will now likely be inlined at compile time.

The majority of Chrome code is intended to be single-threaded, where this presents no problem.  When in multi-threaded code, however, the right answer is usually to use a base::LazyInstance.

Variable initialization

There are myriad ways to initialize variables in C++11.  Prefer the following general rules:

  1. Use assignment syntax when performing "simple" initialization with one or more literal values which will simply be composed into the object:

    int i = 1;
    std::string s = "Hello";
    std::pair<bool, double> p = {true, 2.0};
    std::vector<std::string> v = {"one", "two", "three"};

    Using '=' here is no less efficient than "()" (the compiler won't generate a temp + copy), and ensures that only implicit constructors are called, so readers seeing this syntax can assume nothing complex or subtle is happening.  Note that "{}" are allowed on the right side of the '=' here (e.g. when you're merely passing a set of initial values to a "simple" struct/container constructor; see below items for contrast).

  2. Use constructor syntax when construction performs significant logic, uses an explicit constructor, or in some other way is not intuitively "simple" to the reader:

    MyClass c(1.7, false, "test");
    std::vector<double> v(500, 0.97);  // Creates 500 copies of the provided initializer

  3. Use C++11 "uniform init" syntax ("{}" without '=') only when neither of the above work:

    class C {
      explicit C(bool b) { ... };
    class UsesC {
      C c{true};  // Cannot use '=' since C() is explicit (and "()" is invalid syntax here)

    class Vexing {
      explicit Vexing(const std::string& s) { ... };
    void func() {
      Vexing v{std::string()};  // Using "()" here triggers "most vexing parse";
                                // "{}" is arguably more readable than "(())"

  4. Never mix uniform init syntax with auto, since what it deduces is unlikely to be what was intended:

    auto x{1};  // Until C++17, decltype(x) is std::initializer_list<int>, not int!

Prefer MakeUnique to WrapUnique

base::MakeUnique<Type>( ... ) and base::WrapUnique(new Type( ... )) are equivalent. MakeUnique should be preferred, because it is harder to use unsafely than WrapUnique. In general, bare calls to "new" require careful scrutiny. Bare calls to "new" are currently required to construct reference-counted types; however, reference counted types themselves require careful scrutiny.

    return std::unique_ptr<C>(new C(1, 2, 3));  // BAD: type name mentioned twice
    return base::WrapUnique(new C(1, 2, 3));    // BAD: bare call to new
    return base::MakeUnique<C>(1, 2, 3);        // GOOD

  1. Never friend MakeUnique to work around constructor access restrictions. It will allow anyone to construct the class. Use WrapUnique in this case.

    class Bad {
      std::unique_ptr<Bad> Create() { return base::MakeUnique<Bad>(); }
      // ...

      // ...
      friend std::unique_ptr<Bad> base::MakeUnique<Bad>();  // Lost access control

    class Okay {
      // For explanatory purposes. If Create() adds no value, it is better just
      // to have a public constructor instead.
      std::unique_ptr<Okay> Create() { return base::WrapUnique(new Okay()); }
      // ...

      // ...

  2. WrapUnique(new Foo) and WrapUnique(new Foo()) mean something different if Foo does not have a user-defined constructor. Don't make future maintainers guess whether you left off the '()' on purpose. Use MakeUnique<Foo>() instead. If you're intentionally leaving off the "()" as an optimisation, please leave a comment.

        auto a = base::WrapUnique(new A); // BAD: "()" omitted intentionally?
        auto a = base::MakeUnique<A>();   // GOOD

        // "()" intentionally omitted to avoid unnecessary zero-initialisation.
        // WrapUnique() does the wrong thing for array pointers.
        auto array = std::unique_ptr<A[]>(new A[size]);

Do not use auto to deduce a raw pointer

The use of the auto keyword to deduce the type from the initializing expression is encouraged when it improves readability. However, do not use auto when the type would be deduced to be a pointer type. This can cause confusion. Instead, prefer specifying the "pointer" part outside of auto:

    auto item = new Item();  // BAD: auto deduces to Item*, type of |item| is Item*
    auto* item = new Item(); // GOOD: auto deduces to Item, type of |item| is Item*