Modern 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 and the Abseil library. 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.

If an item remains on the TBD list two years after initial support is added, style arbiters should explicitly move it to an appropriate allowlist or blocklist, allowing it if there are no obvious reasons to ban. The current status of existing standards and Abseil features is:

Table of Contents

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

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::{Once,Repeating}Callback instead. Compared to std::function, base::{Once,Repeating}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.

Abseil Allowed Library Features

The following Abseil library features are allowed in the Chromium codebase.

Feature Snippet Description Documentation Link Notes and Discussion Thread
Status absl::Status Type for returning detailed errors. status.h Approved for use inside a wrapper type. Use abseil_string_conversions.h to convert to and from absl::string_view so the wrapper can expose base::StringPiece. Use absl::Cord directly as minimally necessary to interface; do not expose in the wrapper type API.
Discussion thread
Variant absl::variant Early adaptation of C++17 std::variant. std::variant Discussion thread

Abseil Banned Library Features

The following Abseil library features are not allowed in the Chromium codebase.

Feature Snippet Description Documentation Link Notes and Discussion Thread
Any absl::any a = int{5};
EXPECT_THAT(absl::any_cast<int>(&a), Pointee(5));
EXPECT_EQ(absl::any_cast<size_t>(&a), nullptr);
Early adaptation of C++17 std::any. std::any Banned since workaround for lack of RTTI isn't compatible with the component build. Bug
Command line flags ABSL_FLAG(bool, logs, false, "print logs to stderr");
app --logs=true;
Allows programmatic access to flag values passed on the command-line to binaries. Flags Library Banned since workaround for lack of RTTI isn't compatible with the component build. Bug
Use base::CommandLine instead.
Span absl::Span Early adaptation of C++20 std::span. Using absl::Span Banned due to being less std::-compliant than base::span.
Keep using base::span.
string_view absl::string_view Early adaptation of C++17 std::string_view. absl::string_view Banned due to only working with 8-bit characters. Keep using base::StringPiece from base/strings/.

Abseil TBD Features

The following Abseil 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 and Discussion Thread
128bit integer uint64_t a;
absl::uint128 v = a;
Signed and unsigned 128-bit integer types meant to mimic intrinsic types as closely as possible. Numerics
bind_front absl::bind_front Binds the first N arguments of an invocable object and stores them by value. bind_front.h
Avoid std::bind
Overlaps with base::Bind.
Cleanup FILE* sink_file = fopen(sink_path, "w");
auto sink_closer = absl::MakeCleanup([sink_file] { fclose(sink_file); });
Implements the scope guard idiom, invoking the contained callback's `operator()() &&` on scope exit. cleanup.h Similar to `defer` in Golang.
Containers absl::flat_hash_map, absl::flat_hash_set,
absl::node_hash_map, absl::node_hash_set,
absl::btree_map, absl::btree_set,
absl::btree_multimap, absl::btree_multiset,
absl::InlinedVector, absl::FixedArray
Alternatives to STL containers designed to be more efficient in the general case. Containers
Hash
Supplements base/containers/.
Container utilities auto it = absl::c_find(container, value); Container-based versions of algorithmic functions within C++ standard library. container.h Overlaps with base/ranges/algorithm.h.
FunctionRef absl::FunctionRef Type for holding a non-owning reference to an object of any invocable type. function_ref.h
Optional absl::optional Early adaptation of C++17 std::optional. std::optional Overlaps with base::Optional.
Random absl::BitGen bitgen;
size_t index = absl::Uniform(bitgen, 0u, elems.size());
Functions and utilities for generating pseudorandom data. Random library Overlaps with base/rand_util.h.
StatusOr absl::StatusOr<T> An object that is either a usable value, or an error Status explaining why such a value is not present. statusor.h
String Formatting absl::StrFormat A typesafe replacement for the family of printf() string formatting routines. String Formatting
Strings Library absl::StrSplit, absl::StrJoin,
absl::StrCat, absl::StrAppend,
absl::Substitute, absl::StrContains
Classes and utility functions for manipulating and comparing strings. String Utilities Overlaps with base/strings.
Synchronization absl::Mutex Primitives for managing tasks across different threads. Synchronization Overlaps with Lock in base/synchronization/.
Time library absl::Duration, absl::Time,
absl::TimeZone, absl::CivilDay
Abstractions for holding time values, both in terms of absolute time and civil time. Time Overlaps with Time APIs in base/.