C++ use in Chromium

This document lives at src/styleguide/c++/c++11.html in a Chromium checkout and is part of the more general Chromium C++ style guide. It summarizes the supported state of new and updated language and library features in recent C++ standards. This guide applies to both Chromium and its subprojects, though subprojects can choose to be more restrictive if necessary for toolchain support.

The C++ language has in recent years received an updated standard every three years (C++11, C++14, C++17). For various reasons, Chromium does not immediately allow new features on the publication of such a standard. Instead, once toolchain support is sufficient, a standard is declared "initially supported", with new language/library features banned pending discussion.

You can propose changing the status of a feature by sending an email to cxx@chromium.org. Include a short blurb on what the feature is and why you think it should or should not be allowed, along with links to any relevant previous discussion. If the list arrives at some consensus, send a codereview to change this file accordingly, linking to your discussion thread.

Two years after a standard is initially supported in Chromium, style arbiters should make a final decision on any remaining TBD features to be banned, then default-allow all non-banned portions of the standard. The current status of existing standards is:

Table of Contents

  1. Allowed Features
    1. Language C++14
    2. Library C++14
  2. Banned Features
    1. Language C++11
    2. Library C++11 C++14
  3. To Be Discussed
    1. Language C++14
    2. Library C++14

C++14 Allowed Language Features

The following C++14 language features are allowed in the Chromium codebase.

Feature Snippet Description Documentation Link Notes and Discussion Thread
Aggregate member initialization struct Point { int x, y, z = 0; };
Point p = {2, 3};
Allows classes with default member initializers to be initialized with aggregate initialization, optionally omitting data members with such initializers. aggregate initialization Discussion thread
Binary literals int i = 0b1001; Allows defining literals in base two. Integer literals Discussion thread
Function return type deduction auto f() { return 42; }
decltype(auto) g() { return 42; }
Allows the return type of a function to be automatically deduced from its return statements, according to either template or decltype rules. Return type deduction Usage should be rare, primarily for abstract template code. If you're not sure of the difference, prefer decltype(auto) for templated forwarding/wrapper functions and auto for other cases; see Effective Modern C++ item 3 for more detail. Discussion thread
Generic lambdas [](const auto& x) { ... } Allows lambda argument types to be deduced using auto (according to the rules that apply to templates). lambda expressions Discussion thread
Lambda capture expressions auto widget = std::make_unique<Widget>();
auto lambda = [widget = std::move(widget)]() {
  SetWidget(std::move(widget));
}
Allows lambda captures to be explicitly initialized with expressions. Lambda capture Lambda capture expressions should only be used to capture existing names in ways that C++11's direct capture doesn't allow, and should not be used as a way to introduce new names. That is, capture expressions should always shadow existing variables (or data members), and not substantially change their meaning. Usage should be rare. Discussion thread with examples
Number literal separators float f = 1'000'000.000'1; 's anywhere in int or float literals are ignored Integer literals, Floating point literals Discussion thread
Relaxed constant expressions constexpr int Factorial(int n) {
  int result = 1;
  while (n > 0)
    result *= n--;
  return result;
}
Allows use of more declarations, conditional statements and loops inside constexpr functions. constexpr specifier Prefer to const for variables where possible. Use cautiously on functions. Don't go out of the way to convert existing code. Google Style Guide. Discussion thread

C++14 Allowed Library Features

The following C++14 library features are allowed in the Chromium codebase.

Feature or Library Snippet Description Documentation Link Notes and Discussion Thread
Constant begin/end non-member functions std::cbegin(container)
std::cend(container)
std::crbegin(container)
std::crend(container)
Constant counterparts to std::begin etc. std::cbegin
Heterogeneous lookup in associative containers // Does not construct an std::string to use as the lookup key.
std::map<std::string, int, std::less<>> map;
auto it = map.find("answer");
Allows searching associative containers without converting the key to exactly match the stored key type, assuming a suitable comparator exists. std::less Discussion thread
std::integer_sequence template <size_t... I>
void CallFooImpl(std::index_sequence<I...>) {
  Foo(I...);
}

template <size_t N>
void CallFoo() {
  CallFooImpl(std::make_index_sequence<N>());
}
Template metaprogramming utility for representing a sequence of integers as a type. std::integer_sequence This also includes the alias, std::index_sequence, which is the specialization for size_t. Discussion thread
std::make_unique auto widget = std::make_unique<Widget>(); Allocates objects on the heap and immediately constructs an std::unique_ptr to assume ownership. std::make_unique Discussion thread
Transparent function objects Arithmetic operations:
std::plus<>, std::minus<> ...
Comparisons:
std::less<>, std::equal_to<>...
Logical operations:
std::logical_and<>, std::logical_or<>...
Bitwise operations:
std::bit_and<>, std::bit_or<>...
Function objects that deduce argument types. std::less<> Should replace base::less and usage of these functors with explicit types where appropriate. Discussion thread
Tuple addressing by type std::tuple<int, char> enterprise(1701, 'D');
int n = std::get<int>(enterprise);
Allows entries in a tuple to be accessed by type rather than entry, if it is not ambiguous. std::get(std::tuple)
Reverse Iterator Adaptor std::make_reverse_iterator() For a given iterator, deduces the type of a corresponding reverse iterator and constructs it. std::make_reverse_iterator Useful to reduce boilerplate when constructing reverse iterators. The alternative is using std::reverse_iterator(i) where T is the, usually long, type of the iterator i. Discussion thread

C++11 Banned Language Features

The following C++11 language features are not allowed in the Chromium codebase.

Feature or Library Snippet Description Documentation Link Notes and Discussion Thread
Inline Namespaces inline namespace foo { ... } Allows better versioning of namespaces Inline namespaces Banned in the Google Style Guide. Unclear how it will work with components.
long long Type long long var = value; An integer of at least 64 bits Fundamental types Use a stdint.h type if you need a 64-bit number. Discussion thread
User-Defined Literals type var = literal_value_type Allows user-defined literal expressions User-defined literals Banned in the Google Style Guide.
thread_local storage class thread_local int foo = 1; Puts variables into thread local storage. Storage duration Some surprising effects on Mac (discussion, fork). Use base::SequenceLocalStorageSlot for sequence support, and base::ThreadLocal/base::ThreadLocalStorage otherwise.

C++11 Banned Library Features

The following C++11 library features are not allowed in the Chromium codebase.

Feature Snippet Description Documentation Link Notes and Discussion Thread
Bind Operations std::bind(function, args, ...) Declares a function object bound to certain arguments std::bind Use base::Bind instead. Compared to std::bind, base::Bind helps prevent lifetime issues by preventing binding of capturing lambdas and by forcing callers to declare raw pointers as Unretained. Discussion thread
C Floating-Point Environment <cfenv>, <fenv.h> Provides floating point status flags and control modes for C-compatible code Standard library header <cfenv> Banned by the Google Style Guide due to concerns about compiler support.
Date and time utilities <chrono> A standard date and time library Date and time utilities Overlaps with Time APIs in base/. Keep using the base/ classes.
Exceptions <exception> Enhancements to exception throwing and handling Standard library header <exception> Exceptions are banned by the Google Style Guide and disabled in Chromium compiles. However, the noexcept specifier is explicitly allowed. Discussion thread
Function Objects std::function Wraps a standard polymorphic function std::function Use base::Callback instead. Compared to std::function, base::Callback directly supports Chromium's refcounting classes and weak pointers and deals with additional thread safety concerns. Discussion thread
Random Number Engines The random number engines defined in <random> (see separate item for random number distributions), e.g.:
linear_congruential_engine, mersenne_twister_engine
minstd_rand0, mt19937, ranlinux48
random_device
Random number generation algorithms and utilities. Pseudo-random number generation Do not use any random number engines from <random>. Instead, use base::RandomBitGenerator. Discussion thread
Ratio Template Class std::ratio<numerator, denominator> Provides compile-time rational numbers std::ratio Banned by the Google Style Guide due to concerns that this is tied to a more template-heavy interface style.
Regular Expressions <regex> A standard regular expressions library Regular expressions library Overlaps with many regular expression libraries in Chromium. When in doubt, use re2.
Shared Pointers std::shared_ptr Allows shared ownership of a pointer through reference counts std::shared_ptr Needs a lot more evaluation for Chromium, and there isn't enough of a push for this feature. Google Style Guide. Discussion Thread
String-Number Conversion Functions std::stoi(), std::stol(), std::stoul(), std::stoll, std::stoull(), std::stof(), std::stod(), std::stold(), std::to_string() Converts strings to/from numbers std::stoi, std::stol, std::stoll, std::stoul, std::stoull, std::stof, std::stod, std::stold, std::to_string The string-to-number conversions rely on exceptions to communicate failure, while the number-to-string conversions have performance concerns and depend on the locale. Use the routines in base/strings/string_number_conversions.h instead.
Thread Library <thread> and related headers, including
<future>, <mutex>, <condition_variable>
Provides a standard multithreading library using std::thread and associates Thread support library Overlaps with many classes in base/. Keep using the base/ classes for now. base::Thread is tightly coupled to MessageLoop which would make it hard to replace. We should investigate using standard mutexes, or unique_lock, etc. to replace our locking/synchronization classes.
Weak Pointers std::weak_ptr Allows a weak reference to a std::shared_ptr std::weak_ptr Banned because std::shared_ptr is banned. Use base::WeakPtr instead.

C++14 Banned Library Features

The following C++14 library features are not allowed in the Chromium codebase.

Feature Snippet Description Documentation Link Notes and Discussion Thread
std::chrono literals using namespace std::chrono_literals;
auto timeout = 30s;
Allows std::chrono types to be more easily constructed. std::literals::chrono_literals::operator""s Banned because <chrono> is banned.

C++14 TBD Language Features

The following C++14 language features are not allowed in the Chromium codebase. See the top of this page on how to propose moving a feature from this list into the allowed or banned sections.

Feature Snippet Description Documentation Link Notes and Discussion Thread
[[deprecated]] attribute [[deprecated]] void f();
[[deprecated("use h() instead")]] void g();
Marks a function as deprecated. Standard attributes We don't use deprecation warnings in Chromium; if you want to deprecate something, remove all callers and remove the function instead.
decltype(auto) variable declarations decltype(auto) x = 42; Allows deducing the type of a variable using decltype rules. auto specifier Often more surprising than auto. For instance, the decltype deduction rules do not remove references.
Variable templates template <typename T>
constexpr T tau = T(6.283185307179586476925286766559);
Allows templates that declare variables, rather than functions or classes. Variable template

C++14 TBD Library Features

The following C++14 library features are not allowed in the Chromium codebase. See the top of this page on how to propose moving a feature from this list into the allowed or banned sections.

Feature Snippet Description Documentation Link Notes
std::complex literals using namespace std::complex_literals;
std::complex<double> c = 2.0 + 0.5i;
Allows std::complex objects to be more easily constructed. std::literals::complex_literals
std::string literals #include <string>
using std::literals::string_literals::operator"" s;
auto s = "asdf"s; // deduces to std::string
Allows literals of type std::string std::literals::string_literals::operator""s