# C++11 use in Chromium

This document lives at src/styleguide/c++/c++11.html in a Chromium checkout.

This document summarizes the features of C++11 (both in the language itself and in enhancements to the Standard Library) and describes which features are allowed in Chromium and contains pointers to more detailed information. The Guide applies to Chromium and its subprojects. Subprojects can choose to be more restrictive if they need to compile on more toolchains than Chromium.

You can propose to make a feature available or to ban a feature by sending an email to cxx@chromium.org. Ideally include a short blurb on what the feature is, and why you think it should or should not be allowed. Ideally, the list will arrive at some consensus and the wiki page will be updated to mention that consensus. If there's no consensus, `src/styleguide/c++/OWNERS` get to decide -- for divisive features, we expect the decision to be to not use the feature yet and possibly discuss it again a few months later, when we have more experience with the language.

## Table of Contents

## C++11 Allowed Features

The following features are currently allowed.

Feature | Snippet | Description | Documentation Link | Notes and Discussion Thread
--- | --- | --- | --- | ---
Aliases | `using new_alias = typename` | Allow parameterized typedefs | Type alias (using syntax) | Use instead of typedef, unless the header needs to be compatible with C. Discussion thread
Angle Bracket Parsing in Templates | `>>` for `> >` and `<::` 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 | Use according to the Google Style Guide on `auto`. Discussion thread. Another 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? | Doesn't work for move constructors and move assignment operators in MSVC2013. 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. | enum-class | Enum classes are still enums and follow enum naming rules (which means SHOUTY_CASE in the current style guide). Discussion thread
Final Specifier | `final` | Indicates that a class or function is final and cannot be overridden | final Language Reference | Recommended for new code. Existing uses of the `FINAL` macro will be replaced throughout the codebase. Discussion thread
Function Suppression | `Function(arguments) = delete;` | Suppresses the implementation of a function, especially a synthetic function such as a copy constructor | TODO: documentation link | Discussion thread
Lambda Expressions | `[captures](params) -> ret { body }` | Anonymous functions | Lambda functions | Do not bind or store lambdas; use `base::Bind` and `base::Callback` instead, because they offer protection against a large class of object lifetime mistakes. Don't use default captures (`[=]`, `[&]` – Google Style Guide). Lambdas are typically useful as a parameter to methods or functions that will use them immediately, such as those in `<algorithm>`. Discussion thread
Local Types as Template Arguments |  | 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.
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 | Recommended for new code. Discussion thread. Google Style Guide. `std::nullptr_t` can be used too.
Override Specifier | `override` | Indicates that a class or function overrides a base implementation | override Language Reference | Recommended for new code. Existing uses of the `OVERRIDE` macro will be replaced throughout the codebase. Discussion
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 | As per the Google style guide: 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 (or DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND if needed) in most cases. Discussion thread and discussion thread. MSVC 2013 has some known bugs with rvalue references: Exported classes generate copy constructors even if they are not used, which tries to use copy constructors on members. Use DISALLOW_COPY_AND_ASSIGN on the exported class to resolve it. The compiler chooses a T::(T&) constructor before T::(T&&). However copy constructors should be written as T::T(const T&) and these are prioritized correctly. The compiler does not create default move constructors, either implicitly or with the =default keyword. You must provide such constructors explicitly to create them.
Standard Integers | Typedefs within `<stdint.h>` and `<inttypes>` | Provides fixed-size integers independent of platforms | <stdint.h> (cstdint) | Already in common use in the codebase. Approved without discussion.
Static Assertions | `static_assert(bool, string)` | Tests compile-time conditions | Static Assertion | 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
--- | --- | --- | --- | ---
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
Begin and End Non-Member Functions | `std::begin()` and `std::end()` | Allows use of free functions on any container, including fixed-size arrays | std::begin and std::end | Useful for fixed-size arrays. Discussion thread
Conditional Type Selection | `std::enable_if` and `std::conditional` | Enables compile-time conditional type selection | std::enable_if and conditional | Usage should be rare. Discussion thread
Containers containing movable types | `vector<scoped_ptr>` | Enables containers that contain move-only types like `scoped_ptr` | TODO | Allows getting rid of ScopedVector
Lexicographical struct comparison | `tie(a, b, c) < tie(rhs.a, rhs.b, rhs.c)` | Idiom for `operator<` implementation | std::tie | General use of `std::tuple`, and `std::tie` for unpacking or multiple assignments is still not allowed. 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 `scoped_ptr`. Discussion thread
Move Semantics | `std::move()` | Facilitates efficient move operations | `std::move` reference | Discussion thread
Range Move | `std::move()` | Moves contents of an iterator range to a different iterator. This is a counterpart of std::copy that applies std::move() to each element. | `std::move` reference | This is allowed, but there is almost always a way to write code without using this version of std::move. Not using it usually results in cleaner, easier to read, and less confusing code. 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
Type Traits | Class templates within `<type_traits>` | 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 (eg std::underlying_type doesn't work in libstdc++4.6). Use judiciously. Discussion thread
Types, functions, and constants from `<cmath>` | `std::round()`, `std::isnan()`, and others | Useful for math-related code | `<cmath>` | Anything in `<cmath>` is allowed. 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
--- | --- | --- | --- | ---
Alignment Features | `alignas` specifier, `alignof` operator | Object alignment | alignas, alignof | Doesn't work in MSVS2013. MSVS2015 supports them; reevaluate after MSVS2015 is available. Discussion thread
Constant Expressions | `constexpr` | Compile-time constant expressions | constexpr specifier | Doesn't work in MSVS2013. Reevalute once it does. Google Style Guide on `constexpr`
Explicit Conversion Operators | `explicit operator type() { // code }` | Allows conversion operators that cannot be implicitly invoked | explicit specifier | Doesn't work in MSVS2013. Reevaluate once it does. Discussion thread
Function Local Variable | `__func__` | Provides a local variable of the name of the enclosing function for logging purposes | The __func__ Predeclared Identifier is Coming to C++ | Doesn't work in MSVS2013. Reevaluate once it does. Discussion thread
Inherited Constructors | `class Derived : Base { using Base::Base; };` | Allow derived classes to inherit constructors from base classes | Using-declaration | Doesn't work in MSVS2013. Reevaluate once it does. Discussion thread
`long long` Type | `long long var= value;` | An integer of at least 64 bits | Fundamental types | Use an stdint.h type if you need a 64bit number. 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 | Causes incorrect line numbers in MSVS2013 and gcc. Reevaluate once that works. Discussion thread
(Uniform) Initialization Syntax | `type name { [value ..., value]};` | Allows any object of primitive, aggregate or class type to be initialized using brace syntax | TODO: documentation link | Dangerous without library support, see thread. Reevaulate once we have C++11 library support. 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 | Doesn't work in MSVS2013. Reevaluate once it does. Non-UTF-8 text is banned by the C++ Style Guide. However, may be useful for consuming non-ASCII data. Discussion thread
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 | Does not yet work in MSVS2013. Reevaluate once it does. 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. | Member functions | Banned in the google3 C++11 library style guide. Banned in Chromium except by explicit approval from `styleguide/c++/OWNERS`. Discussion Thread

### 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
--- | --- | --- | --- | ---
Chrono Library | `<chrono>` | Provides a standard date and time library | Date and time utilities | Duplicated `Time` APIs in `base/`. Keep using the `base/` classes.
Regex Library | `<regex>` | Provides a standard regular expressions library | Regular expressions library | We already have too many regular expression libraries in Chromium. Use re2 when in doubt.
Thread Library | `<thread> support, including <future>, <mutex>, <condition_variable>` | Provides a standard mulitthreading library using `std::thread` and associates | Thread support library | C++11 has all kinds of classes for threads, mutexes, etc. Since we already have good code for this in `base/`, we should keep using the base classes, at least at first. `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.
Atomics | `std::atomic` and others in `<atomic>` | Fine-grained atomic types and operations | <atomic> | Use in tcmalloc has caused performance regressions. Banned until we understand this better. Discussion Thread
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. Discussion Thread, Google Style Guide
Initializer Lists | `std::initializer_list<T>` | Allows containers to be initialized with aggregate elements | `std::initializer_list` | Banned for now; will be re-evaluated once we switch to MSVC 2015. Discussion Thread

### 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. Note that not all of these features work in all our compilers yet.

Feature | Snippet | Description | Documentation Link | Notes
--- | --- | --- | --- | ---
Attributes | `[[attribute_name]]` | Attaches properties to declarations that specific compiler implementations may use. | C++11 generalized attributes |
Exception Features | `noexcept`, `exception_ptr`, `current_exception()`, `rethrow_exception`, and `nested_exception` | Enhancements to exception throwing and handling | std::exception | Exceptions are banned by the C++ Style Guide. Discussion thread
Inline Namespaces | `inline` | Allows better versioning of namespaces | Namespaces | Unclear how it will work with components
Union Class Members | `union name { class var}` | Allows class type members | Union declarations |
User-Defined Literals | `type var = literal_value_type` | Allows user-defined literal expressions | User-defined literals |

### 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. Note that not all of these features work in all our compilers yet.

Feature | Snippet | Description | Documentation Link | Style Guide Usage
--- | --- | --- | --- | ---
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>` and `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.
Bind Operations | `std::bind(function, args, ...)` | Declares a function object bound to certain arguments | TODO: documentation link |
C Floating-Point Environment | `<cfenv>`, `<fenv.h>` | Provides floating point status flags and control modes for C-compatible code | Standard library header <cfenv> | Compilers do not support use. This is banned in google style guide over compilers not supporting these reliably.
Complex Inverse Trigonometric and Hyperbolic Functions | Functions within `<complex>` | Adds inverse trigonomentric and hyperbolic non-member functions to the `<complex>` library. | std::complex |
Constant Iterator Methods on Containers | `std::cbegin()` and `std::cend()` | Enforces iteration methods that don't change container contents | TODO: documentation link |
Construct Elements in Containers | `emplace()`,`emplace_back()`, `emplace_front()`, `emplace_hint()` | Constructs elements directly within a container without a copy or a move | TODO: documentation link | Use where element construction within a container is needed.
Container Compaction Functions | `std::vector::shrink_to_fit()`, `std::deque::shrink_to_fit()`, and `std::string::shrink_to_fit()` | Requests the removal of unused space in the container | std::vector::shrink_to_fit, std::deque::shrink_to_fit, and 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?
Function Objects | `std::function` | Wraps a standard polymorphic function | TODO: documentation link |
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()` and `std::{un}declare_no_pointers()` | Enables garbage collection implementations | std::declare_reachable and std::declare_no_pointers |
Heap Validation | `std::is_heap()` | Checks whether an iterator range is in fact a heap | TODO: documentation link |
Iterator Operators | `std::next()` and `std::prev()` | Copies an iterator and increments or decrements the copy by some value | std::next and 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.
Random Number Generators | Functions within `<random>` | Random number generation algorithms and utilities | Pseudo-random number generation |
Ratio Template Class | `std::ratio<numerator, denominator>` | Provides compile-time rational numbers | std::ratio | Note: These are banned in the google style guide over concerns that they are tied to a more template-heavy interface style.
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) | Reference Wrappers |
Soft Program Exits | `std::at_quick_exit()` and `std::quick_exit()` | Allows registration of functions to be called upon exit, allowing cleaner program exit than `abort()` or `exit` | std:quick_exit |
String Direct Reference Functions | `std::string::front()` and `std::string::back()` | Returns a reference to the front or back of a string | std::basic_string::front and std::basic_string::back |
String to Number Functions | `std::stoi()`, `std::stol()`, `std::stoul()`, `std::stoll`, `std::stoull()`, `std::stof()`, `std::stod()`, `std::stold()`, and `std::to_string()` | Converts strings to numbers | std::stoi, std::stol, std::stoll, std::stoul, std::stoull, and std::stof, std::stod, std::stold |
STL Algorithms | Functions within `<algorithm>`. | Enhancements to the set of STL algorithms | See the Algorithms library for a complete list. |
System Errors | `<system_error>` | Provides a standard system error library | std::system_error |
Trailing Return Types | `auto function declaration -> return_type` | Allows trailing function return value syntax | Declaring functions | Discussion thread
Tuples | `std::tuple` | A fixed-size ordered collection of values of mixed types | std::tuple | Tracking bug to plan moving from `base::Tuple` to `std::tuple`. See also `std::tie`
Type-Generic Math Functions | Functions within `<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` and `std::type_info::hash_code()` | Allows type information (most often within containers) that can be copied, assigned, or hashed | std::type_index and 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
Unique Pointers | `std::unique_ptr<type>` | Defines a pointer with clear and unambiguous ownership | TODO: documentation link | Ownership and Smart Pointers
Unordered Associative Containers | `std::unordered_set`, `std::unordered_map`, `std::unordered_multiset`, and `std::unordered_multimap` | Allows efficient containers of key/value pairs | std::unordered_map and std::unordered_set |
Variadic Copy Macro | `va_copy(va_list dest, va_list src)` | Makes a copy of the variadic function arguments |  |
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`, and `std::codecvt_utf8_utf16` | Converts between string encodings | std::wstring_convert, std::wbuffer_convert, std::codecvt_utf8, std::codecvt_utf16, and std::codecvt_utf8_utf16 | Non-UTF-8 text is banned by the C++ Style Guide. However, may be useful for consuming non-ASCII data.