# C++11
NOTE: this is a web “mirror” of Anthony Calandra’s modern-cpp-features shared under MIT License (see at bottom). The only reason I do a copy is I hate reading markdowns from github. I want something simple and plain for my own reference.
# Overview
Many of these descriptions and examples are taken from various resources (see Acknowledgements section) and summarized in my own words.
C++11 includes the following new language features:
- move semantics
- variadic templates
- rvalue references
- forwarding references
- initializer lists
- static assertions
- auto
- lambda expressions
- decltype
- type aliases
- nullptr
- strongly-typed enums
- attributes
- constexpr
- delegating constructors
- user-defined literals
- explicit virtual overrides
- final specifier
- default functions
- deleted functions
- range-based for loops
- special member functions for move semantics
- converting constructors
- explicit conversion functions
- inline-namespaces
- non-static data member initializers
- right angle brackets
- ref-qualified member functions
- trailing return types
- noexcept specifier
- char32_t and char16_t
- raw string literals
C++11 includes the following new library features:
- std::move
- std::forward
- std::thread
- std::to_string
- type traits
- smart pointers
- std::chrono
- tuples
- std::tie
- std::array
- unordered containers
- std::make_shared
- std::ref
- memory model
- std::async
- std::begin/end
# C++11 Language Features
# Move semantics
Moving an object means to transfer ownership of some resource it manages to another object.
The first benefit of move semantics is performance optimization. When an object is about to reach the end of its lifetime, either because it’s a temporary or by explicitly calling std::move
, a move is often a cheaper way to transfer resources. For example, moving a std::vector
is just copying some pointers and internal state over to the new vector – copying would involve having to copy every single contained element in the vector, which is expensive and unnecessary if the old vector will soon be destroyed.
Moves also make it possible for non-copyable types such as std::unique_ptr
s (smart pointers) to guarantee at the language level that there is only ever one instance of a resource being managed at a time, while being able to transfer an instance between scopes.
See the sections on: rvalue references, special member functions for move semantics, std::move
, std::forward
, forwarding references
.
# Rvalue references
C++11 introduces a new reference termed the rvalue reference. An rvalue reference to T
, which is a non-template type parameter (such as int
, or a user-defined type), is created with the syntax T&&
. 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 perfect forwarding: the ability to pass arguments while maintaining their value category (e.g. lvalues stay as lvalues, temporaries are forwarded as 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.
|
|
An interesting use for this is creating an initializer list from a parameter pack in order to iterate over variadic function arguments.
|
|
# 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
by reference.[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) (C++14)
.
# Type aliases
Semantically similar to using a typedef
however, type 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 that are possibly evaluated by the compiler at compile-time. Only non-complex computations can be carried out in a constant expression (these rules are progressively relaxed in later versions). Use the constexpr
specifier to indicate the variable, function, etc. is a constant expression.
|
|
In the previous snippet, notice that the computation when calling square
is carried out at compile-time, and then the result is embedded in the code generation, while square2
is called at run-time.
constexpr
values are those that the compiler can evaluate, but are not guaranteed to, 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.
|
|
# Ref-qualified member functions
Member functions can now be qualified depending on whether *this
is an lvalue or rvalue reference.
|
|
# Trailing return types
C++11 allows functions and lambdas an alternative syntax for specifying their return types.
|
|
|
|
This feature is especially useful when certain return types cannot be resolved:
|
|
In C++14, decltype(auto) (C++14)
can be used instead.
# Noexcept specifier
The noexcept
specifier specifies whether a function could throw exceptions. It is an improved version of throw()
.
|
|
Non-throwing functions are permitted to call potentially-throwing functions. Whenever an exception is thrown and the search for a handler encounters the outermost block of a non-throwing function, the function std::terminate is called.
|
|
# char32_t and char16_t
Provides standard types for representing UTF-8 strings.
|
|
# Raw string literals
C++11 introduces a new way to declare string literals as “raw string literals”. Characters issued from an escape sequence (tabs, line feeds, single backslashes, etc.) can be inputted raw while preserving formatting. This is useful, for example, to write literary text, which might contain a lot of quotes or special formatting. This can make your string literals easier to read and maintain.
A raw string literal is declared using the following syntax:
R"delimiter(raw_characters)delimiter"
where:
delimiter
is an optional sequence of characters made of any source character except parentheses, backslashes and spaces.raw_characters
is any raw character sequence; must not contain the closing sequence")delimiter"
.
Example:
|
|
# C++11 Library Features
# std::move
std::move
indicates that the object passed to it may have its resources transferred. Using objects that have been moved from should be used with care, as they can be left in an unspecified state (see: What can I do with a moved-from object?).
A definition of std::move
(performing a move is nothing more than casting to an rvalue reference):
|
|
Transferring std::unique_ptr
s:
|
|
# std::forward
Returns the arguments passed to it while maintaining their value category and cv-qualifiers. Useful for generic code and 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 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 pointer that manages its own heap-allocated memory. 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
.
# std::ref
std::ref(val)
is used to create object of type std::reference_wrapper
that holds reference of val. Used in cases when usual reference passing using &
does not compile or &
is dropped due to type deduction. std::cref
is similar but created reference wrapper holds a const reference to val.
|
|
# 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.
|
|
# std::begin/end
std::begin
and std::end
free functions were added to return begin and end iterators of a container generically. These functions also work with raw arrays which do not have begin
and end
member functions.
|
|
# 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.
- clang and gcc’s standards support pages. Also included here are the proposals for language/library features that I used to help find a description of, what it’s meant to fix, and some examples.
- Compiler explorer
- Scott Meyers’ Effective Modern C++ - highly recommended book!
- Jason Turner’s C++ Weekly - nice collection of C++-related videos.
- What can I do with a moved-from object?
- What are some uses of decltype(auto)?
- And many more SO posts I’m forgetting…
# COPYING & ATTRIBUTIONS:
Author Anthony Calandra
Content Contributors
See: https://github.com/AnthonyCalandra/modern-cpp-features/graphs/contributors
License: The MIT License (MIT) Copyright (c) 2024 Anthony Calandra
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.