Overview
C++17/14/11
Overview
Many of these descriptions and examples come from various resources (see Acknowledgements section), summarized in my own words.
Also, there are now dedicated readme pages for each major C++ version.
C++17 includes the following new language features:
C++17 includes the following new library features:
C++14 includes the following new language features:
C++14 includes the following new library features:
C++11 includes the following new language features:
C++11 includes the following new library features:
C++17 Language Features
Template argument deduction for class templates
Automatic template argument deduction much like how it's done for functions, but now including class constructors.
Declaring non-type template parameters with auto
Following the deduction rules of auto
, while respecting the non-type template parameter list of allowable types[*], template arguments can be deduced from the types of its arguments:
* - For example, you cannot use a double
as a template parameter type, which also makes this an invalid deduction using auto
.
Folding expressions
A fold expression performs a fold of a template parameter pack over a binary operator.
An expression of the form
(... op e)
or(e op ...)
, whereop
is a fold-operator ande
is an unexpanded parameter pack, are called unary folds.An expression of the form
(e1 op ... op e2)
, whereop
are fold-operators, is called a binary fold. Eithere1
ore2
is an unexpanded parameter pack, but not both.
New rules for auto deduction from braced-init-list
Changes to auto
deduction when used with the uniform initialization syntax. Previously, auto x {3};
deduces a std::initializer_list<int>
, which now deduces to int
.
constexpr lambda
Compile-time lambdas using constexpr
.
Lambda capture this
by value
this
by valueCapturing this
in a lambda's environment was previously reference-only. An example of where this is problematic is asynchronous code using callbacks that require an object to be available, potentially past its lifetime. *this
(C++17) will now make a copy of the current object, while this
(C++11) continues to capture by reference.
Inline variables
The inline specifier can be applied to variables as well as to functions. A variable declared inline has the same semantics as a function declared inline.
Nested namespaces
Using the namespace resolution operator to create nested namespace definitions.
Structured bindings
A proposal for de-structuring initialization, that would allow writing auto [ x, y, z ] = expr;
where the type of expr
was a tuple-like object, whose elements would be bound to the variables x
, y
, and z
(which this construct declares). Tuple-like objects include std::tuple
, std::pair
, std::array
, and aggregate structures.
Selection statements with initializer
New versions of the if
and switch
statements which simplify common code patterns and help users keep scopes tight.
constexpr if
Write code that is instantiated depending on a compile-time condition.
UTF-8 Character Literals
A character literal that begins with u8
is a character literal of type char
. The value of a UTF-8 character literal is equal to its ISO 10646 code point value.
Direct List Initialization of Enums
Enums can now be initialized using braced syntax.
C++17 Library Features
std::variant
The class template std::variant
represents a type-safe union
. An instance of std::variant
at any given time holds a value of one of its alternative types (it's also possible for it to be valueless).
std::optional
The class template std::optional
manages an optional contained value, i.e. a value that may or may not be present. A common use case for optional is the return value of a function that may fail.
std::any
A type-safe container for single values of any type.
std::string_view
A non-owning reference to a string. Useful for providing an abstraction on top of strings (e.g. for parsing).
std::invoke
Invoke a Callable
object with parameters. Examples of Callable
objects are std::function
or std::bind
where an object can be called similarly to a regular function.
std::apply
Invoke a Callable
object with a tuple of arguments.
std::filesystem
The new std::filesystem
library provides a standard way to manipulate files, directories, and paths in a filesystem.
Here, a big file is copied to a temporary path if there is available space:
std::byte
The new std::byte
type provides a standard way of representing data as a byte. Benefits of using std::byte
over char
or unsigned char
is that it is not a character type, and is also not an arithmetic type; while the only operator overloads available are bitwise operations.
Note that std::byte
is simply an enum, and braced initialization of enums become possible thanks to direct-list-initialization of enums.
Splicing for maps and sets
Moving nodes and merging containers without the overhead of expensive copies, moves, or heap allocations/deallocations.
Moving elements from one map to another:
Inserting an entire set:
Inserting elements which outlive the container:
Changing the key of a map element:
Parallel algorithms
Many of the STL algorithms, such as the copy
, find
and sort
methods, started to support the parallel execution policies: seq
, par
and par_unseq
which translate to "sequentially", "parallel" and "parallel unsequenced".
C++14 Language Features
Binary literals
Binary literals provide a convenient way to represent a base-2 number. It is possible to separate digits with '
.
Generic lambda expressions
C++14 now allows the auto
type-specifier in the parameter list, enabling polymorphic lambdas.
Lambda capture initializers
This allows creating lambda captures initialized with arbitrary expressions. The name given to the captured value does not need to be related to any variables in the enclosing scopes and introduces a new name inside the lambda body. The initializing expression is evaluated when the lambda is created (not when it is invoked).
Because it is now possible to move (or forward) values into a lambda that could previously be only captured by copy or reference we can now capture move-only types in a lambda by value. Note that in the below example the p
in the capture-list of task2
on the left-hand-side of =
is a new variable private to the lambda body and does not refer to the original p
.
Using this reference-captures can have different names than the referenced variable.
Return type deduction
Using an auto
return type in C++14, the compiler will attempt to deduce the type for you. With lambdas, you can now deduce its return type using auto
, which makes returning a deduced reference or rvalue reference possible.
decltype(auto)
The decltype(auto)
type-specifier also deduces a type like auto
does. However, it deduces return types while keeping their references and cv-qualifiers, while auto
will not.
See also: decltype
.
Relaxing constraints on constexpr functions
In C++11, constexpr
function bodies could only contain a very limited set of syntaxes, including (but not limited to): typedef
s, using
s, and a single return
statement. In C++14, the set of allowable syntaxes expands greatly to include the most common syntax such as if
statements, multiple return
s, loops, etc.
Variable Templates
C++14 allows variables to be templated:
C++14 Library Features
User-defined literals for standard library types
New user-defined literals for standard library types, including new built-in literals for chrono
and basic_string
. These can be constexpr
meaning they can be used at compile-time. Some uses for these literals include compile-time integer parsing, binary literals, and imaginary number literals.
Compile-time integer sequences
The class template std::integer_sequence
represents a compile-time sequence of integers. There are a few helpers built on top:
std::make_integer_sequence<T, N...>
- creates a sequence of0, ..., N - 1
with typeT
.std::index_sequence_for<T...>
- converts a template parameter pack into an integer sequence.
Convert an array into a tuple:
std::make_unique
std::make_unique
is the recommended way to create instances of std::unique_ptr
s due to the following reasons:
Avoid having to use the
new
operator.Prevents code repetition when specifying the underlying type the pointer shall hold.
Most importantly, it provides exception-safety. Suppose we were calling a function
foo
like so:
The compiler is free to call new T{}
, then function_that_throws()
, and so on... Since we have allocated data on the heap in the first construction of a T
, we have introduced a leak here. With std::make_unique
, we are given exception-safety:
See the section on smart pointers for more information on std::unique_ptr
and std::shared_ptr
.
C++11 Language Features
Move semantics
Move semantics is mostly about performance optimization: the ability to move an object without the expensive overhead of copying. The difference between a copy and a move is that a copy leaves the source unchanged, and a move will leave the source either unchanged or radically different -- depending on what the source is. For plain old data, a move is the same as a copy.
To move an object means to transfer ownership of some resource it manages to another object. You could think of this as changing pointers held by the source object to be moved, or now held, by the destination object; the resource remains in its location in memory. Such an inexpensive transfer of resources is extremely useful when the source is an rvalue
, where the potentially dangerous side-effect of changing the source after the move is redundant since the source is a temporary object that won't be accessible later.
Moves also make it possible to transfer objects such as std::unique_ptr
s, smart pointers that are designed to hold a pointer to a unique object, from one scope to another.
See the sections on: rvalue references, defining move special member functions, std::move
, std::forward
, forwarding references
.
Rvalue references
C++11 introduces a new reference termed the rvalue reference. An rvalue reference to A
, which is a non-template type parameter (such as int
, or a user-defined type), is created with the syntax A&&
. Rvalue references only bind to rvalues.
Type deduction with lvalues and rvalues:
See also: std::move
, std::forward
, forwarding references
.
Forwarding references
Also known (unofficially) as universal references. A forwarding reference is created with the syntax T&&
where T
is a template type parameter, or using auto&&
. This enables two major features: move semantics; and perfect forwarding, the ability to pass arguments that are either lvalues or rvalues.
Forwarding references allow a reference to bind to either an lvalue or rvalue depending on the type. Forwarding references follow the rules of reference collapsing:
T& &
becomesT&
T& &&
becomesT&
T&& &
becomesT&
T&& &&
becomesT&&
auto
type deduction with lvalues and rvalues:
Template type parameter deduction with lvalues and rvalues:
See also: std::move
, std::forward
, rvalue references
.
Variadic templates
The ...
syntax creates a parameter pack or expands one. A template parameter pack is a template parameter that accepts zero or more template arguments (non-types, types, or templates). A template with at least one parameter pack is called a variadic template.
Initializer lists
A lightweight array-like container of elements created using a "braced list" syntax. For example, { 1, 2, 3 }
creates a sequences of integers, that has type std::initializer_list<int>
. Useful as a replacement to passing a vector of objects to a function.
Static assertions
Assertions that are evaluated at compile-time.
auto
auto
-typed variables are deduced by the compiler according to the type of their initializer.
Extremely useful for readability, especially for complicated types:
Functions can also deduce the return type using auto
. In C++11, a return type must be specified either explicitly, or using decltype
like so:
The trailing return type in the above example is the declared type (see section on decltype
) of the expression x + y
. For example, if x
is an integer and y
is a double, decltype(x + y)
is a double. Therefore, the above function will deduce the type depending on what type the expression x + y
yields. Notice that the trailing return type has access to its parameters, and this
when appropriate.
Lambda expressions
A lambda
is an unnamed function object capable of capturing variables in scope. It features: a capture list; an optional set of parameters with an optional trailing return type; and a body. Examples of capture lists:
[]
- captures nothing.[=]
- capture local objects (local variables, parameters) in scope by value.[&]
- capture local objects (local variables, parameters) in scope by reference.[this]
- capturethis
pointer by value.[a, &b]
- capture objectsa
by value,b
by reference.
By default, value-captures cannot be modified inside the lambda because the compiler-generated method is marked as const
. The mutable
keyword allows modifying captured variables. The keyword is placed after the parameter-list (which must be present even if it is empty).
decltype
decltype
is an operator which returns the declared type of an expression passed to it. cv-qualifiers and references are maintained if they are part of the expression. Examples of decltype
:
See also: decltype(auto)
.
Template aliases
Semantically similar to using a typedef
however, template aliases with using
are easier to read and are compatible with templates.
nullptr
C++11 introduces a new null pointer type designed to replace C's NULL
macro. nullptr
itself is of type std::nullptr_t
and can be implicitly converted into pointer types, and unlike NULL
, not convertible to integral types except bool
.
Strongly-typed enums
Type-safe enums that solve a variety of problems with C-style enums including: implicit conversions, inability to specify the underlying type, scope pollution.
Attributes
Attributes provide a universal syntax over __attribute__(...)
, __declspec
, etc.
constexpr
Constant expressions are expressions evaluated by the compiler at compile-time. Only non-complex computations can be carried out in a constant expression. Use the constexpr
specifier to indicate the variable, function, etc. is a constant expression.
constexpr
values are those that the compiler can evaluate at compile-time:
Constant expressions with classes:
Delegating constructors
Constructors can now call other constructors in the same class using an initializer list.
User-defined literals
User-defined literals allow you to extend the language and add your own syntax. To create a literal, define a T operator "" X(...) { ... }
function that returns a type T
, with a name X
. Note that the name of this function defines the name of the literal. Any literal names not starting with an underscore are reserved and won't be invoked. There are rules on what parameters a user-defined literal function should accept, according to what type the literal is called on.
Converting Celsius to Fahrenheit:
String to integer conversion:
Explicit virtual overrides
Specifies that a virtual function overrides another virtual function. If the virtual function does not override a parent's virtual function, throws a compiler error.
Final specifier
Specifies that a virtual function cannot be overridden in a derived class or that a class cannot be inherited from.
Class cannot be inherited from.
Default functions
A more elegant, efficient way to provide a default implementation of a function, such as a constructor.
With inheritance:
Deleted functions
A more elegant, efficient way to provide a deleted implementation of a function. Useful for preventing copies on objects.
Range-based for loops
Syntactic sugar for iterating over a container's elements.
Note the difference when using int
as opposed to int&
:
Special member functions for move semantics
The copy constructor and copy assignment operator are called when copies are made, and with C++11's introduction of move semantics, there is now a move constructor and move assignment operator for moves.
Converting constructors
Converting constructors will convert values of braced list syntax into constructor arguments.
Note that the braced list syntax does not allow narrowing:
Note that if a constructor accepts a std::initializer_list
, it will be called instead:
Explicit conversion functions
Conversion functions can now be made explicit using the explicit
specifier.
Inline namespaces
All members of an inline namespace are treated as if they were part of its parent namespace, allowing specialization of functions and easing the process of versioning. This is a transitive property, if A contains B, which in turn contains C and both B and C are inline namespaces, C's members can be used as if they were on A.
Non-static data member initializers
Allows non-static data members to be initialized where they are declared, potentially cleaning up constructors of default initializations.
Right angle Brackets
C++11 is now able to infer when a series of right angle brackets is used as an operator or as a closing statement of typedef, without having to add whitespace.
C++11 Library Features
std::move
std::move
indicates that the object passed to it may be moved, or in other words, moved from one object to another without a copy. The object passed in should not be used after the move in certain situations.
A definition of std::move
(performing a move is nothing more than casting to an rvalue):
Transferring std::unique_ptr
s:
std::forward
Returns the arguments passed to it as-is, either as an lvalue or rvalue references, and includes cv-qualification. Useful for generic code that need a reference (either lvalue or rvalue) when appropriate, e.g factories. Used in conjunction with forwarding references
.
A definition of std::forward
:
An example of a function wrapper
which just forwards other A
objects to a new A
object's copy or move constructor:
See also: forwarding references
, rvalue references
.
std::thread
The std::thread
library provides a standard way to control threads, such as spawning and killing them. In the example below, multiple threads are spawned to do different calculations and then the program waits for all of them to finish.
std::to_string
Converts a numeric argument to a std::string
.
Type traits
Type traits defines a compile-time template-based interface to query or modify the properties of types.
Smart pointers
C++11 introduces new smart(er) pointers: std::unique_ptr
, std::shared_ptr
, std::weak_ptr
. std::auto_ptr
now becomes deprecated and then eventually removed in C++17.
std::unique_ptr
is a non-copyable, movable smart pointer that properly manages arrays and STL containers. Note: Prefer using the std::make_X
helper functions as opposed to using constructors. See the sections for std::make_unique and std::make_shared.
A std::shared_ptr
is a smart pointer that manages a resource that is shared across multiple owners. A shared pointer holds a control block which has a few components such as the managed object and a reference counter. All control block access is thread-safe, however, manipulating the managed object itself is not thread-safe.
std::chrono
The chrono library contains a set of utility functions and types that deal with durations, clocks, and time points. One use case of this library is benchmarking code:
Tuples
Tuples are a fixed-size collection of heterogeneous values. Access the elements of a std::tuple
by unpacking using std::tie
, or using std::get
.
std::tie
Creates a tuple of lvalue references. Useful for unpacking std::pair
and std::tuple
objects. Use std::ignore
as a placeholder for ignored values. In C++17, structured bindings should be used instead.
std::array
std::array
is a container built on top of a C-style array. Supports common container operations such as sorting.
Unordered containers
These containers maintain average constant-time complexity for search, insert, and remove operations. In order to achieve constant-time complexity, sacrifices order for speed by hashing elements into buckets. There are four unordered containers:
unordered_set
unordered_multiset
unordered_map
unordered_multimap
std::make_shared
std::make_shared
is the recommended way to create instances of std::shared_ptr
s due to the following reasons:
Avoid having to use the
new
operator.Prevents code repetition when specifying the underlying type the pointer shall hold.
It provides exception-safety. Suppose we were calling a function
foo
like so:
The compiler is free to call new T{}
, then function_that_throws()
, and so on... Since we have allocated data on the heap in the first construction of a T
, we have introduced a leak here. With std::make_shared
, we are given exception-safety:
Prevents having to do two allocations. When calling
std::shared_ptr{ new T{} }
, we have to allocate memory forT
, then in the shared pointer we have to allocate memory for the control block within the pointer.
See the section on smart pointers for more information on std::unique_ptr
and std::shared_ptr
.
Memory model
C++11 introduces a memory model for C++, which means library support for threading and atomic operations. Some of these operations include (but aren't limited to) atomic loads/stores, compare-and-swap, atomic flags, promises, futures, locks, and condition variables.
See the sections on: std::thread
std::async
std::async
runs the given function either asynchronously or lazily-evaluated, then returns a std::future
which holds the result of that function call.
The first parameter is the policy which can be:
std::launch::async | std::launch::deferred
It is up to the implementation whether to perform asynchronous execution or lazy evaluation.std::launch::async
Run the callable object on a new thread.std::launch::deferred
Perform lazy evaluation on the current thread.
Acknowledgements
cppreference - especially useful for finding examples and documentation of new library features.
C++ Rvalue References Explained - a great introduction I used to understand rvalue references, perfect forwarding, and move semantics.
Scott Meyers' Effective Modern C++ - highly recommended book!
Jason Turner's C++ Weekly - nice collection of C++-related videos.
And many more SO posts I'm forgetting...
Last updated