当前位置:   article > 正文

C++11 14 17 20

C++11 14 17 20

C++20 Language Features

Coroutines

Coroutines are special functions that can have their execution suspended and resumed. To define a coroutine, the co_returnco_await, or co_yield keywords must be present in the function's body. C++20's coroutines are stackless; unless optimized out by the compiler, their state is allocated on the heap.

An example of a coroutine is a generator function, which yields (i.e. generates) a value at each invocation:

  1. generator<int> range(int start, int end) {
  2. while (start < end) {
  3. co_yield start;
  4. start++;
  5. }
  6. // Implicit co_return at the end of this function:
  7. // co_return;
  8. }
  9. for (int n : range(0, 10)) {
  10. std::cout << n << std::endl;
  11. }

The above range generator function generates values starting at start until end (exclusive), with each iteration step yielding the current value stored in start. The generator maintains its state across each invocation of range (in this case, the invocation is for each iteration in the for loop). co_yield takes the given expression, yields (i.e. returns) its value, and suspends the coroutine at that point. Upon resuming, execution continues after the co_yield.

Another example of a coroutine is a task, which is an asynchronous computation that is executed when the task is awaited:

  1. task<void> echo(socket s) {
  2. for (;;) {
  3. auto data = co_await s.async_read();
  4. co_await async_write(s, data);
  5. }
  6. // Implicit co_return at the end of this function:
  7. // co_return;
  8. }

In this example, the co_await keyword is introduced. This keyword takes an expression and suspends execution if the thing you're awaiting on (in this case, the read or write) is not ready, otherwise you continue execution. (Note that under the hood, co_yield uses co_await.)

Using a task to lazily evaluate a value:

  1. task<int> calculate_meaning_of_life() {
  2. co_return 42;
  3. }
  4. auto meaning_of_life = calculate_meaning_of_life();
  5. // ...
  6. co_await meaning_of_life; // == 42

Note: While these examples illustrate how to use coroutines at a basic level, there is lots more going on when the code is compiled. These examples are not meant to be complete coverage of C++20's coroutines. Since the generator and task classes are not provided by the standard library yet, I used the cppcoro library to compile these examples.

Concepts

Concepts are named compile-time predicates which constrain types. They take the following form:

  1. template < template-parameter-list >
  2. concept concept-name = constraint-expression;

where constraint-expression evaluates to a constexpr Boolean. Constraints should model semantic requirements, such as whether a type is a numeric or hashable. A compiler error results if a given type does not satisfy the concept it's bound by (i.e. constraint-expression returns false). Because constraints are evaluated at compile-time, they can provide more meaningful error messages and runtime safety.

  1. // `T` is not limited by any constraints.
  2. template <typename T>
  3. concept always_satisfied = true;
  4. // Limit `T` to integrals.
  5. template <typename T>
  6. concept integral = std::is_integral_v<T>;
  7. // Limit `T` to both the `integral` constraint and signedness.
  8. template <typename T>
  9. concept signed_integral = integral<T> && std::is_signed_v<T>;
  10. // Limit `T` to both the `integral` constraint and the negation of the `signed_integral` constraint.
  11. template <typename T>
  12. concept unsigned_integral = integral<T> && !signed_integral<T>;

There are a variety of syntactic forms for enforcing concepts:

  1. // Forms for function parameters:
  2. // `T` is a constrained type template parameter.
  3. template <my_concept T>
  4. void f(T v);
  5. // `T` is a constrained type template parameter.
  6. template <typename T>
  7. requires my_concept<T>
  8. void f(T v);
  9. // `T` is a constrained type template parameter.
  10. template <typename T>
  11. void f(T v) requires my_concept<T>;
  12. // `v` is a constrained deduced parameter.
  13. void f(my_concept auto v);
  14. // `v` is a constrained non-type template parameter.
  15. template <my_concept auto v>
  16. void g();
  17. // Forms for auto-deduced variables:
  18. // `foo` is a constrained auto-deduced value.
  19. my_concept auto foo = ...;
  20. // Forms for lambdas:
  21. // `T` is a constrained type template parameter.
  22. auto f = []<my_concept T> (T v) {
  23. // ...
  24. };
  25. // `T` is a constrained type template parameter.
  26. auto f = []<typename T> requires my_concept<T> (T v) {
  27. // ...
  28. };
  29. // `T` is a constrained type template parameter.
  30. auto f = []<typename T> (T v) requires my_concept<T> {
  31. // ...
  32. };
  33. // `v` is a constrained deduced parameter.
  34. auto f = [](my_concept auto v) {
  35. // ...
  36. };
  37. // `v` is a constrained non-type template parameter.
  38. auto g = []<my_concept auto v> () {
  39. // ...
  40. };

The requires keyword is used either to start a requires clause or a requires expression:

  1. template <typename T>
  2. requires my_concept<T> // `requires` clause.
  3. void f(T);
  4. template <typename T>
  5. concept callable = requires (T f) { f(); }; // `requires` expression.
  6. template <typename T>
  7. requires requires (T x) { x + x; } // `requires` clause and expression on same line.
  8. T add(T a, T b) {
  9. return a + b;
  10. }

Note that the parameter list in a requires expression is optional. Each requirement in a requires expression are one of the following:

  • Simple requirements - asserts that the given expression is valid.
  1. template <typename T>
  2. concept callable = requires (T f) { f(); };
  • Type requirements - denoted by the typename keyword followed by a type name, asserts that the given type name is valid.
  1. struct foo {
  2. int foo;
  3. };
  4. struct bar {
  5. using value = int;
  6. value data;
  7. };
  8. struct baz {
  9. using value = int;
  10. value data;
  11. };
  12. // Using SFINAE, enable if `T` is a `baz`.
  13. template <typename T, typename = std::enable_if_t<std::is_same_v<T, baz>>>
  14. struct S {};
  15. template <typename T>
  16. using Ref = T&;
  17. template <typename T>
  18. concept C = requires {
  19. // Requirements on type `T`:
  20. typename T::value; // A) has an inner member named `value`
  21. typename S<T>; // B) must have a valid class template specialization for `S`
  22. typename Ref<T>; // C) must be a valid alias template substitution
  23. };
  24. template <C T>
  25. void g(T a);
  26. g(foo{}); // ERROR: Fails requirement A.
  27. g(bar{}); // ERROR: Fails requirement B.
  28. g(baz{}); // PASS.
  • Compound requirements - an expression in braces followed by a trailing return type or type constraint.
  1. template <typename T>
  2. concept C = requires(T x) {
  3. {*x} -> std::convertible_to<typename T::inner>; // the type of the expression `*x` is convertible to `T::inner`
  4. {x + 1} -> std::same_as<int>; // the expression `x + 1` satisfies `std::same_as<decltype((x + 1))>`
  5. {x * 1} -> std::convertible_to<T>; // the type of the expression `x * 1` is convertible to `T`
  6. };
  • Nested requirements - denoted by the requires keyword, specify additional constraints (such as those on local parameter arguments).
  1. template <typename T>
  2. concept C = requires(T x) {
  3. requires std::same_as<sizeof(x), size_t>;
  4. };

See also: concepts library.

Designated initializers

C-style designated initializer syntax. Any member fields that are not explicitly listed in the designated initializer list are default-initialized.

  1. struct A {
  2. int x;
  3. int y;
  4. int z = 123;
  5. };
  6. A a {.x = 1, .z = 2}; // a.x == 1, a.y == 0, a.z == 2

Template syntax for lambdas

Use familiar template syntax in lambda expressions.

  1. auto f = []<typename T>(std::vector<T> v) {
  2. // ...
  3. };

Range-based for loop with initializer

This feature simplifies common code patterns, helps keep scopes tight, and offers an elegant solution to a common lifetime problem.

  1. for (auto v = std::vector{1, 2, 3}; auto& e : v) {
  2. std::cout << e;
  3. }
  4. // prints "123"

[[likely]] and [[unlikely]] attributes

Provides a hint to the optimizer that the labelled statement has a high probability of being executed.

  1. switch (n) {
  2. case 1:
  3. // ...
  4. break;
  5. [[likely]] case 2: // n == 2 is considered to be arbitrarily more
  6. // ... // likely than any other value of n
  7. break;
  8. }

If one of the likely/unlikely attributes appears after the right parenthesis of an if-statement,
it indicates that the branch is likely/unlikely to have its substatement (body) executed.

  1. int random = get_random_number_between_x_and_y(0, 3);
  2. if (random > 0) [[likely]] {
  3. // body of if statement
  4. // ...
  5. }

It can also be applied to the substatement (body) of an iteration statement.

  1. while (unlikely_truthy_condition) [[unlikely]] {
  2. // body of while statement
  3. // ...
  4. }

Deprecate implicit capture of this

Implicitly capturing this in a lambda capture using [=] is now deprecated; prefer capturing explicitly using [=, this] or [=, *this].

  1. struct int_value {
  2. int n = 0;
  3. auto getter_fn() {
  4. // BAD:
  5. // return [=]() { return n; };
  6. // GOOD:
  7. return [=, *this]() { return n; };
  8. }
  9. };

Class types in non-type template parameters

Classes can now be used in non-type template parameters. Objects passed in as template arguments have the type const T, where T is the type of the object, and has static storage duration.

  1. struct foo {
  2. foo() = default;
  3. constexpr foo(int) {}
  4. };
  5. template <foo f>
  6. auto get_foo() {
  7. return f;
  8. }
  9. get_foo(); // uses implicit constructor
  10. get_foo<foo{123}>();

constexpr virtual functions

Virtual functions can now be constexpr and evaluated at compile-time. constexpr virtual functions can override non-constexpr virtual functions and vice-versa.

  1. struct X1 {
  2. virtual int f() const = 0;
  3. };
  4. struct X2: public X1 {
  5. constexpr virtual int f() const { return 2; }
  6. };
  7. struct X3: public X2 {
  8. virtual int f() const { return 3; }
  9. };
  10. struct X4: public X3 {
  11. constexpr virtual int f() const { return 4; }
  12. };
  13. constexpr X4 x4;
  14. x4.f(); // == 4

explicit(bool)

Conditionally select at compile-time whether a constructor is made explicit or not. explicit(true) is the same as specifying explicit.

  1. struct foo {
  2. // Specify non-integral types (strings, floats, etc.) require explicit construction.
  3. template <typename T>
  4. explicit(!std::is_integral_v<T>) foo(T) {}
  5. };
  6. foo a = 123; // OK
  7. foo b = "123"; // ERROR: explicit constructor is not a candidate (explicit specifier evaluates to true)
  8. foo c {"123"}; // OK

Immediate functions

Similar to constexpr functions, but functions with a consteval specifier must produce a constant. These are called immediate functions.

  1. consteval int sqr(int n) {
  2. return n * n;
  3. }
  4. constexpr int r = sqr(100); // OK
  5. int x = 100;
  6. int r2 = sqr(x); // ERROR: the value of 'x' is not usable in a constant expression
  7. // OK if `sqr` were a `constexpr` function

using enum

Bring an enum's members into scope to improve readability. Before:

  1. enum class rgba_color_channel { red, green, blue, alpha };
  2. std::string_view to_string(rgba_color_channel channel) {
  3. switch (channel) {
  4. case rgba_color_channel::red: return "red";
  5. case rgba_color_channel::green: return "green";
  6. case rgba_color_channel::blue: return "blue";
  7. case rgba_color_channel::alpha: return "alpha";
  8. }
  9. }

After:

  1. enum class rgba_color_channel { red, green, blue, alpha };
  2. std::string_view to_string(rgba_color_channel my_channel) {
  3. switch (my_channel) {
  4. using enum rgba_color_channel;
  5. case red: return "red";
  6. case green: return "green";
  7. case blue: return "blue";
  8. case alpha: return "alpha";
  9. }
  10. }

Lambda capture of parameter pack

Capture parameter packs by value:

  1. template <typename... Args>
  2. auto f(Args&&... args){
  3. // BY VALUE:
  4. return [...args = std::forward<Args>(args)] {
  5. // ...
  6. };
  7. }

Capture parameter packs by reference:

  1. template <typename... Args>
  2. auto f(Args&&... args){
  3. // BY REFERENCE:
  4. return [&...args = std::forward<Args>(args)] {
  5. // ...
  6. };
  7. }

char8_t

Provides a standard type for representing UTF-8 strings.

char8_t utf8_str[] = u8"\u0123";

constinit

The constinit specifier requires that a variable must be initialized at compile-time.

  1. const char* g() { return "dynamic initialization"; }
  2. constexpr const char* f(bool p) { return p ? "constant initializer" : g(); }
  3. constinit const char* c = f(true); // OK
  4. constinit const char* d = f(false); // ERROR: `g` is not constexpr, so `d` cannot be evaluated at compile-time.

C++20 Library Features

Concepts library

Concepts are also provided by the standard library for building more complicated concepts. Some of these include:

Core language concepts:

  • same_as - specifies two types are the same.
  • derived_from - specifies that a type is derived from another type.
  • convertible_to - specifies that a type is implicitly convertible to another type.
  • common_with - specifies that two types share a common type.
  • integral - specifies that a type is an integral type.
  • default_constructible - specifies that an object of a type can be default-constructed.

Comparison concepts:

  • boolean - specifies that a type can be used in Boolean contexts.
  • equality_comparable - specifies that operator== is an equivalence relation.

Object concepts:

  • movable - specifies that an object of a type can be moved and swapped.
  • copyable - specifies that an object of a type can be copied, moved, and swapped.
  • semiregular - specifies that an object of a type can be copied, moved, swapped, and default constructed.
  • regular - specifies that a type is regular, that is, it is both semiregular and equality_comparable.

Callable concepts:

  • invocable - specifies that a callable type can be invoked with a given set of argument types.
  • predicate - specifies that a callable type is a Boolean predicate.

See also: concepts.

Synchronized buffered outputstream

Buffers output operations for the wrapped output stream ensuring synchronization (i.e. no interleaving of output).

std::osyncstream{std::cout} << "The value of x is:" << x << std::endl;

std::span

A span is a view (i.e. non-owning) of a container providing bounds-checked access to a contiguous group of elements. Since views do not own their elements they are cheap to construct and copy -- a simplified way to think about views is they are holding references to their data. As opposed to maintaining a pointer/iterator and length field, a span wraps both of those up in a single object.

Spans can be dynamically-sized or fixed-sized (known as their extent). Fixed-sized spans benefit from bounds-checking.

Span doesn't propogate const so to construct a read-only span use std::span<const T>.

Example: using a dynamically-sized span to print integers from various containers.

  1. void print_ints(std::span<const int> ints) {
  2. for (const auto n : ints) {
  3. std::cout << n << std::endl;
  4. }
  5. }
  6. print_ints(std::vector{ 1, 2, 3 });
  7. print_ints(std::array<int, 5>{ 1, 2, 3, 4, 5 });
  8. int a[10] = { 0 };
  9. print_ints(a);
  10. // etc.

Example: a statically-sized span will fail to compile for containers that don't match the extent of the span.

  1. void print_three_ints(std::span<const int, 3> ints) {
  2. for (const auto n : ints) {
  3. std::cout << n << std::endl;
  4. }
  5. }
  6. print_three_ints(std::vector{ 1, 2, 3 }); // ERROR
  7. print_three_ints(std::array<int, 5>{ 1, 2, 3, 4, 5 }); // ERROR
  8. int a[10] = { 0 };
  9. print_three_ints(a); // ERROR
  10. std::array<int, 3> b = { 1, 2, 3 };
  11. print_three_ints(b); // OK
  12. // You can construct a span manually if required:
  13. std::vector c{ 1, 2, 3 };
  14. print_three_ints(std::span<const int, 3>{ c.data(), 3 }); // OK: set pointer and length field.
  15. print_three_ints(std::span<const int, 3>{ c.cbegin(), c.cend() }); // OK: use iterator pairs.

Bit operations

C++20 provides a new <bit> header which provides some bit operations including popcount.

  1. std::popcount(0u); // 0
  2. std::popcount(1u); // 1
  3. std::popcount(0b1111'0000u); // 4

Math constants

Mathematical constants including PI, Euler's number, etc. defined in the <numbers> header.

  1. std::numbers::pi; // 3.14159...
  2. std::numbers::e; // 2.71828...

std::is_constant_evaluated

Predicate function which is truthy when it is called in a compile-time context.

  1. constexpr bool is_compile_time() {
  2. return std::is_constant_evaluated();
  3. }
  4. constexpr bool a = is_compile_time(); // true
  5. bool b = is_compile_time(); // false

std::make_shared supports arrays

  1. auto p = std::make_shared<int[]>(5); // pointer to `int[5]`
  2. // OR
  3. auto p = std::make_shared<int[5]>(); // pointer to `int[5]`

starts_with and ends_with on strings

Strings (and string views) now have the starts_with and ends_with member functions to check if a string starts or ends with the given string.

  1. std::string str = "foobar";
  2. str.starts_with("foo"); // true
  3. str.ends_with("baz"); // false

Check if associative container has element

Associative containers such as sets and maps have a contains member function, which can be used instead of the "find and check end of iterator" idiom.

  1. std::map<int, char> map {{1, 'a'}, {2, 'b'}};
  2. map.contains(2); // true
  3. map.contains(123); // false
  4. std::set<int> set {1, 2, 3};
  5. set.contains(2); // true

std::bit_cast

A safer way to reinterpret an object from one type to another.

  1. float f = 123.0;
  2. int i = std::bit_cast<int>(f);

std::midpoint

Calculate the midpoint of two integers safely (without overflow).

std::midpoint(1, 3); // == 2

std::to_array

Converts the given array/"array-like" object to a std::array.

  1. std::to_array("foo"); // returns `std::array<char, 4>`
  2. std::to_array<int>({1, 2, 3}); // returns `std::array<int, 3>`
  3. int a[] = {1, 2, 3};
  4. std::to_array(a); // returns `std::array<int, 3>`

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.

  1. template <typename T = float>
  2. struct MyContainer {
  3. T val;
  4. MyContainer() : val{} {}
  5. MyContainer(T val) : val{val} {}
  6. // ...
  7. };
  8. MyContainer c1 {1}; // OK MyContainer<int>
  9. MyContainer c2; // OK MyContainer<float>

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:

  1. template <auto... seq>
  2. struct my_integer_sequence {
  3. // Implementation here ...
  4. };
  5. // Explicitly pass type `int` as template argument.
  6. auto seq = std::integer_sequence<int, 0, 1, 2>();
  7. // Type is deduced to be `int`.
  8. auto seq2 = my_integer_sequence<0, 1, 2>();

* - 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 ...), where op is a fold-operator and e is an unexpanded parameter pack, are called unary folds.
  • An expression of the form (e1 op ... op e2), where op are fold-operators, is called a binary fold. Either e1 or e2 is an unexpanded parameter pack, but not both.
  1. template <typename... Args>
  2. bool logicalAnd(Args... args) {
  3. // Binary folding.
  4. return (true && ... && args);
  5. }
  6. bool b = true;
  7. bool& b2 = b;
  8. logicalAnd(b, b2, true); // == true
  1. template <typename... Args>
  2. auto sum(Args... args) {
  3. // Unary folding.
  4. return (... + args);
  5. }
  6. sum(1.0, 2.0f, 3); // == 6.0

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.

  1. auto x1 {1, 2, 3}; // error: not a single element
  2. auto x2 = {1, 2, 3}; // x2 is std::initializer_list<int>
  3. auto x3 {3}; // x3 is int
  4. auto x4 {3.0}; // x4 is double

constexpr lambda

Compile-time lambdas using constexpr.

  1. auto identity = [](int n) constexpr { return n; };
  2. static_assert(identity(123) == 123);
  1. constexpr auto add = [](int x, int y) {
  2. auto L = [=] { return x; };
  3. auto R = [=] { return y; };
  4. return [=] { return L() + R(); };
  5. };
  6. static_assert(add(1, 2)() == 3);
  1. constexpr int addOne(int n) {
  2. return [n] { return n + 1; }();
  3. }
  4. static_assert(addOne(1) == 2);

Lambda capture this by value

Capturing 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.

  1. struct MyObj {
  2. int value {123};
  3. auto getValueCopy() {
  4. return [*this] { return value; };
  5. }
  6. auto getValueRef() {
  7. return [this] { return value; };
  8. }
  9. };
  10. MyObj mo;
  11. auto valueCopy = mo.getValueCopy();
  12. auto valueRef = mo.getValueRef();
  13. mo.value = 321;
  14. valueCopy(); // 123
  15. valueRef(); // 321

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.

  1. // Disassembly example using compiler explorer.
  2. struct S { int x; };
  3. inline S x1 = S{321}; // mov esi, dword ptr [x1]
  4. // x1: .long 321
  5. S x2 = S{123}; // mov eax, dword ptr [.L_ZZ4mainE2x2]
  6. // mov dword ptr [rbp - 8], eax
  7. // .L_ZZ4mainE2x2: .long 123

It can also be used to declare and define a static member variable, such that it does not need to be initialized in the source file.

  1. struct S {
  2. S() : id{count++} {}
  3. ~S() { count--; }
  4. int id;
  5. static inline int count{0}; // declare and initialize count to 0 within the class
  6. };

Nested namespaces

Using the namespace resolution operator to create nested namespace definitions.

  1. namespace A {
  2. namespace B {
  3. namespace C {
  4. int i;
  5. }
  6. }
  7. }

The code above can be written like this:

  1. namespace A::B::C {
  2. int i;
  3. }

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 xy, and z (which this construct declares). Tuple-like objects include std::tuplestd::pairstd::array, and aggregate structures.

  1. using Coordinate = std::pair<int, int>;
  2. Coordinate origin() {
  3. return Coordinate{0, 0};
  4. }
  5. const auto [ x, y ] = origin();
  6. x; // == 0
  7. y; // == 0
  1. std::unordered_map<std::string, int> mapping {
  2. {"a", 1},
  3. {"b", 2},
  4. {"c", 3}
  5. };
  6. // Destructure by reference.
  7. for (const auto& [key, value] : mapping) {
  8. // Do something with key and value
  9. }

Selection statements with initializer

New versions of the if and switch statements which simplify common code patterns and help users keep scopes tight.

  1. {
  2. std::lock_guard<std::mutex> lk(mx);
  3. if (v.empty()) v.push_back(val);
  4. }
  5. // vs.
  6. if (std::lock_guard<std::mutex> lk(mx); v.empty()) {
  7. v.push_back(val);
  8. }
  1. Foo gadget(args);
  2. switch (auto s = gadget.status()) {
  3. case OK: gadget.zip(); break;
  4. case Bad: throw BadFoo(s.message());
  5. }
  6. // vs.
  7. switch (Foo gadget(args); auto s = gadget.status()) {
  8. case OK: gadget.zip(); break;
  9. case Bad: throw BadFoo(s.message());
  10. }

constexpr if

Write code that is instantiated depending on a compile-time condition.

  1. template <typename T>
  2. constexpr bool isIntegral() {
  3. if constexpr (std::is_integral<T>::value) {
  4. return true;
  5. } else {
  6. return false;
  7. }
  8. }
  9. static_assert(isIntegral<int>() == true);
  10. static_assert(isIntegral<char>() == true);
  11. static_assert(isIntegral<double>() == false);
  12. struct S {};
  13. static_assert(isIntegral<S>() == false);

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.

char x = u8'x';

Direct list initialization of enums

Enums can now be initialized using braced syntax.

  1. enum byte : unsigned char {};
  2. byte b {0}; // OK
  3. byte c {-1}; // ERROR
  4. byte d = byte{1}; // OK
  5. byte e = byte{256}; // ERROR

[[fallthrough]], [[nodiscard]], [[maybe_unused]] attributes

C++17 introduces three new attributes: [[fallthrough]][[nodiscard]] and [[maybe_unused]].

  • [[fallthrough]] indicates to the compiler that falling through in a switch statement is intended behavior. This attribute may only be used in a switch statement, and must be placed before the next case/default label.
  1. switch (n) {
  2. case 1:
  3. // ...
  4. [[fallthrough]];
  5. case 2:
  6. // ...
  7. break;
  8. case 3:
  9. // ...
  10. [[fallthrough]];
  11. default:
  12. // ...
  13. }
  • [[nodiscard]] issues a warning when either a function or class has this attribute and its return value is discarded.
  1. [[nodiscard]] bool do_something() {
  2. return is_success; // true for success, false for failure
  3. }
  4. do_something(); // warning: ignoring return value of 'bool do_something()',
  5. // declared with attribute 'nodiscard'
  1. // Only issues a warning when `error_info` is returned by value.
  2. struct [[nodiscard]] error_info {
  3. // ...
  4. };
  5. error_info do_something() {
  6. error_info ei;
  7. // ...
  8. return ei;
  9. }
  10. do_something(); // warning: ignoring returned value of type 'error_info',
  11. // declared with attribute 'nodiscard'
  • [[maybe_unused]] indicates to the compiler that a variable or parameter might be unused and is intended.
  1. void my_callback(std::string msg, [[maybe_unused]] bool error) {
  2. // Don't care if `msg` is an error message, just log it.
  3. log(msg);
  4. }

__has_include

__has_include (operand) operator may be used in #if and #elif expressions to check whether a header or source file (operand) is available for inclusion or not.

One use case of this would be using two libraries that work the same way, using the backup/experimental one if the preferred one is not found on the system.

  1. #ifdef __has_include
  2. # if __has_include(<optional>)
  3. # include <optional>
  4. # define have_optional 1
  5. # elif __has_include(<experimental/optional>)
  6. # include <experimental/optional>
  7. # define have_optional 1
  8. # define experimental_optional
  9. # else
  10. # define have_optional 0
  11. # endif
  12. #endif

It can also be used to include headers existing under different names or locations on various platforms, without knowing which platform the program is running on, OpenGL headers are a good example for this which are located in OpenGL\ directory on macOS and GL\ on other platforms.

  1. #ifdef __has_include
  2. # if __has_include(<OpenGL/gl.h>)
  3. # include <OpenGL/gl.h>
  4. # include <OpenGL/glu.h>
  5. # elif __has_include(<GL/gl.h>)
  6. # include <GL/gl.h>
  7. # include <GL/glu.h>
  8. # else
  9. # error No suitable OpenGL headers found.
  10. # endif
  11. #endif

Class template argument deduction

Class template argument deduction (CTAD) allows the compiler to deduce template arguments from constructor arguments.

  1. std::vector v{ 1, 2, 3 }; // deduces std::vector<int>
  2. std::mutex mtx;
  3. auto lck = std::lock_guard{ mtx }; // deduces to std::lock_guard<std::mutex>
  4. auto p = new std::pair{ 1.0, 2.0 }; // deduces to std::pair<double, double>

For user-defined types, deduction guides can be used to guide the compiler how to deduce template arguments if applicable:

  1. template <typename T>
  2. struct container {
  3. container(T t) {}
  4. template <typename Iter>
  5. container(Iter beg, Iter end);
  6. };
  7. // deduction guide
  8. template <typename Iter>
  9. container(Iter b, Iter e) -> container<typename std::iterator_traits<Iter>::value_type>;
  10. container a{ 7 }; // OK: deduces container<int>
  11. std::vector<double> v{ 1.0, 2.0, 3.0 };
  12. auto b = container{ v.begin(), v.end() }; // OK: deduces container<double>
  13. container c{ 5, 6 }; // ERROR: std::iterator_traits<int>::value_type is not a type

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).

  1. std::variant<int, double> v{ 12 };
  2. std::get<int>(v); // == 12
  3. std::get<0>(v); // == 12
  4. v = 12.0;
  5. std::get<double>(v); // == 12.0
  6. std::get<1>(v); // == 12.0

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.

  1. std::optional<std::string> create(bool b) {
  2. if (b) {
  3. return "Godzilla";
  4. } else {
  5. return {};
  6. }
  7. }
  8. create(false).value_or("empty"); // == "empty"
  9. create(true).value(); // == "Godzilla"
  10. // optional-returning factory functions are usable as conditions of while and if
  11. if (auto str = create(true)) {
  12. // ...
  13. }

std::any

A type-safe container for single values of any type.

  1. std::any x {5};
  2. x.has_value() // == true
  3. std::any_cast<int>(x) // == 5
  4. std::any_cast<int&>(x) = 10;
  5. std::any_cast<int>(x) // == 10

std::string_view

A non-owning reference to a string. Useful for providing an abstraction on top of strings (e.g. for parsing).

  1. // Regular strings.
  2. std::string_view cppstr {"foo"};
  3. // Wide strings.
  4. std::wstring_view wcstr_v {L"baz"};
  5. // Character arrays.
  6. char array[3] = {'b', 'a', 'r'};
  7. std::string_view array_v(array, std::size(array));
  1. std::string str {" trim me"};
  2. std::string_view v {str};
  3. v.remove_prefix(std::min(v.find_first_not_of(" "), v.size()));
  4. str; // == " trim me"
  5. v; // == "trim me"

std::invoke

Invoke a Callable object with parameters. Examples of callable objects are std::function or lambdas; objects that can be called similarly to a regular function.

  1. template <typename Callable>
  2. class Proxy {
  3. Callable c_;
  4. public:
  5. Proxy(Callable c) : c_{ std::move(c) } {}
  6. template <typename... Args>
  7. decltype(auto) operator()(Args&&... args) {
  8. // ...
  9. return std::invoke(c_, std::forward<Args>(args)...);
  10. }
  11. };
  12. const auto add = [](int x, int y) { return x + y; };
  13. Proxy p{ add };
  14. p(1, 2); // == 3

std::apply

Invoke a Callable object with a tuple of arguments.

  1. auto add = [](int x, int y) {
  2. return x + y;
  3. };
  4. std::apply(add, std::make_tuple(1, 2)); // == 3

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:

  1. const auto bigFilePath {"bigFileToCopy"};
  2. if (std::filesystem::exists(bigFilePath)) {
  3. const auto bigFileSize {std::filesystem::file_size(bigFilePath)};
  4. std::filesystem::path tmpPath {"/tmp"};
  5. if (std::filesystem::space(tmpPath).available > bigFileSize) {
  6. std::filesystem::create_directory(tmpPath.append("example"));
  7. std::filesystem::copy_file(bigFilePath, tmpPath.append("newFile"));
  8. }
  9. }

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.

  1. std::byte a {0};
  2. std::byte b {0xFF};
  3. int i = std::to_integer<int>(b); // 0xFF
  4. std::byte c = a & b;
  5. int j = std::to_integer<int>(c); // 0

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:

  1. std::map<int, string> src {{1, "one"}, {2, "two"}, {3, "buckle my shoe"}};
  2. std::map<int, string> dst {{3, "three"}};
  3. dst.insert(src.extract(src.find(1))); // Cheap remove and insert of { 1, "one" } from `src` to `dst`.
  4. dst.insert(src.extract(2)); // Cheap remove and insert of { 2, "two" } from `src` to `dst`.
  5. // dst == { { 1, "one" }, { 2, "two" }, { 3, "three" } };

Inserting an entire set:

  1. std::set<int> src {1, 3, 5};
  2. std::set<int> dst {2, 4, 5};
  3. dst.merge(src);
  4. // src == { 5 }
  5. // dst == { 1, 2, 3, 4, 5 }

Inserting elements which outlive the container:

  1. auto elementFactory() {
  2. std::set<...> s;
  3. s.emplace(...);
  4. return s.extract(s.begin());
  5. }
  6. s2.insert(elementFactory());

Changing the key of a map element:

  1. std::map<int, string> m {{1, "one"}, {2, "two"}, {3, "three"}};
  2. auto e = m.extract(2);
  3. e.key() = 4;
  4. m.insert(std::move(e));
  5. // m == { { 1, "one" }, { 3, "three" }, { 4, "two" } }

Parallel algorithms

Many of the STL algorithms, such as the copyfind and sort methods, started to support the parallel execution policiesseqpar and par_unseq which translate to "sequentially", "parallel" and "parallel unsequenced".

  1. std::vector<int> longVector;
  2. // Find element using parallel execution policy
  3. auto result1 = std::find(std::execution::par, std::begin(longVector), std::end(longVector), 2);
  4. // Sort elements using sequential execution policy
  5. auto result2 = std::sort(std::execution::seq, std::begin(longVector), std::end(longVector));

std::sample

Samples n elements in the given sequence (without replacement) where every element has an equal chance of being selected.

  1. const std::string ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  2. std::string guid;
  3. // Sample 5 characters from ALLOWED_CHARS.
  4. std::sample(ALLOWED_CHARS.begin(), ALLOWED_CHARS.end(), std::back_inserter(guid),
  5. 5, std::mt19937{ std::random_device{}() });
  6. std::cout << guid; // e.g. G1fW2

std::clamp

Clamp given value between a lower and upper bound.

  1. std::clamp(42, -1, 1); // == 1
  2. std::clamp(-42, -1, 1); // == -1
  3. std::clamp(0, -1, 1); // == 0
  4. // `std::clamp` also accepts a custom comparator:
  5. std::clamp(0, -1, 1, std::less<>{}); // == 0

std::reduce

Fold over a given range of elements. Conceptually similar to std::accumulate, but std::reduce will perform the fold in parallel. Due to the fold being done in parallel, if you specify a binary operation, it is required to be associative and commutative. A given binary operation also should not change any element or invalidate any iterators within the given range.

The default binary operation is std::plus with an initial value of 0.

  1. const std::array<int, 3> a{ 1, 2, 3 };
  2. std::reduce(std::cbegin(a), std::cend(a)); // == 6
  3. // Using a custom binary op:
  4. std::reduce(std::cbegin(a), std::cend(a), 1, std::multiplies<>{}); // == 6

Additionally you can specify transformations for reducers:

  1. std::transform_reduce(std::cbegin(a), std::cend(a), 0, std::plus<>{}, times_ten); // == 60
  2. const std::array<int, 3> b{ 1, 2, 3 };
  3. const auto product_times_ten = [](const auto a, const auto b) { return a * b * 10; };
  4. std::transform_reduce(std::cbegin(a), std::cend(a), std::cbegin(b), 0, std::plus<>{}, product_times_ten); // == 140

Prefix sum algorithms

Support for prefix sums (both inclusive and exclusive scans) along with transformations.

  1. const std::array<int, 3> a{ 1, 2, 3 };
  2. std::inclusive_scan(std::cbegin(a), std::cend(a),
  3. std::ostream_iterator<int>{ std::cout, " " }, std::plus<>{}); // 1 3 6
  4. std::exclusive_scan(std::cbegin(a), std::cend(a),
  5. std::ostream_iterator<int>{ std::cout, " " }, 0, std::plus<>{}); // 0 1 3
  6. const auto times_ten = [](const auto n) { return n * 10; };
  7. std::transform_inclusive_scan(std::cbegin(a), std::cend(a),
  8. std::ostream_iterator<int>{ std::cout, " " }, std::plus<>{}, times_ten); // 10 30 60
  9. std::transform_exclusive_scan(std::cbegin(a), std::cend(a),
  10. std::ostream_iterator<int>{ std::cout, " " }, 0, std::plus<>{}, times_ten); // 0 10 30

GCD and LCM

Greatest common divisor (GCD) and least common multiple (LCM).

  1. const int p = 9;
  2. const int q = 3;
  3. std::gcd(p, q); // == 3
  4. std::lcm(p, q); // == 9

std::not_fn

Utility function that returns the negation of the result of the given function.

  1. const std::ostream_iterator<int> ostream_it{ std::cout, " " };
  2. const auto is_even = [](const auto n) { return n % 2 == 0; };
  3. std::vector<int> v{ 0, 1, 2, 3, 4 };
  4. // Print all even numbers.
  5. std::copy_if(std::cbegin(v), std::cend(v), ostream_it, is_even); // 0 2 4
  6. // Print all odd (not even) numbers.
  7. std::copy_if(std::cbegin(v), std::cend(v), ostream_it, std::not_fn(is_even)); // 1 3

String conversion to/from numbers

Convert integrals and floats to a string or vice-versa. Conversions are non-throwing, do not allocate, and are more secure than the equivalents from the C standard library.

Users are responsible for allocating enough storage required for std::to_chars, or the function will fail by setting the error code object in its return value.

These functions allow you to optionally pass a base (defaults to base-10) or a format specifier for floating type input.

  • std::to_chars returns a (non-const) char pointer which is one-past-the-end of the string that the function wrote to inside the given buffer, and an error code object.
  • std::from_chars returns a const char pointer which on success is equal to the end pointer passed to the function, and an error code object.

Both error code objects returned from these functions are equal to the default-initialized error code object on success.

Convert the number 123 to a std::string:

  1. const int n = 123;
  2. // Can use any container, string, array, etc.
  3. std::string str;
  4. str.resize(3); // hold enough storage for each digit of `n`
  5. const auto [ ptr, ec ] = std::to_chars(str.data(), str.data() + str.size(), n);
  6. if (ec == std::errc{}) { std::cout << str << std::endl; } // 123
  7. else { /* handle failure */ }

Convert from a std::string with value "123" to an integer:

  1. const std::string str{ "123" };
  2. int n;
  3. const auto [ ptr, ec ] = std::from_chars(str.data(), str.data() + str.size(), n);
  4. if (ec == std::errc{}) { std::cout << n << std::endl; } // 123
  5. else { /* handle failure */ }

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 '.

  1. 0b110 // == 6
  2. 0b1111'1111 // == 255

Generic lambda expressions

C++14 now allows the auto type-specifier in the parameter list, enabling polymorphic lambdas.

  1. auto identity = [](auto x) { return x; };
  2. int three = identity(3); // == 3
  3. std::string foo = identity("foo"); // == "foo"

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).

  1. int factory(int i) { return i * 10; }
  2. auto f = [x = factory(2)] { return x; }; // returns 20
  3. auto generator = [x = 0] () mutable {
  4. // this would not compile without 'mutable' as we are modifying x on each call
  5. return x++;
  6. };
  7. auto a = generator(); // == 0
  8. auto b = generator(); // == 1
  9. auto c = generator(); // == 2

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.

  1. auto p = std::make_unique<int>(1);
  2. auto task1 = [=] { *p = 5; }; // ERROR: std::unique_ptr cannot be copied
  3. // vs.
  4. auto task2 = [p = std::move(p)] { *p = 5; }; // OK: p is move-constructed into the closure object
  5. // the original p is empty after task2 is created

Using this reference-captures can have different names than the referenced variable.

  1. auto x = 1;
  2. auto f = [&r = x, x = x * 10] {
  3. ++r;
  4. return r + x;
  5. };
  6. f(); // sets x to 2 and returns 12

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.

  1. // Deduce return type as `int`.
  2. auto f(int i) {
  3. return i;
  4. }
  1. template <typename T>
  2. auto& f(T& t) {
  3. return t;
  4. }
  5. // Returns a reference to a deduced type.
  6. auto g = [](auto& x) -> auto& { return f(x); };
  7. int y = 123;
  8. int& z = g(y); // reference to `y`

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.

  1. const int x = 0;
  2. auto x1 = x; // int
  3. decltype(auto) x2 = x; // const int
  4. int y = 0;
  5. int& y1 = y;
  6. auto y2 = y1; // int
  7. decltype(auto) y3 = y1; // int&
  8. int&& z = 0;
  9. auto z1 = std::move(z); // int
  10. decltype(auto) z2 = std::move(z); // int&&
  1. // Note: Especially useful for generic code!
  2. // Return type is `int`.
  3. auto f(const int& i) {
  4. return i;
  5. }
  6. // Return type is `const int&`.
  7. decltype(auto) g(const int& i) {
  8. return i;
  9. }
  10. int x = 123;
  11. static_assert(std::is_same<const int&, decltype(f(x))>::value == 0);
  12. static_assert(std::is_same<int, decltype(f(x))>::value == 1);
  13. static_assert(std::is_same<const int&, decltype(g(x))>::value == 1);

See also: decltype (C++11).

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): typedefs, usings, 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 returns, loops, etc.

  1. constexpr int factorial(int n) {
  2. if (n <= 1) {
  3. return 1;
  4. } else {
  5. return n * factorial(n - 1);
  6. }
  7. }
  8. factorial(5); // == 120

Variable templates

C++14 allows variables to be templated:

  1. template<class T>
  2. constexpr T pi = T(3.1415926535897932385);
  3. template<class T>
  4. constexpr T e = T(2.7182818284590452353);

[[deprecated]] attribute

C++14 introduces the [[deprecated]] attribute to indicate that a unit (function, class, etc.) is discouraged and likely yield compilation warnings. If a reason is provided, it will be included in the warnings.

  1. [[deprecated]]
  2. void old_method();
  3. [[deprecated("Use new_method instead")]]
  4. void legacy_method();

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.

  1. using namespace std::chrono_literals;
  2. auto day = 24h;
  3. day.count(); // == 24
  4. std::chrono::duration_cast<std::chrono::minutes>(day).count(); // == 1440

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 of 0, ..., N - 1 with type T.
  • std::index_sequence_for<T...> - converts a template parameter pack into an integer sequence.

Convert an array into a tuple:

  1. template<typename Array, std::size_t... I>
  2. decltype(auto) a2t_impl(const Array& a, std::integer_sequence<std::size_t, I...>) {
  3. return std::make_tuple(a[I]...);
  4. }
  5. template<typename T, std::size_t N, typename Indices = std::make_index_sequence<N>>
  6. decltype(auto) a2t(const std::array<T, N>& a) {
  7. return a2t_impl(a, Indices());
  8. }

std::make_unique

std::make_unique is the recommended way to create instances of std::unique_ptrs 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:
foo(std::unique_ptr<T>{new T{}}, function_that_throws(), std::unique_ptr<T>{new T{}});

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:

foo(std::make_unique<T>(), function_that_throws(), std::make_unique<T>());

See the section on smart pointers (C++11) for more information on std::unique_ptr and std::shared_ptr.

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_ptrs (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 referencesspecial member functions for move semanticsstd::movestd::forwardforwarding 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:

  1. int x = 0; // `x` is an lvalue of type `int`
  2. int& xl = x; // `xl` is an lvalue of type `int&`
  3. int&& xr = x; // compiler error -- `x` is an lvalue
  4. int&& xr2 = 0; // `xr2` is an lvalue of type `int&&` -- binds to the rvalue temporary, `0`
  5. void f(int& x) {}
  6. void f(int&& x) {}
  7. f(x); // calls f(int&)
  8. f(xl); // calls f(int&)
  9. f(3); // calls f(int&&)
  10. f(std::move(x)); // calls f(int&&)
  11. f(xr2); // calls f(int&)
  12. f(std::move(xr2)); // calls f(int&& x)

See also: std::movestd::forwardforwarding 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& & becomes T&
  • T& && becomes T&
  • T&& & becomes T&
  • T&& && becomes T&&

auto type deduction with lvalues and rvalues:

  1. int x = 0; // `x` is an lvalue of type `int`
  2. auto&& al = x; // `al` is an lvalue of type `int&` -- binds to the lvalue, `x`
  3. auto&& ar = 0; // `ar` is an lvalue of type `int&&` -- binds to the rvalue temporary, `0`

Template type parameter deduction with lvalues and rvalues:

  1. // Since C++14 or later:
  2. void f(auto&& t) {
  3. // ...
  4. }
  5. // Since C++11 or later:
  6. template <typename T>
  7. void f(T&& t) {
  8. // ...
  9. }
  10. int x = 0;
  11. f(0); // T is int, deduces as f(int &&) => f(int&&)
  12. f(x); // T is int&, deduces as f(int& &&) => f(int&)
  13. int& y = x;
  14. f(y); // T is int&, deduces as f(int& &&) => f(int&)
  15. int&& z = 0; // NOTE: `z` is an lvalue with type `int&&`.
  16. f(z); // T is int&, deduces as f(int& &&) => f(int&)
  17. f(std::move(z)); // T is int, deduces as f(int &&) => f(int&&)

See also: std::movestd::forwardrvalue 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.

  1. template <typename... T>
  2. struct arity {
  3. constexpr static int value = sizeof...(T);
  4. };
  5. static_assert(arity<>::value == 0);
  6. static_assert(arity<char, short, int>::value == 3);

An interesting use for this is creating an initializer list from a parameter pack in order to iterate over variadic function arguments.

  1. template <typename First, typename... Args>
  2. auto sum(const First first, const Args... args) -> decltype(first) {
  3. const auto values = {first, args...};
  4. return std::accumulate(values.begin(), values.end(), First{0});
  5. }
  6. sum(1, 2, 3, 4, 5); // 15
  7. sum(1, 2, 3); // 6
  8. sum(1.5, 2.0, 3.7); // 7.2

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.

  1. int sum(const std::initializer_list<int>& list) {
  2. int total = 0;
  3. for (auto& e : list) {
  4. total += e;
  5. }
  6. return total;
  7. }
  8. auto list = {1, 2, 3};
  9. sum(list); // == 6
  10. sum({1, 2, 3}); // == 6
  11. sum({}); // == 0

Static assertions

Assertions that are evaluated at compile-time.

  1. constexpr int x = 0;
  2. constexpr int y = 1;
  3. static_assert(x == y, "x != y");

auto

auto-typed variables are deduced by the compiler according to the type of their initializer.

  1. auto a = 3.14; // double
  2. auto b = 1; // int
  3. auto& c = b; // int&
  4. auto d = { 0 }; // std::initializer_list<int>
  5. auto&& e = 1; // int&&
  6. auto&& f = b; // int&
  7. auto g = new auto(123); // int*
  8. const auto h = 1; // const int
  9. auto i = 1, j = 2, k = 3; // int, int, int
  10. auto l = 1, m = true, n = 1.61; // error -- `l` deduced to be int, `m` is bool
  11. auto o; // error -- `o` requires initializer

Extremely useful for readability, especially for complicated types:

  1. std::vector<int> v = ...;
  2. std::vector<int>::const_iterator cit = v.cbegin();
  3. // vs.
  4. auto cit = v.cbegin();

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:

  1. template <typename X, typename Y>
  2. auto add(X x, Y y) -> decltype(x + y) {
  3. return x + y;
  4. }
  5. add(1, 2); // == 3
  6. add(1, 2.0); // == 3.0
  7. add(1.5, 1.5); // == 3.0

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

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] - capture this by reference.
  • [a, &b] - capture objects a by value, b by reference.
  1. int x = 1;
  2. auto getX = [=] { return x; };
  3. getX(); // == 1
  4. auto addX = [=](int y) { return x + y; };
  5. addX(1); // == 2
  6. auto getXRef = [&]() -> int& { return x; };
  7. getXRef(); // int& to `x`

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).

  1. int x = 1;
  2. auto f1 = [&x] { x = 2; }; // OK: x is a reference and modifies the original
  3. auto f2 = [x] { x = 2; }; // ERROR: the lambda can only perform const-operations on the captured value
  4. // vs.
  5. auto f3 = [x]() mutable { x = 2; }; // OK: the lambda can perform any operations on the captured value

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:

  1. int a = 1; // `a` is declared as type `int`
  2. decltype(a) b = a; // `decltype(a)` is `int`
  3. const int& c = a; // `c` is declared as type `const int&`
  4. decltype(c) d = a; // `decltype(c)` is `const int&`
  5. decltype(123) e = 123; // `decltype(123)` is `int`
  6. int&& f = 1; // `f` is declared as type `int&&`
  7. decltype(f) g = 1; // `decltype(f) is `int&&`
  8. decltype((a)) h = g; // `decltype((a))` is int&
  1. template <typename X, typename Y>
  2. auto add(X x, Y y) -> decltype(x + y) {
  3. return x + y;
  4. }
  5. add(1, 2.0); // `decltype(x + y)` => `decltype(3.0)` => `double`

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.

  1. template <typename T>
  2. using Vec = std::vector<T>;
  3. Vec<int> v; // std::vector<int>
  4. using String = std::string;
  5. String s {"foo"};

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.

  1. void foo(int);
  2. void foo(char*);
  3. foo(NULL); // error -- ambiguous
  4. foo(nullptr); // calls foo(char*)

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.

  1. // Specifying underlying type as `unsigned int`
  2. enum class Color : unsigned int { Red = 0xff0000, Green = 0xff00, Blue = 0xff };
  3. // `Red`/`Green` in `Alert` don't conflict with `Color`
  4. enum class Alert : bool { Red, Green };
  5. Color c = Color::Red;

Attributes

Attributes provide a universal syntax over __attribute__(...)__declspec, etc.

  1. // `noreturn` attribute indicates `f` doesn't return.
  2. [[ noreturn ]] void f() {
  3. throw "error";
  4. }

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.

  1. constexpr int square(int x) {
  2. return x * x;
  3. }
  4. int square2(int x) {
  5. return x * x;
  6. }
  7. int a = square(2); // mov DWORD PTR [rbp-4], 4
  8. int b = square2(2); // mov edi, 2
  9. // call square2(int)
  10. // mov DWORD PTR [rbp-8], eax

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:

  1. const int x = 123;
  2. constexpr const int& y = x; // error -- constexpr variable `y` must be initialized by a constant expression

Constant expressions with classes:

  1. struct Complex {
  2. constexpr Complex(double r, double i) : re{r}, im{i} { }
  3. constexpr double real() { return re; }
  4. constexpr double imag() { return im; }
  5. private:
  6. double re;
  7. double im;
  8. };
  9. constexpr Complex I(0, 1);

Delegating constructors

Constructors can now call other constructors in the same class using an initializer list.

  1. struct Foo {
  2. int foo;
  3. Foo(int foo) : foo{foo} {}
  4. Foo() : Foo(0) {}
  5. };
  6. Foo foo;
  7. foo.foo; // == 0

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:

  1. // `unsigned long long` parameter required for integer literal.
  2. long long operator "" _celsius(unsigned long long tempCelsius) {
  3. return std::llround(tempCelsius * 1.8 + 32);
  4. }
  5. 24_celsius; // == 75

String to integer conversion:

  1. // `const char*` and `std::size_t` required as parameters.
  2. int operator "" _int(const char* str, std::size_t) {
  3. return std::stoi(str);
  4. }
  5. "123"_int; // == 123, with type `int`

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.

  1. struct A {
  2. virtual void foo();
  3. void bar();
  4. };
  5. struct B : A {
  6. void foo() override; // correct -- B::foo overrides A::foo
  7. void bar() override; // error -- A::bar is not virtual
  8. void baz() override; // error -- B::baz does not override A::baz
  9. };

Final specifier

Specifies that a virtual function cannot be overridden in a derived class or that a class cannot be inherited from.

  1. struct A {
  2. virtual void foo();
  3. };
  4. struct B : A {
  5. virtual void foo() final;
  6. };
  7. struct C : B {
  8. virtual void foo(); // error -- declaration of 'foo' overrides a 'final' function
  9. };

Class cannot be inherited from.

  1. struct A final {};
  2. struct B : A {}; // error -- base 'A' is marked 'final'

Default functions

A more elegant, efficient way to provide a default implementation of a function, such as a constructor.

  1. struct A {
  2. A() = default;
  3. A(int x) : x{x} {}
  4. int x {1};
  5. };
  6. A a; // a.x == 1
  7. A a2 {123}; // a.x == 123

With inheritance:

  1. struct B {
  2. B() : x{1} {}
  3. int x;
  4. };
  5. struct C : B {
  6. // Calls B::B
  7. C() = default;
  8. };
  9. C c; // c.x == 1

Deleted functions

A more elegant, efficient way to provide a deleted implementation of a function. Useful for preventing copies on objects.

  1. class A {
  2. int x;
  3. public:
  4. A(int x) : x{x} {};
  5. A(const A&) = delete;
  6. A& operator=(const A&) = delete;
  7. };
  8. A x {123};
  9. A y = x; // error -- call to deleted copy constructor
  10. y = x; // error -- operator= deleted

Range-based for loops

Syntactic sugar for iterating over a container's elements.

  1. std::array<int, 5> a {1, 2, 3, 4, 5};
  2. for (int& x : a) x *= 2;
  3. // a == { 2, 4, 6, 8, 10 }

Note the difference when using int as opposed to int&:

  1. std::array<int, 5> a {1, 2, 3, 4, 5};
  2. for (int x : a) x *= 2;
  3. // a == { 1, 2, 3, 4, 5 }

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.

  1. struct A {
  2. std::string s;
  3. A() : s{"test"} {}
  4. A(const A& o) : s{o.s} {}
  5. A(A&& o) : s{std::move(o.s)} {}
  6. A& operator=(A&& o) {
  7. s = std::move(o.s);
  8. return *this;
  9. }
  10. };
  11. A f(A a) {
  12. return a;
  13. }
  14. A a1 = f(A{}); // move-constructed from rvalue temporary
  15. A a2 = std::move(a1); // move-constructed using std::move
  16. A a3 = A{};
  17. a2 = std::move(a3); // move-assignment using std::move
  18. a1 = f(A{}); // move-assignment from rvalue temporary

Converting constructors

Converting constructors will convert values of braced list syntax into constructor arguments.

  1. struct A {
  2. A(int) {}
  3. A(int, int) {}
  4. A(int, int, int) {}
  5. };
  6. A a {0, 0}; // calls A::A(int, int)
  7. A b(0, 0); // calls A::A(int, int)
  8. A c = {0, 0}; // calls A::A(int, int)
  9. A d {0, 0, 0}; // calls A::A(int, int, int)

Note that the braced list syntax does not allow narrowing:

  1. struct A {
  2. A(int) {}
  3. };
  4. A a(1.1); // OK
  5. A b {1.1}; // Error narrowing conversion from double to int

Note that if a constructor accepts a std::initializer_list, it will be called instead:

  1. struct A {
  2. A(int) {}
  3. A(int, int) {}
  4. A(int, int, int) {}
  5. A(std::initializer_list<int>) {}
  6. };
  7. A a {0, 0}; // calls A::A(std::initializer_list<int>)
  8. A b(0, 0); // calls A::A(int, int)
  9. A c = {0, 0}; // calls A::A(std::initializer_list<int>)
  10. A d {0, 0, 0}; // calls A::A(std::initializer_list<int>)

Explicit conversion functions

Conversion functions can now be made explicit using the explicit specifier.

  1. struct A {
  2. operator bool() const { return true; }
  3. };
  4. struct B {
  5. explicit operator bool() const { return true; }
  6. };
  7. A a;
  8. if (a); // OK calls A::operator bool()
  9. bool ba = a; // OK copy-initialization selects A::operator bool()
  10. B b;
  11. if (b); // OK calls B::operator bool()
  12. bool bb = b; // error copy-initialization does not consider B::operator bool()

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.

  1. namespace Program {
  2. namespace Version1 {
  3. int getVersion() { return 1; }
  4. bool isFirstVersion() { return true; }
  5. }
  6. inline namespace Version2 {
  7. int getVersion() { return 2; }
  8. }
  9. }
  10. int version {Program::getVersion()}; // Uses getVersion() from Version2
  11. int oldVersion {Program::Version1::getVersion()}; // Uses getVersion() from Version1
  12. bool firstVersion {Program::isFirstVersion()}; // Does not compile when Version2 is added

Non-static data member initializers

Allows non-static data members to be initialized where they are declared, potentially cleaning up constructors of default initializations.

  1. // Default initialization prior to C++11
  2. class Human {
  3. Human() : age{0} {}
  4. private:
  5. unsigned age;
  6. };
  7. // Default initialization on C++11
  8. class Human {
  9. private:
  10. unsigned age {0};
  11. };

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.

  1. typedef std::map<int, std::map <int, std::map <int, int> > > cpp98LongTypedef;
  2. typedef std::map<int, std::map <int, std::map <int, int>>> cpp11LongTypedef;

Ref-qualified member functions

Member functions can now be qualified depending on whether *this is an lvalue or rvalue reference.

  1. struct Bar {
  2. // ...
  3. };
  4. struct Foo {
  5. Bar getBar() & { return bar; }
  6. Bar getBar() const& { return bar; }
  7. Bar getBar() && { return std::move(bar); }
  8. private:
  9. Bar bar;
  10. };
  11. Foo foo{};
  12. Bar bar = foo.getBar(); // calls `Bar getBar() &`
  13. const Foo foo2{};
  14. Bar bar2 = foo2.getBar(); // calls `Bar Foo::getBar() const&`
  15. Foo{}.getBar(); // calls `Bar Foo::getBar() &&`
  16. std::move(foo).getBar(); // calls `Bar Foo::getBar() &&`
  17. std::move(foo2).getBar(); // calls `Bar Foo::getBar() const&&`

Trailing return types

C++11 allows functions and lambdas an alternative syntax for specifying their return types.

  1. int f() {
  2. return 123;
  3. }
  4. // vs.
  5. auto f() -> int {
  6. return 123;
  7. }
  1. auto g = []() -> int {
  2. return 123;
  3. };

This feature is especially useful when certain return types cannot be resolved:

  1. // NOTE: This does not compile!
  2. template <typename T, typename U>
  3. decltype(a + b) add(T a, U b) {
  4. return a + b;
  5. }
  6. // Trailing return types allows this:
  7. template <typename T, typename U>
  8. auto add(T a, U b) -> decltype(a + b) {
  9. return a + b;
  10. }

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().

  1. void func1() noexcept; // does not throw
  2. void func2() noexcept(true); // does not throw
  3. void func3() throw(); // does not throw
  4. void func4() noexcept(false); // may 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.

  1. extern void f(); // potentially-throwing
  2. void g() noexcept {
  3. f(); // valid, even if f throws
  4. throw 42; // valid, effectively a call to std::terminate
  5. }

char32_t and char16_t

Provides standard types for representing UTF-8 strings.

  1. char32_t utf8_str[] = U"\u0123";
  2. char16_t utf8_str[] = u"\u0123";

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:

  1. // msg1 and msg2 are equivalent.
  2. const char* msg1 = "\nHello,\n\tworld!\n";
  3. const char* msg2 = R"(
  4. Hello,
  5. world!
  6. )";

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):

  1. template <typename T>
  2. typename remove_reference<T>::type&& move(T&& arg) {
  3. return static_cast<typename remove_reference<T>::type&&>(arg);
  4. }

Transferring std::unique_ptrs:

  1. std::unique_ptr<int> p1 {new int{0}}; // in practice, use std::make_unique
  2. std::unique_ptr<int> p2 = p1; // error -- cannot copy unique pointers
  3. std::unique_ptr<int> p3 = std::move(p1); // move `p1` into `p3`
  4. // now unsafe to dereference object held by `p1`

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:

  1. template <typename T>
  2. T&& forward(typename remove_reference<T>::type& arg) {
  3. return static_cast<T&&>(arg);
  4. }

An example of a function wrapper which just forwards other A objects to a new A object's copy or move constructor:

  1. struct A {
  2. A() = default;
  3. A(const A& o) { std::cout << "copied" << std::endl; }
  4. A(A&& o) { std::cout << "moved" << std::endl; }
  5. };
  6. template <typename T>
  7. A wrapper(T&& arg) {
  8. return A{std::forward<T>(arg)};
  9. }
  10. wrapper(A{}); // moved
  11. A a;
  12. wrapper(a); // copied
  13. wrapper(std::move(a)); // moved

See also: forwarding referencesrvalue 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.

  1. void foo(bool clause) { /* do something... */ }
  2. std::vector<std::thread> threadsVector;
  3. threadsVector.emplace_back([]() {
  4. // Lambda function that will be invoked
  5. });
  6. threadsVector.emplace_back(foo, true); // thread will run foo(true)
  7. for (auto& thread : threadsVector) {
  8. thread.join(); // Wait for threads to finish
  9. }

std::to_string

Converts a numeric argument to a std::string.

  1. std::to_string(1.2); // == "1.2"
  2. std::to_string(123); // == "123"

Type traits

Type traits defines a compile-time template-based interface to query or modify the properties of types.

  1. static_assert(std::is_integral<int>::value);
  2. static_assert(std::is_same<int, int>::value);
  3. static_assert(std::is_same<std::conditional<true, int, double>::type, int>::value);

Smart pointers

C++11 introduces new smart pointers: std::unique_ptrstd::shared_ptrstd::weak_ptrstd::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.

  1. std::unique_ptr<Foo> p1 { new Foo{} }; // `p1` owns `Foo`
  2. if (p1) {
  3. p1->bar();
  4. }
  5. {
  6. std::unique_ptr<Foo> p2 {std::move(p1)}; // Now `p2` owns `Foo`
  7. f(*p2);
  8. p1 = std::move(p2); // Ownership returns to `p1` -- `p2` gets destroyed
  9. }
  10. if (p1) {
  11. p1->bar();
  12. }
  13. // `Foo` instance is destroyed when `p1` goes out of scope

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.

  1. void foo(std::shared_ptr<T> t) {
  2. // Do something with `t`...
  3. }
  4. void bar(std::shared_ptr<T> t) {
  5. // Do something with `t`...
  6. }
  7. void baz(std::shared_ptr<T> t) {
  8. // Do something with `t`...
  9. }
  10. std::shared_ptr<T> p1 {new T{}};
  11. // Perhaps these take place in another threads?
  12. foo(p1);
  13. bar(p1);
  14. baz(p1);

std::chrono

The chrono library contains a set of utility functions and types that deal with durationsclocks, and time points. One use case of this library is benchmarking code:

  1. std::chrono::time_point<std::chrono::steady_clock> start, end;
  2. start = std::chrono::steady_clock::now();
  3. // Some computations...
  4. end = std::chrono::steady_clock::now();
  5. std::chrono::duration<double> elapsed_seconds = end - start;
  6. double t = elapsed_seconds.count(); // t number of seconds, represented as a `double`

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.

  1. // `playerProfile` has type `std::tuple<int, const char*, const char*>`.
  2. auto playerProfile = std::make_tuple(51, "Frans Nielsen", "NYI");
  3. std::get<0>(playerProfile); // 51
  4. std::get<1>(playerProfile); // "Frans Nielsen"
  5. std::get<2>(playerProfile); // "NYI"

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.

  1. // With tuples...
  2. std::string playerName;
  3. std::tie(std::ignore, playerName, std::ignore) = std::make_tuple(91, "John Tavares", "NYI");
  4. // With pairs...
  5. std::string yes, no;
  6. std::tie(yes, no) = std::make_pair("yes", "no");

std::array

std::array is a container built on top of a C-style array. Supports common container operations such as sorting.

  1. std::array<int, 3> a = {2, 1, 3};
  2. std::sort(a.begin(), a.end()); // a == { 1, 2, 3 }
  3. for (int& x : a) x *= 2; // a == { 2, 4, 6 }

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_ptrs 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:
foo(std::shared_ptr<T>{new T{}}, function_that_throws(), std::shared_ptr<T>{new T{}});

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:

foo(std::make_shared<T>(), function_that_throws(), std::make_shared<T>());
  • Prevents having to do two allocations. When calling std::shared_ptr{ new T{} }, we have to allocate memory for T, 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.

  1. // create a container to store reference of objects.
  2. auto val = 99;
  3. auto _ref = std::ref(val);
  4. _ref++;
  5. auto _cref = std::cref(val);
  6. //_cref++; does not compile
  7. std::vector<std::reference_wrapper<int>>vec; // vector<int&>vec does not compile
  8. vec.push_back(_ref); // vec.push_back(&i) does not compile
  9. cout << val << endl; // prints 100
  10. cout << vec[0] << endl; // prints 100
  11. cout << _cref; // prints 100

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:

  1. std::launch::async | std::launch::deferred It is up to the implementation whether to perform asynchronous execution or lazy evaluation.
  2. std::launch::async Run the callable object on a new thread.
  3. std::launch::deferred Perform lazy evaluation on the current thread.
  1. int foo() {
  2. /* Do something here, then return the result. */
  3. return 1000;
  4. }
  5. auto handle = std::async(std::launch::async, foo); // create an async task
  6. auto result = handle.get(); // wait for the result

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.

  1. template <typename T>
  2. int CountTwos(const T& container) {
  3. return std::count_if(std::begin(container), std::end(container), [](int item) {
  4. return item == 2;
  5. });
  6. }
  7. std::vector<int> vec = {2, 2, 43, 435, 4543, 534};
  8. int arr[8] = {2, 43, 45, 435, 32, 32, 32, 32};
  9. auto a = CountTwos(vec); // 2
  10. auto b = CountTwos(arr); // 1

Acknowledgements

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/323840
推荐阅读
相关标签
  

闽ICP备14008679号