# C++11 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.

This summarizes the new and updated features in C++11 (for both the language itself and the Standard Library) from the perspective of what's allowed in Chromium. When applicable, it contains pointers to more detailed information. This Guide applies to Chromium and its subprojects, though subprojects can choose to be more restrictive if necessary for toolchain support.

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.

## Table of Contents

## C++11 Allowed Features

The following features are currently allowed.

Feature | Snippet | Description | Documentation Link | Notes and Discussion Thread
--- | --- | --- | --- | ---
__func__ Local Variable | `__func__` | Provides a local variable containing the name of the enclosing function | __func__ | Use instead of the non-standard `__FUNCTION__`. Discussion thread
Angle Bracket Parsing in Templates | `>>` for `> >`, `<::` for `< ::` | More intuitive parsing of template parameters | C++ templates angle brackets pitfall | Recommended to increase readability. Approved without discussion.
Arrays | `std::array` | A fixed-size replacement for built-in arrays, with STL support | std::array | Useful in performance-critical situations, with small, fixed-size arrays. In most cases, consider std::vector instead. std::vector is cheaper to std::move and is more widely used. Discussion thread
Automatic Types | `auto` | Automatic type deduction | auto specifier | Google Style Guide. Discussion thread. Another discussion thread
Constant Expressions | `constexpr` | Compile-time constant expressions | 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
Declared Type Accessor | `decltype(expression)` | Provides a means to determine the type of an expression at compile-time, useful most often in templates. | decltype specifier | Usage should be rare. Discussion thread
Default Function Creation | `Function(arguments) = default;` | Instructs the compiler to generate a default version of the indicated function | What's the point in defaulting functions in C++11? | Discussion thread
Default Function Template Arguments | `template <typename T = type> type Function(T var) {}` | Allow function templates, like classes, to have default arguments | Default Template Arguments for Function Templates | Discussion thread
Delegated Constructors | `Class() : Class(0) {} Class(type var) : Class(var, 0) {}` | Allow overloaded constructors to use common initialization code | Introduction to the C++11 feature: delegating constructors | Discussion thread
Enumerated Type Classes and Enum Bases | `enum class classname enum class classname : base-type enum enumname : base-type` | Provide enums as full classes, with no implicit conversion to booleans or integers. Provide an explicit underlying type for enum classes and regular enums. | enumeration declaration | Enum classes are still enums and follow enum naming rules (which means SHOUTY_CASE in the Chromium Style Guide). Discussion thread
Explicit Conversion Operators | `explicit operator type() { ... }` | Allows conversion operators that cannot be implicitly invoked | explicit specifier | Prefer to the "safe bool" idiom. Discussion thread
Final Specifier | `final` | Indicates that a class or function is final and cannot be overridden | final specifier | Recommended for new code. Discussion thread
Function Suppression | `Function(arguments) = delete;` | Suppresses the implementation of a function, especially a synthetic function such as a copy constructor | Deleted functions | Discussion thread
Inherited Constructors | `class Derived : Base { using Base::Base; };` | Allows derived classes to inherit constructors from base classes | Inheriting constructors | Discussion thread
Lambda Expressions | `[captures](params) -> ret { body }` | Anonymous functions | Lambda functions | Lambdas are typically useful as a parameter to methods or functions that will use them immediately, such as those in `<algorithm>`. Be careful with default captures (`[=]`, `[&]`), and do not bind or store any capturing lambdas outside the lifetime of the stack frame they are defined in; use `base::Callback` for this instead, as it helps prevent object lifetime mistakes. (Captureless lambdas can be used with `base::Bind` as they do not have the same risks.) Google Style Guide. Discussion thread. Another discussion thread (about captureless lambdas and `base::Bind`).
Local Types as Template Arguments | `void func() { class Pred { public: bool operator()(const T&) { ... } }; std::remove_if(vec.begin(), vec.end(), Pred());` | Allows local and unnamed types as template arguments | Local types, types without linkage and unnamed types as template arguments | Usage should be rare. Approved without discussion.
Noexcept Specifier | `void f() noexcept` | Specifies that a function will not throw exceptions | noexcept specifier | Chromium compiles without exception support, but there are still cases where explicitly marking a function as `noexcept` may be necessary to compile, or for performance reasons. Usage should be rare. Discussion thread
Non-Static Class Member Initializers | `class C { type var = value; C() // copy-initializes var` | Allows non-static class members to be initialized at their definitions (outside constructors) | Non-static data members | Discussion thread
Null Pointer Constant | `nullptr` | Declares a type-safe null pointer | nullptr, the pointer literal | Prefer over `NULL` or `0`. Google Style Guide. Discussion thread
Override Specifier | `override` | Indicates that a class or function overrides a base implementation | override specifier | Recommended for new code. Discussion thread
Range-Based For Loops | `for (type var : range)` | Facilitates a more concise syntax for iterating over the elements of a container (or a range of iterators) in a `for` loop | Range-based for loop | As a rule of thumb, use `for (const auto& ...)`, `for (auto& ...)`, or `for (concrete type ...)`. For pointers, use `for (auto* ...)` to make clear that the copy of the loop variable is intended, and only a pointer is copied. Discussion thread
Rvalue References | `T(T&& t)` and `T& operator=(T&& t) template <typename T> void Function(T&& t) { ... }` | Reference that only binds to a temporary object | Rvalue references | Only use these to define move constructors and move assignment operators, and for perfect forwarding. Most classes should not be copyable, even if movable. Continue to use DISALLOW_COPY_AND_ASSIGN in most cases. Google Style Guide. Discussion thread. Another discussion thread
Standard Integers | Typedefs within `<stdint.h>` and `<inttypes>` | Provides fixed-size integers independent of platforms | Standard library header <cstdint> | Approved without discussion. Required by the Google Style Guide.
Static Assertions | `static_assert(bool, string)` | Tests compile-time conditions | Static Assertion | Discussion thread
Trailing Return Types | `auto function declaration -> return_type` | Allows trailing function return value syntax | Declaring functions | Use only where it considerably improves readability. Discussion thread. Another discussion thread
Type Aliases ("using" instead of "typedef") | `using new_alias = typename` | Allows parameterized typedefs | Type alias, alias template | Use instead of typedef, unless the header needs to be compatible with C. Discussion thread
Uniform Initialization Syntax | `type name {[value ..., value]};` | Allows any object of primitive, aggregate or class type to be initialized using brace syntax | Uniform initialization syntax and semantics | See the Chromium C++ Dos And Don'ts guidance on when to use this. Discussion thread
Union Class Members | `union name {class var}` | Allows class type members | Union declaration | Usage should be rare. Discussion thread
Variadic Macros | `#define MACRO(...) Impl(args, __VA_ARGS__)` | Allows macros that accept a variable number of arguments | Are Variadic macros nonstandard? | Usage should be rare. Discussion thread
Variadic Templates | `template <typename ... arg>` | Allows templates that accept a variable number of arguments | Parameter pack | Usage should be rare. Use instead of .pump files. Discussion thread

## C++11 Allowed Library Features

The following library features are currently allowed.

Feature or Library | Snippet | Description | Documentation Link | Notes and Discussion Thread
--- | --- | --- | --- | ---
Access to underlying `std::vector` data | `v.data()` | Returns a pointer to a `std::vector`'s underlying data, accounting for empty vectors. | std::vector::data | Discussion thread
Algorithms | All C++11 features in `<algorithm>`: `all_of`, `any_of`, `none_of` `find_if_not` `copy_if`, `copy_n` `move`, `move_backward` (see note) `shuffle` `is_partitioned`, `partition_copy`, `partition_point` `is_sorted`, `is_sorted_until` `is_heap`, `is_heap_until` `minmax`, `minmax_element` `is_permutation` | Safe and performant implementations of common algorithms | Standard library header <algorithm> | Note that <algorithm> contains a range-based `move` method. This is allowed, but because people may confuse it with the single-arg `std::move`, there is often a way to write code without it that is more readable. Discussion thread. Another discussion thread
Begin and End Non-Member Functions | `std::begin()`, `std::end()` | Allows use of free functions on any container, including fixed-size arrays | std::begin, std::end | Useful for fixed-size arrays. Note that non-member `cbegin()` and `cend()` are not available until C++14. Discussion thread
Conditional Type Selection | `std::enable_if`, `std::conditional` | Enables compile-time conditional type selection | std::enable_if, conditional | Usage should be rare. Discussion thread
Constant Iterator Methods on Containers | E.g. `std::vector::cbegin()`, `std::vector::cend()` | Allows more widespread use of `const_iterator` | std::vector::cbegin, std::vector::cend | Applies to all containers, not just `vector`. Consider using `const_iterator` over `iterator` where possible for the same reason as using `const` variables and functions where possible; see Effective Modern C++ item 13. Discussion thread
Declared Type As Value | `std::declval<class>()` | Converts a type to a reference of the type to allow use of members of the type without constructing it in templates. | std::declval | Usage should be rare. Discussion thread
Emplacement methods for containers | `emplace()`, `emplace_back()`, `emplace_front()`, `emplace_hint()` | Constructs elements directly within a container without a copy or a move. Less verbose than `push_back()` due to not naming the type being constructed. | E.g. std::vector::emplace_back | `std::map::emplace()` is not yet available on all libstdc++ versions we support. When using emplacement for performance reasons, your type should probably be movable (since e.g. a vector of it might be resized); given a movable type, then, consider whether you really need to avoid the move done by `push_back()`. For readability concerns, treat like `auto`; sometimes the brevity over `push_back()` is a win, sometimes a loss. Discussion thread
Forwarding references | `std::forward()` | Perfectly forwards arguments (including rvalues) | std::forward | Allowed, though usage should be rare (primarily for forwarding constructor arguments, or in carefully reviewed library code). Discussion thread
Initializer Lists | `std::initializer_list<T>` | Allows containers to be initialized with aggregate elements | std::initializer_list | Be cautious adding new constructors which take these, as they can hide non-initializer_list constructors in undesirable ways; see Effective Modern C++ Item 7. Discussion thread. Another discussion thread
Math functions | All C++11 features in `<cmath>`, e.g.: `INFINITY`, `NAN`, `FP_NAN` `float_t`, `double_t` `fmax`, `fmin`, `trunc`, `round` `isinf`, `isnan` | Useful for math-related code | Standard library header <cmath> | Discussion thread
Move Iterator Adaptor | `std::make_move_iterator()` | Wraps an iterator so that it moves objects instead of copying them. | std::make_move_iterator | Useful to move objects between containers that contain move-only types like `std::unique_ptr`. Discussion thread
Move Semantics | `std::move()` | Facilitates efficient move operations | std::move | Discussion thread
Null Pointer Type | `std::nullptr_t` | Allows referencing the type of `nullptr`, e.g. in templates | std::nullptr_t | Discussion thread
Random Number Generators | `<random>` | Random number generation algorithms and utilities | Pseudo-random number generation | Because the standard does not define precisely how the `xxx_distribution` objects generate output, the same object may produce different output for the same seed across platforms, or even across different versions of the STL. Do not use these objects in any scenario where behavioral consistency is required. Discussion thread
Raw String Literals | `string var=R"(raw_string)";` | Allows a string to be encoded without any escape sequences, easing parsing in regex expressions, for example | string literal | Beware of passing these as macro arguments, which can trigger a lexer bug on older GCC versions. Discussion thread
String Direct Reference Functions | `std::string::front()`, `std::string::back()` | Returns a reference to the front or back of a string | std::basic_string::front, std::basic_string::back | Discussion thread
Type Traits | All C++11 features in `<type_traits>` except for aligned storage (see separate item), e.g.: `integral_constant` `is_floating_point`, `is_rvalue_reference`, `is_scalar` `is_const`, `is_pod`, `is_unsigned` `is_default_constructible`, `is_move_constructible`, `is_copy_assignable` `enable_if`, `conditional`, `result_of` | Allows compile-time inspection of the properties of types | Standard library header <type_traits> | Note that not all type traits are available on all platforms (e.g. `std::underlying_type` doesn't work in libstdc++ 4.6). Use judiciously. Discussion thread
Tuples | All C++11 features in `<tuple>`, e.g. `std::tie` and `std::tuple`. | A fixed-size ordered collection of values of mixed types | Standard library header <tuple> | libstdc++ 4.6 has a bug where `std::get` can return an lvalue-reference when it should return an rvalue-reference. `base::get` can be used to avoid this. Discussion thread. Another discussion thread
Unordered Associative Containers | `std::unordered_set`, `std::unordered_map`, `std::unordered_multiset`, `std::unordered_multimap` | Allows efficient containers of key/value pairs | std::unordered_map, std::unordered_set | Specify custom hashers instead of specializing `std::hash` for custom types. Google Style Guide. Discussion thread
Unique Pointers | `std::unique_ptr<type>` | A smart pointer with sole ownership of the owned object. | std::unique_ptr | Google Style Guide. Discussion thread

## C++11 Blacklist (Disallowed and Banned Features)

This section lists features that are not allowed to be used yet.

### C++11 Banned Features

This section lists C++11 features that 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 64bit number. Discussion thread
Ref-qualified Member Functions | `class T { void f() & {} void f() && {} }; t.f(); // first T().f(); // second std::move(t).f(); // second` | Allows class member functions to only bind to |this| as an rvalue or lvalue. | const-, volatile-, and ref-qualified member functions | Banned in the Google Style Guide. May only be used in Chromium with explicit approval from `styleguide/c++/OWNERS`. Discussion Thread
User-Defined Literals | `type var = literal_value_type` | Allows user-defined literal expressions | User-defined literals | Banned in the Google Style Guide.

### C++11 Banned Library Features

This section lists C++11 library features that are not allowed in the Chromium codebase.

Feature | Snippet | Description | Documentation Link | Notes and Discussion Thread
--- | --- | --- | --- | ---
Atomics | `<atomic>` | Fine-grained atomic types and operations | Atomic operations library | Use in tcmalloc has caused performance regressions. Banned until we understand this better. 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. Note that the `noexcept` specifier is explicitly allowed above. 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
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
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.

### C++11 Features To Be Discussed

The following C++ language features are currently disallowed. 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
--- | --- | --- | --- | ---
Alignment Features | `alignas` specifier, `alignof` operator | Object alignment | alignas specifier, alignof operator | Reevaluate now that MSVS2015 is available. Discussion thread
Attributes | `[[attribute_name]]` | Attaches properties to declarations that specific compiler implementations may use. | C++11 generalized attributes |
UTF-8, UTF-16, UTF-32 String Literals | `u8"string", u"string", U"string"` | Enforces UTF-8, UTF-16, UTF-32 encoding on all string literals | string literal | Reevaluate now that MSVS2015 is available. Discussion thread
UTF-16 and UTF-32 Support (16-Bit and 32-Bit Character Types) | `char16_t` and `char32_t` | Provides character types for handling 16-bit and 32-bit code units (useful for encoding UTF-16 and UTF-32 string data) | Fundamental types | Reevaluate now that MSVS2015 is available. Non-UTF-8 text is banned by the Google Style Guide. However, may be useful for consuming non-ASCII data. Discussion thread

### C++11 Standard Library Features To Be Discussed

The following C++ library features are currently disallowed. 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
--- | --- | --- | --- | ---
Address Retrieval | `std::addressof()` | Obtains the address of an object even with overloaded `operator&` | std::addressof | Usage should be rare as operator overloading is rare and `&` should suffice in most cases. May be preferable over `&` for performing object identity checks.
Aligned Storage | `std::aligned_storage<Size, Align>::type` `std::alignment_of<T>`, `std::aligned_union<Size, ...Types>` `std::max_align_t` | Declare uninitialized storage having a specified alignment, or determine alignments. | std::aligned_storage | `std::aligned_storage` and `std::aligned_union` are disallowed in google3 over concerns about compatibility with internal cross-compiling toolchains.
Allocator Traits | `std::allocator_traits` | Provides an interface for accessing custom allocators | std::allocator_traits | Usage should be rare.
Complex Inverse Trigonometric and Hyperbolic Functions | Functions within `<complex>` | Adds inverse trigonomentric and hyperbolic non-member functions to the `<complex>` library. | std::complex |
Container Compaction Functions | `std::vector::shrink_to_fit()`, `std::deque::shrink_to_fit()`, `std::string::shrink_to_fit()` | Requests the removal of unused space in the container | std::vector::shrink_to_fit, std::deque::shrink_to_fit, std::basic_string::shrink_to_fit |
Date/Time String Formatting Specifiers | `std::strftime()` | Converts date and time information into a formatted string using new specifiers | std::strftime |
Function Return Type Deduction | `std::result_of<Functor(ArgTypes...)>` | Extracts the return type from the type signature of a function call invocation at compile-time. | std::result_of | Why does std::result_of take an (unrelated) function type as a type argument?
Forward Lists | `std::forward_list` | Provides an efficient singly linked list | std::forward_list |
Gamma Natural Log | `std::lgamma()` | Computes the natural log of the gamma of a floating point value | std::lgamma |
Garbage Collection Features | `std::{un}declare_reachable()`, `std::{un}declare_no_pointers()` | Enables garbage collection implementations | std::declare_reachable, std::declare_no_pointers |
Iterator Operators | `std::next()`, `std::prev()` | Copies an iterator and increments or decrements the copy by some value | std::next, std::prev |
Pointer Traits Class Template | `std::pointer_traits` | Provides a standard way to access properties of pointers and pointer-like types | std::pointer_traits | Useful for determining the element type pointed at by a (possibly smart) pointer.
Reference Wrapper Classes | `std::reference_wrapper` and `std::ref()`, `std::cref()` | Allows you to wrap a reference within a standard object (and use those within containers) | std::reference_wrapper |
Soft Program Exits | `std::at_quick_exit()`, `std::quick_exit()` | Allows registration of functions to be called upon exit, allowing cleaner program exit than `abort()` or `exit` | std:quick_exit |
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 | May be useful to replace dmg_fp.
System Errors | `<system_error>` | Provides a standard system error library | Standard library header <system_error> |
Type-Generic Math Functions | `<ctgmath>` | Provides a means to call real or complex functions based on the type of arguments | Standard library header <ctgmath> |
Type Info Enhancements | `std::type_index`, `std::type_info::hash_code()` | Allows type information (most often within containers) that can be copied, assigned, or hashed | std::type_index, std::type_info::hash_code | `std::type_index` is a thin wrapper for `std::type_info`, allowing you to use it directly within both associative and unordered containers.
Variadic Copy Macro | `va_copy(va_list dest, va_list src)` | Makes a copy of the variadic function arguments | va_copy |
Weak Pointers | `std::weak_ptr` | Allows a weak reference to a `std::shared_ptr` | std::weak_ptr | Ownership and Smart Pointers
Wide String Support | `std::wstring_convert`, `std::wbuffer_convert` `std::codecvt_utf8`, `std::codecvt_utf16`, `std::codecvt_utf8_utf16` | Converts between string encodings | std::wstring_convert, std::wbuffer_convert, std::codecvt_utf8, std::codecvt_utf16, std::codecvt_utf8_utf16 | Non-UTF-8 text is banned by the Google Style Guide. However, may be useful for consuming non-ASCII data.