Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 # Chromium C++ style guide | |
| 2 | |
| 3 _For other languages, please see the [Chromium style guides](https://chromium.go oglesource.com/chromium/src/+/master/styleguide/styleguide.md)._ | |
| 4 | |
| 5 Chromium follows the [Google C++ Style | |
| 6 Guide](https://google.github.io/styleguide/cppguide.html) unless an exception | |
| 7 is listed below. | |
| 8 | |
|
jbroman
2016/07/06 19:38:03
The exception for Blink style is missing here. Bli
| |
| 9 A checkout should give you | |
| 10 [clang-format](https://chromium.googlesource.com/chromium/src/+/master/docs/clan g_format.md) | |
| 11 to automatically format C++ code. By policy, Clang's formatting of code should | |
| 12 always be accepted in code reviews. | |
| 13 | |
| 14 You can propose changes to the style guide by sending an email to | |
| 15 `cxx@chromium.org`. Ideally, the list will arrive at some consensus and the | |
| 16 wiki page will be updated to mention that consensus. If there's no consensus, | |
| 17 `src/styleguide/c++/OWNERS` get to decide. | |
| 18 | |
| 19 ## C++11 features | |
| 20 | |
| 21 Google style has adopted most C++11 features, but Chromium has a more | |
| 22 restricted set. The status of C++11 features in Chromium is tracked in the | |
| 23 separate [C++11 use in Chromium](https://chromium-cpp.appspot.com/) page. | |
| 24 | |
| 25 ## Naming | |
| 26 | |
| 27 * "Chromium" is the name of the project, not the product, and should never | |
| 28 appear in code, variable names, API names etc. Use "Chrome" instead. | |
| 29 | |
| 30 * Though the Google C++ Style Guide now says to use `kConstantNaming` for | |
| 31 enums, Chromium was written using `MACRO_STYLE` naming. In enums that are | |
| 32 actually enumerations (i.e. have multiple values), continue to use this | |
| 33 style for consistency. Use `kConstantNaming` when using the "enum hack" to | |
| 34 define a single constant, as you would for a const int or the like. | |
| 35 | |
| 36 * Functions used only for testing should be restricted to test-only scenarios | |
| 37 either by `#ifdefing` them appropriately (e.g. `#if defined(UNIT_TEST)`) or | |
| 38 by naming them with a `ForTesting` suffix. The latter will be checked at | |
| 39 presubmit time to ensure they're only called by test files. | |
| 40 | |
| 41 ## Code formatting | |
| 42 | |
| 43 * Put `*` and `&` by the type rather than the variable name. | |
| 44 | |
| 45 * When you derive from a base class, group any overriding functions in your | |
| 46 header file in one labeled section. Use the override specifier on all these | |
| 47 functions. | |
| 48 | |
| 49 * Prefer `(foo == 0)` to `(0 == foo)`. | |
| 50 | |
| 51 * Function declaration order should match function definition order. | |
| 52 | |
| 53 * Prefer putting delegate classes in their own header files. Implementors of | |
| 54 the delegate interface will often be included elsewhere, which will often | |
| 55 cause more coupling with the header of the main class. | |
| 56 | |
| 57 * Don't use else after return. So use: | |
| 58 ``` | |
|
jbroman
2016/07/06 19:38:03
```c++ can be used to get C++ style highlighting i
| |
| 59 if (foo) | |
| 60 return 1; | |
| 61 return 2; | |
| 62 ``` | |
| 63 instead of: | |
| 64 ``` | |
| 65 if (foo) | |
| 66 return 1; | |
| 67 else | |
| 68 return 2; | |
| 69 ``` | |
| 70 | |
| 71 ## Unnamed namespaces | |
| 72 | |
| 73 Items local to a .cc file should be wrapped in an unnamed namespace. While some | |
| 74 such items are already file-scope by default in C++, not all are; also, shared | |
| 75 objects on Linux builds export all symbols, so unnamed namespaces (which | |
| 76 restrict these symbols to the compilation unit) improve function call cost and | |
| 77 reduce the size of entry point tables. | |
| 78 | |
| 79 ## Exporting symbols | |
| 80 | |
| 81 When building shared libraries and DLLs, we need to indicate which functions | |
| 82 and classes should be visible outside of the library, and which should only be | |
| 83 visible inside the library. | |
| 84 | |
| 85 Symbols can be exported by annotating with a `<COMPONENT>_EXPORT` macro name | |
| 86 (where `<COMPONENT>` is the name of the component being built, e.g. BASE, NET, | |
| 87 CONTENT, etc.). Class annotations should precede the class name: | |
| 88 ``` | |
| 89 class FOO_EXPORT Foo { | |
| 90 void Bar(); | |
| 91 void Baz(); | |
| 92 // ... | |
| 93 }; | |
| 94 ``` | |
| 95 | |
| 96 Function annotations should precede the return type: | |
| 97 ``` | |
| 98 class FooSingleton { | |
| 99 FOO_EXPORT Foo& GetFoo(); | |
| 100 FOO_EXPORT Foo& SetFooForTesting(Foo& foo); | |
| 101 void SetFoo(Foo& foo); | |
| 102 }; | |
| 103 ``` | |
| 104 | |
| 105 These examples result in `Foo::Bar()`, `Foo::Baz()`, `FooSingleton::GetFoo()`, | |
| 106 and `FooSingleton::SetFooForTesting()` all being available outside of the DLL, | |
| 107 but not `FooSingleton::SetFoo()`. | |
| 108 | |
| 109 Whether something is exported is distinct from whether it is public or private, | |
| 110 or even whether it would normally be considered part of the external API. For | |
| 111 example, if part of the external API is an inlined function that calls a | |
| 112 private function, that private function must be exported as well. | |
| 113 | |
| 114 ## Multiple inheritance | |
| 115 | |
| 116 Multiple inheritance and virtual inheritance are permitted in Chromium code, | |
| 117 but discouraged (beyond the "interface" style of inheritance allowed by the | |
| 118 Google style guide, for which we do not require classes to have the "Interface" | |
| 119 suffix). Consider whether composition could solve the problem instead. | |
| 120 | |
| 121 ## Inline functions | |
| 122 | |
| 123 Simple accessors should generally be the only inline functions. These should be | |
| 124 named `unix_hacker_style()`. Virtual functions should never be declared this way . | |
| 125 For more detail, consult the [C++ Dos and | |
| 126 Don'ts](https://www.chromium.org/developers/coding-style/cpp-dos-and-donts) | |
| 127 section on inlining. | |
| 128 | |
| 129 ## Logging | |
| 130 | |
| 131 Remove most logging calls before checking in. Unless you're adding temporary | |
| 132 logging to track down a specific bug, and you have a plan for how to collect | |
| 133 the logged data from user machines, you should generally not add logging | |
| 134 statements. | |
| 135 | |
| 136 For the rare case when logging needs to stay in the codebase for a while, | |
| 137 prefer `DVLOG(1)` to other logging methods. This avoids bloating the release | |
| 138 executable and in debug can be selectively enabled at runtime by command-line | |
| 139 arguments: | |
| 140 | |
| 141 * `--v=n` sets the global log level to n (default 0). All log statements with a | |
| 142 log level less than or equal to the global level will be printed. | |
| 143 | |
| 144 * `--vmodule=mod=n[,mod=n,...]` overrides the global log level for the module | |
| 145 mod. Supplying the string foo for mod will affect all files named foo.cc, | |
| 146 while supplying a wildcard like `*bar/baz*` will affect all files with | |
| 147 `bar/baz` in their full pathnames. | |
| 148 | |
| 149 ## Platform-specific code | |
| 150 | |
| 151 To `#ifdef` code for specific platforms, use the macros defined in | |
| 152 `build/build_config.h` and in the Chromium build config files, not other macros | |
| 153 set by specific compilers or build environments (e.g. `WIN32`). | |
| 154 | |
| 155 Place platform-specific #includes in their own section below the "normal" | |
| 156 `#includes`. Repeat the standard `#include` order within this section: | |
| 157 | |
| 158 ``` | |
| 159 #include "foo/foo.h" | |
| 160 | |
| 161 #include <stdint.h> | |
| 162 #include <algorithm> | |
| 163 | |
| 164 #include "base/strings/utf_string_conversions.h" | |
| 165 #include "chrome/common/render_messages.h" | |
| 166 | |
| 167 #if defined(OS_WIN) | |
| 168 #include <windows.h> | |
| 169 #include "base/win/scoped_comptr.h" | |
| 170 #elif defined(OS_POSIX) | |
| 171 #include "base/posix/global_descriptors.h" | |
| 172 #endif | |
| 173 ``` | |
| 174 | |
| 175 ## Types | |
| 176 | |
| 177 * Use `size_t` for object and allocation sizes, object counts, array and | |
| 178 pointer offsets, vector indices, and so on. The signed types are incorrect | |
| 179 and unsafe for these purposes (e.g. integer overflow behavior for signed | |
| 180 types is undefined in the C and C++ standards, while the behavior is | |
| 181 defined for unsigned types.) The C++ STL is a guide here: they use `size_t` | |
| 182 and `foo::size_type` for very good reasons. | |
| 183 | |
| 184 * Use `size_t` directly in preference to `std::string::size_type` and similar. | |
| 185 | |
| 186 * Occasionally classes may have a good reason to use a type other than `size_t ` | |
| 187 for one of these concepts, e.g. as a storage space optimization. In these | |
| 188 cases, continue to use `size_t` in public-facing function declarations. | |
| 189 | |
| 190 * Be aware that `size_t` (object sizes and indices), `off_t` (file offsets), | |
| 191 `ptrdiff_t` (the difference between two pointer values), `intptr_t` (an | |
| 192 integer type large enough to hold the value of a pointer), `uint32_t`, | |
| 193 `uint64_t`, and so on are not necessarily the same. Use the right type for | |
| 194 your purpose. | |
| 195 | |
| 196 * When casting to and from different types, use `static_cast<>()` when you kno w | |
| 197 the conversion is safe. Use `checked_cast<>()` (from | |
| 198 `base/numerics/safe_conversions.h`) when you need to enforce via `CHECK()` t hat | |
| 199 the source value is in-range for the destination type. Use | |
| 200 `saturated_cast<>()` (from the same file) if you instead wish to clamp | |
| 201 out-of-range values. | |
| 202 | |
| 203 * Do not use unsigned types to mean "this value should never be < 0". For | |
| 204 that, use assertions or run-time checks (as appropriate). | |
| 205 | |
| 206 * In cases where the exact size of the type matters (e.g. a 32-bit pixel | |
| 207 value, a bitmask, or a counter that has to be a particular width), use one | |
| 208 of the sized types from `<stdint.h>`, e.g. `uint32_t`. | |
| 209 | |
| 210 * When passing values across network or process boundaries, use | |
| 211 explicitly-sized types for safety, since the sending and receiving ends may | |
| 212 not have been compiled with the same sizes for things like int and | |
| 213 `size_t`. However, to the greatest degree possible, avoid letting these | |
| 214 sized types bleed through the APIs of the layers in question. | |
| 215 | |
| 216 * Don't use `std::wstring`. Use `base::string16` or `base::FilePath` instead. | |
| 217 (Windows-specific code interfacing with system APIs using `wstring` and | |
| 218 `wchar_t` can still use `string16` and `char16`; it is safe to assume that | |
| 219 these are equivalent to the "wide" types.) | |
| 220 | |
| 221 ## Object ownership and calling conventions | |
| 222 | |
| 223 When functions need to take raw or smart pointers as parameters, use the | |
| 224 following conventions. Here we refer to the parameter type as `T` and name as | |
| 225 `t`. | |
| 226 | |
| 227 * If the function does not modify `t`'s ownership, declare the param as `T*`. The | |
| 228 caller is expected to ensure `t` stays alive as long as necessary, generally | |
| 229 through the duration of the call. Exception: In rare cases (e.g. using | |
| 230 lambdas with STL algorithms over containers of `uniuqe_ptr<>`s), you may be | |
| 231 forced to declare the param as `const std::unique_ptr<T>&`. Do this only whe n | |
| 232 required. | |
| 233 | |
| 234 * If the function takes ownership of a non-refcounted object, declare the | |
| 235 param as `std::unique_ptr<T>`. | |
| 236 | |
| 237 * If the function (at least sometimes) takes a ref on a refcounted object, | |
| 238 declare the param as `base::scoped_refptr<T>`. The caller can decide | |
|
jbroman
2016/07/06 19:38:03
scoped_refptr is not in namespace base.
| |
| 239 whether it wishes to transfer ownership (by calling `std::move(t)` when | |
| 240 passing `t`) or retain its ref (by simply passing t directly). | |
| 241 | |
| 242 * In short, functions should never take ownership of parameters passed as raw | |
| 243 pointers, and there should rarely be a need to pass smart pointers by const | |
| 244 ref. | |
| 245 | |
| 246 Conventions for return values are similar: return raw pointers when the caller | |
| 247 does not take ownership, and return smart pointers by value otherwise, | |
| 248 potentially in conjunction with `std::move()`. | |
| 249 | |
| 250 A great deal of Chromium code predates the above rules. In particular, some | |
| 251 functions take ownership of params passed as `T*`, or take `const | |
| 252 scoped_refptr<T>&` instead of `T*`, or return `T*` instead of | |
| 253 `scoped_refptr<T>` (to avoid refcount churn pre-C++11). Try to clean up such | |
| 254 code when you find it, or at least not make such usage any more widespread. | |
| 255 | |
| 256 ## Forward declarations vs. #includes | |
| 257 | |
| 258 Unlike the Google style guide, Chromium style prefers forward declarations to | |
| 259 `#includes` where possible. This can reduce compile times and result in fewer | |
| 260 files needing recompilation when a header changes. | |
| 261 | |
| 262 You can and should use forward declarations for most types passed or returned | |
| 263 by value, reference, or pointer, or types stored as pointer members or in most | |
| 264 STL containers. However, if it would otherwise make sense to use a type as a | |
| 265 member by-value, don't convert it to a pointer just to be able to | |
| 266 forward-declare the type. | |
| 267 | |
| 268 ## File headers | |
| 269 | |
| 270 All files in Chromium start with a common license header. That header should loo k like this: | |
| 271 | |
| 272 ``` | |
| 273 // Copyright $YEAR The Chromium Authors. All rights reserved. | |
| 274 // Use of this source code is governed by a BSD-style license that can be | |
| 275 // found in the LICENSE file. | |
| 276 ``` | |
| 277 | |
| 278 Some important notes about this header: | |
| 279 | |
| 280 * There is no `(c)` after `Copyright`. | |
| 281 | |
| 282 * `$YEAR` should be set to the current year at the time a file is created, and not changed thereafter. | |
| 283 | |
| 284 * For files specific to Chromium OS, replace the word Chromium with the phrase Chromium OS. | |
| 285 | |
| 286 * If the style changes, don't bother to update existing files to comply with | |
| 287 the new style. For the same reason, don't just blindly copy an existing | |
| 288 file's header when creating a new file, since the existing file may use an | |
| 289 outdated style. | |
| 290 | |
| 291 * The Chromium project hosts mirrors of some upstream open-source projects. | |
| 292 When contributing to these portions of the repository, retain the existing | |
| 293 file headers. | |
| 294 | |
| 295 Use standard `#include` guards in all header files (see the Google style guide | |
| 296 sections on these for the naming convention). Do not use `#pragma once`; | |
| 297 historically it was not supported on all platforms, and it does not seem to | |
| 298 outperform #include guards even on platforms which do support it. | |
| 299 | |
| 300 ## CHECK(), DCHECK(), and NOTREACHED() | |
| 301 | |
| 302 The `CHECK()` macro will cause an immediate crash if its condition is not met. | |
| 303 `DCHECK()` is like `CHECK()` but is only compiled in when `DCHECK_IS_ON` is true | |
| 304 (debug builds and some bot configurations, but not end-user builds). | |
| 305 `NOTREACHED()` is equivalent to `DCHECK(false)`. Here are some rules for using | |
| 306 these: | |
| 307 | |
| 308 * Use `DCHECK()` or `NOTREACHED()` as assertions, e.g. to document pre- and | |
| 309 post-conditions. A `DCHECK()` means "this condition must always be true", | |
| 310 not "this condition is normally true, but perhaps not in exceptional | |
| 311 cases." Things like disk corruption or strange network errors are examples | |
| 312 of exceptional circumstances that nevertheless should not result in | |
| 313 `DCHECK()` failure. | |
| 314 | |
| 315 * A consequence of this is that you should not handle DCHECK() failures, even | |
| 316 if failure would result in a crash. Attempting to handle a `DCHECK()` failur e | |
| 317 is a statement that the `DCHECK()` can fail, which contradicts the point of | |
| 318 writing the `DCHECK()`. In particular, do not write code like the following: | |
| 319 ``` | |
| 320 DCHECK(foo); | |
| 321 if (!foo) ... // Can't succeed! | |
| 322 | |
| 323 if (!bar) { | |
| 324 NOTREACHED(); | |
| 325 return; // Replace this whole conditional with "DCHECK(bar);" and keep going instead. | |
| 326 } | |
| 327 ``` | |
| 328 | |
| 329 * Use `CHECK()` if the consequence of a failed assertion would be a security | |
| 330 vulnerability, where crashing the browser is preferable. Because this takes | |
| 331 down the whole browser, sometimes there are better options than `CHECK()`. | |
| 332 For example, if a renderer sends the browser process a malformed IPC, an | |
| 333 attacker may control the renderer, but we can simply kill the offending | |
| 334 renderer instead of crashing the whole browser. | |
| 335 | |
| 336 * You can temporarily use `CHECK()` instead of `DCHECK()` when trying to | |
| 337 force crashes in release builds to sniff out which of your assertions is | |
| 338 failing. Don't leave these in the codebase forever; remove them or change | |
| 339 them back once you've solved the problem. | |
| 340 | |
| 341 * Don't use these macros in tests, as they crash the test binary and leave | |
| 342 bots in a bad state. Use the `ASSERT_xx()` and `EXPECT_xx()` family of | |
| 343 macros, which report failures gracefully and can continue running other | |
| 344 tests. | |
| 345 | |
| 346 ## Miscellany | |
| 347 | |
| 348 * Use UTF-8 file encodings and LF line endings. | |
| 349 | |
| 350 * Unit tests and performance tests should be placed in the same directory as | |
| 351 the functionality they're testing. | |
| 352 | |
| 353 * The [C++ do's and | |
| 354 don'ts](https://sites.google.com/a/chromium.org/dev/developers/coding-style/ cpp-dos-and-donts) | |
| 355 page has more helpful information. | |
| OLD | NEW |