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 chromium-dev. 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.

Unless otherwise noted, no C++11 library features are allowed.

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.
Automatic Types auto Automatic type deduction TODO: documentation link Use according to the Google Style Guide on auto. 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
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.
Null Pointer Constant nullptr Declares a type-safe null pointer TODO: documentation link Recommended for new code. Discussion thread. Google Style Guide. Note: std::nullptr_t is a library feature and not available.
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 TODO: documentation link 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
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 TODO: documentation link Usage should be rare. Use instead of .pump files. 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
Constant Expressions constexpr Compile-time constant expressions TODO: documentation link 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 TODO: documentation link Causes incorrect line numbers in MSVS2014 and gcc. Reevaluate once that works. Discussion thread
Rvalue References (and Move Semantics) T(T&& t) and T& operator=(T&& t) Reference that only binds to a temporary object TODO: documentation link To be revisited in the future. Allowed in exceptional cases where approved by the OWNERS of src/styleguide/c++/.
(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

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
Alignment Features alignas specifier, std::alignment_of<T>, std::aligned_union<Size, ...Types> and std::max_align_t Object alignment std::alignment_of
Attributes [[attribute_name]] Attaches properties to declarations that specific compiler implementations may use. C++11 generalized attributes
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
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
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
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 TODO: documentation link

C++11 Standard Library features

All C++11 Standard Library features are currently banned, because they are not supported on all of our toolchains yet. In particular, chromium/android is currently using STLport, and chromium/mac is currently using libstdc++4.2, which predate C++11.

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 &s; should suffice in most cases. May be preferable over &s; for performing object identity checks.
Aligned Storage std::aligned_storage<Size, Align>::type Declare uninitialized storage having a specified alignment. std::aligned_storage Note: std::aligned_storage is allowed, but some other C++11 alignment features are still disallowed.
Allocator Traits std::allocator_traits Provides an interface for accessing custom allocators std::allocator_traits Usage should be rare.
Atomics std::atomic and others in <atomic> Fine-grained atomic types and operations <atomic>
Arrays std::array A fixed-size replacement for built-in arrays, with STL support std::array
Begin and End Non-Member Functions std::begin() and std::end() Allows use of free functions on any container, including built-in arrays std::begin and std::end Useful for built-in arrays.
Bind Operations std::bind(function, args, ...) Declares a function object bound to certain arguments TODO: documentation link
C Floating-Point Environment <cfenv> Provides floating point status flags and control modes for C-compatible code Standard library header <cfenv> Compilers do not support use
Chrono Library <chrono> Provides a standard date and time library Date and time utilities
Complex Inverse Trigonometric and Hyperbolic Functions Functions within <complex> Adds inverse trigonomentric and hyperbolic non-member functions to the <complex> library. std::complex
Conditional Type Selection std::enable_if and std::conditional Enables compile-time conditional type selection std::enable_if and conditional
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
Is Nan std::isnan() Determines if a floating point value is not-a-number std::isnan
Iterator Operators std::next() and std::prev() Copies an iterator and increments or decrements the copy by some value std::next and std::prev
Initializer Lists std::initializer_list<T> Allows containers to be initialized with aggregate elements TODO: documentation link
Move Semantics std::move() Facilitates efficient move operations std::move reference
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 TODO: documentation link
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
Regex Library <regex> Provides a standard regular expressions library Regular expressions library
Shared Pointers std::shared_ptr Allows shared ownership of a pointer through reference counts std::shared_ptr Ownership and Smart Pointers
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
Thread Library <thread> support, including <future>, <mutex>, <condition_variable> Provides a standard mulitthreading library using std::thread and associates Thread support library
Tuples std::tuple A fixed-size ordered collection of values of mixed types TODO: documentation link
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
Type Traits Class templates within <type_traits> Allows compile-time inspection of the properties of types Standard library header <type_traits>
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.