Instead of overloading methods, it is preferable to write methods with unique identifiers.
BackgroundC++ is one of the main development languages used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain. Show
The goal of this guide is to manage this complexity by describing in detail the dos and don'ts of writing C++ code . These rules exist to keep the code base manageable while still allowing coders to use C++ language features productively. Style, also known as readability, is what we call the conventions that govern our C++ code. The term Style is a bit of a misnomer, since these conventions cover far more than just source file formatting. Most open-source projects developed by Google conform to the requirements in this guide. Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language. Goals of the Style GuideWhy do we have this document? There are a few core goals that we believe this guide should serve. These are the fundamental whys that underlie all of the individual rules. By bringing these ideas to the fore, we hope to ground discussions and make it clearer to our broader community why the rules are in place and why particular decisions have been made. If you understand what goals each rule is serving, it should be clearer to everyone when a rule may be waived (some can be), and what sort of argument or alternative would be necessary to change a rule in the guide. The goals of the style guide as we currently see them are as follows: Style rules should pull their weightThe benefit of a style rule must be large enough to justify asking all of our engineers to remember it. The benefit is measured relative to the codebase we would get without the rule, so a rule against a very harmful practice may still have a small benefit if people are unlikely to do it anyway. This principle mostly explains the rules we don’t have, rather than the rules we do: for example,goto contravenes many of the following principles, but is already vanishingly rare, so the Style Guide doesn’t discuss it.Optimize for the reader, not the writerOur codebase (and most individual components submitted to it) is expected to continue for quite some time. As a result, more time will be
spent reading most of our code than writing it. We explicitly choose to optimize for the experience of our average software engineer reading, maintaining, and debugging code in our codebase rather than ease when writing said code. "Leave a trace for the reader" is a particularly common sub-point of this principle: When something surprising or unusual is happening in a snippet of code (for example, transfer of pointer ownership), leaving textual hints for the reader at the point of use is
valuable (std::unique_ptr demonstrates the ownership transfer unambiguously at the call site). Be consistent with existing codeUsing one style consistently through our codebase lets us focus on other (more important) issues. Consistency also allows for automation: tools that format your code or adjust your #include s only work properly when your code is consistent with the expectations of the tooling. In many cases, rules that are attributed to "Be Consistent" boil down to "Just pick
one and stop worrying about it"; the potential value of allowing flexibility on these points is outweighed by the cost of having people argue over them. However, there are limits to consistency; it is a good tie breaker when there is no clear technical argument, nor a long-term direction. It applies more heavily locally (per file, or for a tightly-related set of interfaces). Consistency should not generally be used as a justification to do things in an old style without considering the benefits
of the new style, or the tendency of the codebase to converge on newer styles over time.Be consistent with the broader C++ community when appropriateConsistency with the way other organizations use C++ has value for the same reasons as consistency within our code base. If a feature in the C++ standard solves a problem, or if some idiom is widely known and accepted, that's an argument for using it. However, sometimes standard features and idioms are flawed, or were just designed
without our codebase's needs in mind. In those cases (as described below) it's appropriate to constrain or ban standard features. In some cases we prefer a homegrown or third-party library over a library defined in the C++ Standard, either out of perceived superiority or insufficient value to transition the codebase to the standard interface.Avoid surprising or dangerous constructsC++ has features that are more surprising or dangerous than one might think at a glance. Some
style guide restrictions are in place to prevent falling into these pitfalls. There is a high bar for style guide waivers on such restrictions, because waiving such rules often directly risks compromising program correctness. Avoid constructs that our average C++ programmer would find tricky or hard to maintainC++ has features that may not be generally appropriate because of the complexity they introduce to the code. In widely used code, it may be more acceptable to use
trickier language constructs, because any benefits of more complex implementation are multiplied widely by usage, and the cost in understanding the complexity does not need to be paid again when working with new portions of the codebase. When in doubt, waivers to rules of this type can be sought by asking your project leads. This is specifically important for our codebase because code ownership and team membership changes over time: even if everyone that works with some piece of code currently
understands it, such understanding is not guaranteed to hold a few years from now.Be mindful of our scaleWith a codebase of 100+ million lines and thousands of engineers, some mistakes and simplifications for one engineer can become costly for many. For instance it's particularly important to avoid polluting the global namespace: name collisions across a codebase of hundreds of millions of lines are difficult to work with and hard to avoid if everyone puts things into the
global namespace.Concede to optimization when necessaryPerformance optimizations can sometimes be necessary and appropriate, even when they conflict with the other principles of this document.The intent of this document is to provide maximal guidance with reasonable restriction. As always, common sense and good taste should prevail. By this we specifically refer to the established conventions of the entire Google C++ community, not just your personal preferences or those of your team. Be skeptical about and reluctant to use clever or unusual constructs: the absence of a prohibition is not the same as a license to proceed. Use your judgment, and if you are unsure, please don't hesitate to ask your project leads to get additional input. C++ VersionCurrently, code should target C++17, i.e., should not use C++2x features, with the exception of designated initializers. The C++ version targeted by this guide will advance (aggressively) over time. Do not use non-standard extensions. Consider portability to other environments before using features from C++14 and C++17 in your project. In general, every Correct use of header files can make a huge difference to the readability, size and performance of your code. The following rules will guide you through the various pitfalls of using header files. Header files should be self-contained (compile on their own) and end in All header files should be self-contained. Users and refactoring tools should not have to adhere to special conditions to include the header. Specifically, a header should have header guards and include all other headers it needs. When a header declares inline functions or templates that clients of the header will instantiate, the inline
functions and templates must also have definitions in the header, either directly or in files it includes. Do not move these definitions to separately included header ( There are rare cases where a file designed to be included is not self-contained. These are typically intended to be included at unusual locations, such as the middle of another file. They might not use header guards, and might not include their prerequisites. Name such files with the The #define GuardAll header files should have To guarantee uniqueness, they should be based on the full path in a project's source tree. For example, the file #ifndef FOO_BAR_BAZ_H_ #define FOO_BAR_BAZ_H_ ... #endif // FOO_BAR_BAZ_H_ Include What You UseIf a source or header file refers to a symbol defined elsewhere, the file should directly include a header file which properly intends to provide a declaration or definition of that symbol. It should not include header files for any other reason. Do not rely on transitive inclusions. This allows people to remove no-longer-needed Forward DeclarationsAvoid using forward declarations where possible. Instead, include the headers you need. A "forward declaration" is a declaration of an entity without an associated definition. // In a C++ source file: class B; void FuncInB(); extern int variable_in_b; ABSL_DECLARE_FLAG(flag_in_b);
Try to avoid forward declarations of entities defined in another project. Inline FunctionsDefine functions inline only when they are small, say, 10 lines or fewer. You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism. Inlining a function can generate more efficient object code, as long as the inlined function is small. Feel free to inline accessors and mutators, and other short, performance-critical functions. Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. A decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of destructors, which are often longer than they appear because of implicit member- and base-destructor calls! Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed). It is important to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the class, either for convenience or to document its behavior, e.g., for accessors and mutators. Names and Order of IncludesInclude headers in the following order: Related header, C system headers, C++ standard library headers, other libraries' headers, your project's headers. All of a
project's header files should be listed as descendants of the project's source directory without use of UNIX directory aliases #include "base/logging.h" In
Separate each non-empty group with one blank line. With the preferred ordering, if the related header
Note that the C headers such as Within each section the includes should be ordered alphabetically. Note that older code might not conform to this rule and should be fixed when convenient. For example, the includes in #include "foo/server/fooserver.h" #include Exception: Sometimes, system-specific code needs conditional includes. Such code can put conditional includes after other includes. Of course, keep your system-specific code small and localized. Example: #include "foo/public/fooserver.h" #include "base/port.h" // For LANG_CXX11. #ifdef LANG_CXX11 #include ScopingNamespacesWith few exceptions, place code in a namespace. Namespaces should have unique names based on the project name, and possibly its path. Do not use using-directives (e.g., Namespaces subdivide the global scope into distinct, named scopes, and so are useful for preventing name collisions in the global scope. Namespaces provide a method for preventing name conflicts in large programs while allowing most code to use reasonably short names. For example, if two different projects have a class Inline namespaces automatically place their names in the enclosing scope. Consider the following snippet, for example: namespace outer { inline namespace inner { void foo(); } // namespace inner } // namespace outer The expressions Namespaces can be confusing, because they complicate the mechanics of figuring out what definition a name refers to. Inline namespaces, in particular, can be confusing because names aren't actually restricted to the namespace where they are declared. They are only useful as part of some larger versioning policy. In some contexts, it's necessary to repeatedly refer to symbols by their fully-qualified names. For deeply-nested namespaces, this can add a lot of clutter. Namespaces should be used as follows:
Internal LinkageWhen definitions in a All declarations can be given internal linkage by placing them in unnamed namespaces. Functions and variables can also be given internal linkage by declaring them Use of internal linkage in Format unnamed namespaces like named namespaces. In the terminating comment, leave the namespace name empty: namespace { ... } // namespace Nonmember, Static Member, and Global FunctionsPrefer placing nonmember functions in a namespace; use completely global functions rarely. Do not use a class simply to group static members. Static methods of a class should generally be closely related to instances of the class or the class's static data. Nonmember and static member functions can be useful in some situations. Putting nonmember functions in a namespace avoids polluting the global namespace. Nonmember and static member functions may make more sense as members of a new class, especially if they access external resources or have significant dependencies. Sometimes it is useful to define a function not bound to a class instance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on external variables, and should nearly always exist in a namespace. Do not create classes only to group static members; this is no different than just giving the names a common prefix, and such grouping is usually unnecessary anyway. If you define a
nonmember function and it is only needed in its Local VariablesPlace a function's variables in the narrowest scope possible, and initialize variables in the declaration. C++ allows you to declare variables anywhere in a function. We encourage you to declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initialized to. In particular, initialization should be used instead of declaration and assignment, e.g.,: int i; i = f(); // Bad -- initialization separate from declaration. int j = g(); // Good -- declaration has initialization. std::vector std::vector Variables needed for while (const char* p = strchr(str, '/')) str = p + 1; There is one caveat: if the variable is an object, its constructor is invoked every time it enters scope and is created, and its destructor is invoked every time it goes out of scope. // Inefficient implementation: for (int i = 0; i < 1000000; ++i) { Foo f; // My ctor and dtor get called 1000000 times each. f.DoSomething(i); } It may be more efficient to declare such a variable used in a loop outside that loop: Foo f; // My ctor and dtor get called once each. for (int i = 0; i < 1000000; ++i) { f.DoSomething(i); } Static and Global VariablesObjects with static storage duration are forbidden unless they are trivially destructible. Informally this means that the destructor does not do anything, even taking member and base destructors into account. More formally it means that the type has no user-defined or virtual destructor and that all bases and non-static members are trivially destructible. Static function-local variables may use dynamic initialization. Use of dynamic initialization for static class member variables or variables at namespace scope is discouraged, but allowed in limited circumstances; see below for details. As a rule of thumb: a global variable satisfies these requirements if its declaration, considered in isolation, could be Every object has a storage duration, which correlates with its lifetime. Objects with static storage duration live from the point of their initialization until the end of the program. Such objects appear as
variables at namespace scope ("global variables"), as static data members of classes, or as function-local variables that are declared with the Initialization may be dynamic, which means that something non-trivial happens during initialization. (For example, consider a constructor that allocates memory, or a variable that is initialized with the current process ID.) The other kind of initialization is static initialization. The two aren't quite opposites, though: static initialization always happens to objects with static storage duration (initializing the object either to a given constant or to a representation consisting of all bytes set to zero), whereas dynamic initialization happens after that, if required. Global and static variables are very useful for a large number of applications: named constants, auxiliary data structures internal to some translation unit, command-line flags, logging, registration mechanisms, background infrastructure, etc. Global and static variables that use dynamic initialization or have non-trivial destructors create complexity that can easily lead to hard-to-find bugs. Dynamic initialization is not ordered across translation units, and neither is destruction (except that destruction happens in reverse order of initialization). When one initialization refers to another variable with static storage duration, it is possible that this causes an object to be accessed before its lifetime has begun (or after its lifetime has ended). Moreover, when a program starts threads that are not joined at exit, those threads may attempt to access objects after their lifetime has ended if their destructor has already run. Decision on destructionWhen destructors are trivial, their execution is not subject to ordering at all (they are effectively not "run"); otherwise we are exposed to the risk of accessing objects after the end of their lifetime. Therefore, we only allow objects with static storage duration if they are trivially destructible. Fundamental types (like pointers and const int kNum = 10; // Allowed struct X { int n; }; const X kX[] = {{1}, {2}, {3}}; // Allowed void foo() { static const char* const kMessages[] = {"hello", "world"}; // Allowed } // Allowed: constexpr guarantees trivial destructor. constexpr std::array // bad: non-trivial destructor const std::string kFoo = "foo"; // Bad for the same reason, even though kBar is a reference (the // rule also applies to lifetime-extended temporary objects). const std::string& kBar = StrCat("a", "b", "c"); void bar() { // Bad: non-trivial destructor. static std::map Note that references are not objects, and thus they are not subject to the constraints on destructibility. The constraint on dynamic initialization still applies, though. In particular, a function-local static reference of the form Decision on initializationInitialization is a more complex topic. This is because we must not only consider whether class constructors execute, but we must also consider the evaluation of the initializer: int n = 5; // Fine int m = f(); // ? (Depends on f) Foo x; // ? (Depends on Foo::Foo) Bar y = g(); // ? (Depends on g and on Bar::Bar) All but the first statement expose us to indeterminate initialization ordering. The concept we are looking for is called constant initialization in the formal language of the C++ standard. It means that the initializing expression is a constant expression, and if the object is initialized by a constructor call, then the constructor must be specified as struct Foo { constexpr Foo(int) {} }; int n = 5; // Fine, 5 is a constant expression. Foo x(2); // Fine, 2 is a constant expression and the chosen constructor is constexpr. Foo a[] = { Foo(1), Foo(2), Foo(3) }; // Fine Constant initialization is always allowed. Constant initialization of static storage duration variables should be marked with By contrast, the following initializations are problematic: // Some declarations used below. time_t time(time_t*); // Not constexpr! int f(); // Not constexpr! struct Bar { Bar() {} }; // Problematic initializations. time_t m = time(nullptr); // Initializing expression not a constant expression. Foo y(f()); // Ditto Bar b; // Chosen constructor Bar::Bar() not constexpr. Dynamic initialization of nonlocal variables is discouraged, and in general it is forbidden. However, we do permit it if no aspect of the program depends on the sequencing of this initialization with respect to all other initializations. Under those restrictions, the ordering of the initialization does not make an observable difference. For example: int p = getpid(); // Allowed, as long as no other static variable // uses p in its own initialization. Dynamic initialization of static local variables is allowed (and common). Common patterns
thread_local Variables
Variables can be declared with
the thread_local Foo foo = ...; Such a variable is actually a collection of objects, so that when different threads access it, they are actually accessing different objects.
Foo& MyThreadLocalFoo() { thread_local Foo result = ComplicatedInitialization(); return result; }
ABSL_CONST_INIT thread_local Foo foo = ...;
ClassesClasses are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a class. Doing Work in ConstructorsAvoid virtual method calls in constructors, and avoid initialization that can fail if you can't signal an error. It is possible to perform arbitrary initialization in the body of the constructor.
Constructors should never call virtual functions. If appropriate for your code , terminating the program may be an appropriate error handling response. Otherwise, consider a factory function or Implicit ConversionsDo not define implicit conversions. Use the Implicit conversions allow an object of one type (called
the source type) to be used where a different type (called the destination type) is expected, such as when passing an In addition to the implicit conversions defined by the language, users can define their own, by adding appropriate members to the class definition of the source or destination type. An implicit conversion in the source type is defined by a type conversion operator named after the
destination type (e.g., The class Foo { explicit Foo(int x, double y); ... }; void Func(Foo f); Func({42, 3.14}); // Error This kind of code isn't technically an implicit conversion, but the language treats it as one as far as
Type conversion operators, and constructors that are callable with a single argument, must be marked Implicit conversions can sometimes be necessary and appropriate for types that are designed to be interchangeable, for example when objects of two types are just different representations of the same underlying value. In that case, contact your project leads to request a waiver of this rule. Constructors that cannot be called with a single argument may omit Copyable and Movable TypesA class's public API must make clear whether the class is copyable, move-only, or neither copyable nor movable. Support copying and/or moving if these operations are clear and meaningful for your type. A movable type is one that can be initialized and assigned from temporaries. A copyable type is one that can be initialized or assigned from any other object of the same type (so is
also movable by definition), with the stipulation that the value of the source does not change. For user-defined types, the copy behavior is defined by the copy constructor and the copy-assignment operator. Move behavior is defined by the move constructor and the move-assignment operator, if they exist, or by the copy constructor and the copy-assignment operator otherwise. The copy/move constructors can be implicitly invoked by the compiler in some situations, e.g., when passing objects by value. Objects of copyable and movable types can be passed and returned by value, which makes APIs simpler, safer, and more general. Unlike when passing objects by pointer or reference, there's no risk of confusion over ownership, lifetime, mutability, and similar issues, and no need to specify them in the contract. It also prevents non-local interactions between the client and the implementation, which makes them easier to understand, maintain, and optimize by the compiler. Further, such objects can be used with generic APIs that require pass-by-value, such as most containers, and they allow for additional flexibility in e.g., type composition. Copy/move constructors and assignment operators are usually easier to define correctly than alternatives like Move operations allow the implicit and efficient transfer of resources out of rvalue objects. This allows a plainer coding style in some cases. Some types do not need to be copyable, and providing copy operations for such types can be confusing, nonsensical, or outright incorrect. Types representing singleton objects ( Copy constructors are invoked implicitly, which makes the invocation easy to miss. This may cause confusion for programmers used to languages where pass-by-reference is conventional or mandatory. It may also encourage excessive copying, which can cause performance problems. Every class's public interface must make clear which copy and move operations the class supports. This should usually take the form of explicitly declaring and/or deleting the appropriate operations in the Specifically, a copyable class should explicitly declare the copy operations, a move-only class should explicitly declare the move operations, and a non-copyable/movable class should explicitly delete the copy operations. A copyable class may also declare move operations in order to support efficient moves. Explicitly declaring or deleting all four copy/move operations is permitted, but not required. If you provide a copy or move assignment operator, you must also provide the corresponding constructor. class Copyable { public: Copyable(const Copyable& other) = default; Copyable& operator=(const Copyable& other) = default; // The implicit move operations are suppressed by the declarations above. // You may explicitly declare move operations to support efficient moves. }; class MoveOnly { public: MoveOnly(MoveOnly&& other) = default; MoveOnly& operator=(MoveOnly&& other) = default; // The copy operations are implicitly deleted, but you can // spell that out explicitly if you want: MoveOnly(const MoveOnly&) = delete; MoveOnly& operator=(const MoveOnly&) = delete; }; class NotCopyableOrMovable { public: // Not copyable or movable NotCopyableOrMovable(const NotCopyableOrMovable&) = delete; NotCopyableOrMovable& operator=(const NotCopyableOrMovable&) = delete; // The move operations are implicitly disabled, but you can // spell that out explicitly if you want: NotCopyableOrMovable(NotCopyableOrMovable&&) = delete; NotCopyableOrMovable& operator=(NotCopyableOrMovable&&) = delete; }; These declarations/deletions can be omitted only if they are obvious:
A type should not be copyable/movable if the meaning of copying/moving is unclear to a casual user, or if it incurs unexpected costs. Move operations for copyable types are strictly a performance optimization and are a potential source of bugs and complexity, so avoid defining them unless they are significantly more efficient than the corresponding copy operations. If your type provides copy operations, it is recommended that you design your class so that the default implementation of those operations is correct. Remember to review the correctness of any defaulted operations as you would any other code. To eliminate the risk of slicing, prefer to make base classes abstract, by making their constructors protected, by declaring their destructors protected, or by giving them one or more pure virtual member functions. Prefer to avoid deriving from concrete classes. Structs vs. ClassesUse a The
If more
functionality or invariants are required, a For consistency with STL, you can use Note that member variables in structs and classes have different naming rules. Structs vs. Pairs and TuplesPrefer to use a While using pairs and tuples can avoid the need to define a custom type, potentially saving work when writing code, a meaningful field name will almost always be much clearer when
reading code than Pairs and tuples may be appropriate in generic code where there are not specific meanings for the elements of the pair or tuple. Their use may also be required in order to interoperate with existing code or APIs. InheritanceComposition is often more appropriate than inheritance. When using inheritance, make it When a sub-class inherits from a base class, it includes the definitions of all the data and operations that the base class defines. "Interface inheritance" is inheritance from a pure abstract base class (one with no state or defined methods); all other inheritance is "implementation inheritance". Implementation inheritance reduces code size by re-using the base class code as it specializes an existing type. Because inheritance is a compile-time declaration, you and the compiler can understand the operation and detect errors. Interface inheritance can be used to programmatically enforce that a class expose a particular API. Again, the compiler can detect errors, in this case, when a class does not define a necessary method of the API. For implementation inheritance, because the code implementing a sub-class is spread between the base and the sub-class, it can be more difficult to understand an implementation. The sub-class cannot override functions that are not virtual, so the sub-class cannot change implementation. Multiple inheritance is especially problematic, because it often imposes a higher performance overhead (in fact, the performance drop from single inheritance to multiple inheritance can often be greater than the performance drop from ordinary to virtual dispatch), and because it risks leading to "diamond" inheritance patterns, which are prone to ambiguity, confusion, and outright bugs. All inheritance should be Do not overuse implementation inheritance. Composition is often more appropriate. Try to restrict use of inheritance to the
"is-a" case: Limit the use of Explicitly annotate overrides of virtual functions or virtual destructors with exactly one of an Multiple inheritance is permitted, but multiple implementation inheritance is strongly discouraged. Operator OverloadingOverload operators judiciously. Do not use user-defined literals. C++ permits user code to declare overloaded versions of the built-in operators using the Operator overloading can make code more concise and intuitive by enabling user-defined types to behave the same as built-in types. Overloaded operators are the idiomatic names for certain operations (e.g., User-defined literals are a very concise notation for creating objects of user-defined types.
Define overloaded operators only if their meaning is obvious, unsurprising, and consistent with the corresponding built-in operators. For example, use Define operators only on your own types. More precisely, define them in the same headers, .cc files, and namespaces as the types they operate on. That way, the operators are available wherever the type is, minimizing the risk of multiple definitions. If possible, avoid
defining operators as templates, because they must satisfy this rule for any possible template arguments. If you define an operator, also define any related operators that make sense, and make sure they are defined consistently. For example, if you overload Prefer to define non-modifying binary operators as non-member functions. If a binary operator is defined as a
class member, implicit conversions will apply to the right-hand argument, but not the left-hand one. It will confuse your users if Don't go out of your way to avoid defining operator overloads. For example, prefer to define Do not overload Type conversion operators are covered in the section on implicit
conversions. The Access ControlMake classes' data members For technical reasons, we allow data members of a test fixture class defined in a .cc file to be
Declaration OrderGroup similar declarations together, placing public parts earlier. A class definition should usually start with a Within each section, prefer grouping similar kinds of declarations together, and prefer the following order:
Do not put large method definitions inline in the class definition. Usually, only trivial or performance-critical, and very short, methods may be defined inline. See Inline Functions for more details. FunctionsInputs and OutputsThe output of a C++ function is naturally provided via a return value and sometimes via output parameters (or in/out parameters). Prefer using return values over output parameters: they improve readability, and often provide the same or better performance. Prefer to return by value or, failing that, return by reference. Avoid returning a pointer unless it can be null. Parameters are either inputs to the function, outputs from the function, or both. Non-optional input parameters should usually be values or Avoid defining functions that require a When ordering function parameters, put all input-only parameters before any output parameters. In particular, do not add new parameters to the end of the function just because they are new; place new input-only parameters before the output parameters. This is not a hard-and-fast rule. Parameters that are both input and output muddy the waters, and, as always, consistency with related functions may require you to bend the rule. Variadic functions may also require unusual parameter ordering. Write Short FunctionsPrefer small and focused functions. We recognize that long functions are sometimes appropriate, so no hard limit is placed on functions length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program. Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code. Small functions are also easier to test. You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code: if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces. Function OverloadingUse overloaded functions (including constructors) only if a reader looking at a call site can get a good idea of what is happening without having to first figure out exactly which overload is being called. You may write a function that takes a class MyClass { public: void Analyze(const std::string &text); void Analyze(const char *text, size_t textlen); }; Overloading can make code more intuitive by allowing an identically-named function to take different arguments. It may be necessary for templatized code, and it can be convenient for Visitors. Overloading based on const or ref qualification may make utility code more usable, more efficient, or both. (See TotW 148 for more.) If a function is overloaded by the argument types alone, a reader may have to understand C++'s complex matching rules in order to tell what's going on. Also many people are confused by the semantics of inheritance if a derived class overrides only some of the variants of a function. You may overload a function when there are no semantic differences between variants. These overloads may vary in types, qualifiers, or argument count. However, a reader of such a call must not need to know which member of the overload set is chosen, only that something from the set is being called. If you can document all entries in the overload set with a single comment in the header, that is a good sign that it is a well-designed overload set. Default ArgumentsDefault arguments are allowed on non-virtual functions when the default is guaranteed to always have the same value. Follow the same restrictions as for function overloading, and prefer overloaded functions if the readability gained with default arguments doesn't outweigh the downsides below. Often you have a function that uses default values, but occasionally you want to override the defaults. Default parameters allow an easy way to do this without having to define many functions for the rare exceptions. Compared to overloading the function, default arguments have a cleaner syntax, with less boilerplate and a clearer distinction between 'required' and 'optional' arguments. Defaulted arguments are another way to achieve the semantics of overloaded functions, so all the reasons not to overload functions apply. The defaults for arguments in a virtual function call are determined by the static type of the target object, and there's no guarantee that all overrides of a given function declare the same defaults. Default parameters are re-evaluated at each call site, which can bloat the generated code. Readers may also expect the default's value to be fixed at the declaration instead of varying at each call. Function pointers are confusing in the presence of default arguments, since the function signature often doesn't match the call signature. Adding function overloads avoids these problems. Default arguments are banned on virtual functions, where they don't work properly, and in cases where the specified default might not evaluate to the same value depending on when it was evaluated. (For example, don't write In some other cases, default arguments can improve the readability of their function declarations enough to overcome the downsides above, so they are allowed. When in doubt, use overloads. Trailing Return Type SyntaxUse trailing return types only where using the ordinary syntax (leading return types) is impractical or much less readable. C++ allows two different forms of function declarations. In the older form, the return type appears before the function name. For example: int foo(int x); The newer form uses the auto foo(int x) -> int; The trailing return type
is in the function's scope. This doesn't make a difference for a simple case like Trailing return types are the only way to explicitly specify the return type of a lambda expression. In some cases the compiler is able to deduce a lambda's return type, but not in all cases. Even when the compiler can deduce it automatically, sometimes specifying it explicitly would be clearer for readers. Sometimes it's easier and more readable to specify a return type after the function's parameter list has already appeared. This is particularly true when the return type depends on template parameters. For example: template versus template Trailing return type syntax is relatively new and it has no analogue in C++-like languages such as C and Java, so some readers may find it unfamiliar. Existing code bases have an enormous number of function declarations that aren't going to get changed to use the new syntax, so the realistic choices are using the old syntax only or using a mixture of the two. Using a single version is better for uniformity of style. In most cases, continue to use the older style of function declaration where the return type goes before the function name. Use the new trailing-return-type form only in cases where it's required (such as lambdas) or where, by putting the type after the function's parameter list, it allows you to write the type in a much more readable way. The latter case should be rare; it's mostly an issue in fairly complicated template code, which is discouraged in most cases. Google-Specific MagicThere are various tricks and utilities that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere. Ownership and Smart PointersPrefer to have single, fixed owners for dynamically allocated objects. Prefer to transfer ownership with smart pointers. "Ownership" is a bookkeeping technique for managing dynamically allocated memory (and other resources). The owner of a dynamically allocated object is an object or function that is responsible for ensuring that it is deleted when no longer needed. Ownership can sometimes be shared, in which case the last owner is typically responsible for deleting it. Even when ownership is not shared, it can be transferred from one piece of code to another. "Smart" pointers are classes that act like pointers, e.g., by overloading the
If dynamic allocation is necessary, prefer to keep ownership with the code that allocated it. If other code needs access to the object, consider passing it a copy, or passing a pointer or reference without transferring ownership. Prefer to use std::unique_ptr Do not design your code to use shared ownership without a
very good reason. One such reason is to avoid expensive copy operations, but you should only do this if the performance benefits are significant, and the underlying object is immutable (i.e., Never use cpplintUse
Some projects have instructions on how to run Other C++ FeaturesRvalue ReferencesUse rvalue references only in certain special cases listed below. Rvalue references are a type of reference that can only bind to temporary objects. The syntax is similar to traditional reference syntax. For example, When the token '&&' is applied to an unqualified template argument in a function parameter, special template argument deduction rules apply. Such a reference is called forwarding reference.
Do not use rvalue references (or apply the
FriendsWe allow use of Friends should usually be defined in the same file so that the reader
does not have to look in another file to find uses of the private members of a class. A common use of Friends extend, but do not break, the encapsulation boundary of a class. In some cases this is better than making a member public when you want to give only one other class access to it. However, most classes should interact with other classes solely through their public members. ExceptionsWe do not use C++ exceptions.
On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions. Given that Google's existing code is not exception-tolerant, the costs of using exceptions are somewhat greater than the costs in a new project. The conversion process would be slow and error-prone. We don't believe that the available alternatives to exceptions, such as error codes and assertions, introduce a significant burden. Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. Because we'd like to use our open-source projects at Google and it's difficult to do so if those projects use exceptions, we need to advise against exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch. This prohibition also applies to exception handling related features such as There is an exception to this rule (no pun intended) for Windows code.
|