Lesson 31-New Features in C++11-14-17-20

New Features and Characteristics in C++11

Automatic Type Deduction (auto)

The auto keyword allows the compiler to automatically deduce the type of a variable based on the type of the initialization expression. This makes code more concise, especially when dealing with complex type expressions.

auto i = 42;  // i has type int
auto p = std::make_pair(1, 2);  // p has type std::pair<int, int>

Initializer Lists ({})

Initializer lists allow the use of braces {} to initialize containers and arrays, making the code clearer.

std::vector<int> v = {1, 2, 3};  // Initialize vector using initializer list

nullptr Type

nullptr is a new keyword used to represent a null pointer. It is an object of type std::nullptr_t and can be converted to any pointer type.

int* p = nullptr;  // Initialize pointer using nullptr

Rvalue References (&&) and Move Semantics

Rvalue references enable move semantics, which can improve performance, especially when dealing with large objects. Move semantics allow the state of a temporary object to be quickly transferred to another object.

class MyClass {
public:
    MyClass() {}
    MyClass(MyClass&& other) noexcept : data(other.data) { other.data = nullptr; }  // Move constructor
    MyClass& operator=(MyClass&& other) noexcept {  // Move assignment operator
        std::swap(data, other.data);
        return *this;
    }
private:
    int* data;
};

std::move

The std::move function is used to explicitly tell the compiler that an expression should be treated as an rvalue, thereby enabling move semantics.

MyClass a;
MyClass b = std::move(a);  // Enable move semantics

override and final Keywords

These two keywords are used to control the behavior of virtual functions. override is used to indicate that a member function overrides a virtual function in the base class; final is used to prohibit further overriding.

class Base {
public:
    virtual void foo() = 0;
};

class Derived : public Base {
public:
    void foo() override;  // Override virtual function in base class
};

class NoMore : public Derived {
public:
    void foo() final;  // Prohibit further overriding
};

Lambda Expressions

Lambda expressions allow the creation of anonymous functions that can be defined and used directly in code. They can capture surrounding variables and are very flexible.

auto add = [](int a, int b) { return a + b; };
int result = add(2, 3);  // Result is 5

Concurrency Support

C++11 introduced the threading library <thread>, providing the std::thread class to support multithreaded programming.

#include <thread>

void hello() {
    std::cout << "Hello from thread" << std::endl;
}

int main() {
    std::thread t(hello);  // Create thread
    t.join();  // Wait for thread to finish
    return 0;
}

decltype

decltype is a tool used to deduce the type of an expression and can be used to define type aliases.

int i = 42;
decltype(i) j = 43;  // j has type int

noexcept Specifier

The noexcept specifier is used to indicate that a function will not throw exceptions or to specify whether an expression may throw exceptions.

void f() noexcept { /* Will not throw exceptions */ }
bool g() noexcept { /* Returns whether exceptions may be thrown */ }

Variadic Templates (template<typename… Args>)

Variadic templates allow the creation of templates that can accept an arbitrary number of type parameters.

template<typename... Args>
void print(Args... args) {
    (std::cout << ... << args) << '\n';  // Print all arguments
}

Non-Type Template Parameters

Template parameters are not limited to types; they can also be constant expressions.

template<int N>
struct PowerOfTwo {
    static constexpr int value = 1 << N;
};

Strongly Typed Enumerations (enum class)

Strongly typed enumerations prevent implicit conversions between different enumeration types, improving type safety.

enum class Color { Red, Green, Blue };

Initializer Lists (std::initializer_list)

std::initializer_list allows functions to accept initializer lists as parameters.

void print(std::initializer_list<int> list) {
    for (auto i : list) {
        std::cout << i << ' ';
    }
    std::cout << '\n';
}

Range-based for Loop

The range-based for loop simplifies traversal of containers.

std::vector<int> v = {1, 2, 3};
for (auto i : v) {
    std::cout << i << ' ';
}

New Features and Characteristics in C++14

Extension of constexpr

In C++11, constexpr was mainly used to define compile-time constants. In C++14, the scope of constexpr has been extended to allow more complex control flow and local variable definitions. This means loops, conditional statements, etc., can be used in compile-time constant expressions.

constexpr int factorial(int n) {
    return (n <= 1) ? 1 : n * factorial(n - 1);
}

constexpr int fact = factorial(5);  // Compile-time constant

Generic Lambda Expressions

C++14 allows Lambda expressions to use automatic type deduction, making Lambda expressions more generic.

auto lambda = [](auto x, auto y) { return x + y; };
int sum = lambda(1, 2);  // Can accept parameters of any type

deprecated Attribute

[[deprecated]] is an attribute used to mark a function or type as deprecated. When the compiler detects the use of a function or type with this attribute, it will generate a warning.

[[deprecated("Use function2 instead")]] void function1() {}

void function2() {}

int main() {
    function1();  // Compiler will issue a warning
    return 0;
}

Direct Initialization of Arrays

C++14 allows the use of braces {} to directly initialize arrays, making the syntax more consistent.

int arr[] = {1, 2, 3};  // Directly initialize array

Digit Separators

C++14 introduced the digit separator _, which can be used in long integer literals to increase readability.

long long big_number = 1'000'000'000;  // Use digit separator to increase readability

Binary Literals

C++14 supports binary literals, making it easier to write binary numbers.

int binary = 0b1010;  // Binary literal

General Attributes

C++14 allows the use of general attributes on types, enabling additional information to be added to types.

[[nodiscard]] int get_value() { return 42; }  // Suggest not to ignore return value

std::make_unique

std::make_unique is a helper function added in C++14 for creating std::unique_ptr objects, making it more convenient to create smart pointers.

#include <memory>

int main() {
    auto ptr = std::make_unique<int>(42);  // Create unique_ptr
    return 0;
}

std::exchange

std::exchange is an atomic operation used to exchange the value of an object and return the old value.

#include <atomic>

std::atomic<int> counter{0};
int old_value = std::exchange(counter, 1);  // Exchange the value of counter and get the old value

std::optional

Although std::optional was officially introduced in C++17, its concept already existed in C++14. std::optional provides an elegant way to handle values that may not exist.

#include <optional>

int main() {
    std::optional<int> opt;
    if (opt) {
        // opt has a value
    } else {
        // opt has no value
    }
    return 0;
}

New Features and Characteristics in C++17

std::optional

std::optional is a container used to represent a state that may or may not contain a value. It provides a type-safe way to handle values that may not exist.

#include <optional>

int main() {
    std::optional<int> value;
    if (value) {
        // value has a value
    } else {
        // value has no value
    }
    return 0;
}

std::variant

std::variant is a container that can store one of multiple types, similar to a union, but it ensures type safety and resource management.

#include <variant>

int main() {
    std::variant<int, float, std::string> v(42);
    if (std::holds_alternative<int>(v)) {
        // v contains an int type
    }
    return 0;
}

std::any

std::any is a container that can store any type, providing a type-safe access mechanism.

#include <any>

int main() {
    std::any a(42);
    if (a.type() == typeid(int)) {
        // a contains an int type
    }
    return 0;
}

std::string_view

std::string_view provides a lightweight string reference for viewing strings without owning them, improving performance.

#include <string_view>

int main() {
    std::string_view sv("Hello");
    return 0;
}

Automatic Type Deduction in if and while Statements

if and while statements can now use auto to deduce variable types.

auto s = "Hello";
if (auto p = s.c_str(); p != nullptr) {
    // Use p
}

Enhancement of constexpr

constexpr has been further enhanced in C++17, allowing more functions and expressions to be computed at compile time.

constexpr int abs(int x) {
    return x >= 0 ? x : -x;
}

constexpr int a = abs(-42);  // Compile-time constant expression

likely and unlikely Attributes

These attributes can hint to the compiler about branch prediction, helping to optimize code.

[[likely]] bool is_positive(int x) {
    return x > 0;
}

[[unlikely]] bool is_negative(int x) {
    return x < 0;
}

std::apply

The std::apply function can apply the elements of a tuple or pair to a function.

#include <tuple>
#include <utility>

int main() {
    auto t = std::make_tuple(1, 2, 3);
    std::apply([](int a, int b, int c) { return a + b + c; }, t);  // Result is 6
    return 0;
}

std::from_chars

std::from_chars is a new function for converting strings to numeric values, providing better error handling.

#include <charconv>

int main() {
    char str[] = "12345";
    int val;
    auto res = std::from_chars(str, str + sizeof(str), val);
    if (res.ec == std::errc()) {
        // Conversion successful
    }
    return 0;
}

std::byte

The std::byte type provides a type-safe way to handle byte data.

#include <cstddef>

int main() {
    std::byte b = std::byte{0x01};
    return 0;
}

std::shared_timed_mutex

std::shared_timed_mutex is a mutex that supports shared and exclusive locks and can set timeouts.

#include <mutex>

int main() {
    std::shared_timed_mutex mtx;
    std::unique_lock<std::shared_timed_mutex> lock(mtx, std::defer_lock);
    if (lock.try_lock_until(std::chrono::steady_clock::now() + std::chrono::seconds(1))) {
        // Lock acquired successfully
    }
    return 0;
}

std::make_from_tuple

std::make_from_tuple is a helper function that can create an object from a tuple.

#include <tuple>

struct Point {
    int x, y;
};

int main() {
    auto t = std::make_tuple(1, 2);
    auto p = std::make_from_tuple<Point>(t);
    return 0;
}

Structured Bindings

Structured bindings allow destructuring data from a tuple or initializer_list.

#include <tuple>

int main() {
    auto [a, b] = std::make_tuple(1, 2);
    return 0;
}

std::is_aggregate

std::is_aggregate can be used to determine whether a type is an aggregate type.

#include <type_traits>

int main() {
    struct A { int x; };  // Aggregate type
    static_assert(std::is_aggregate_v<A>);
    return 0;
}

std::filesystem

Although std::filesystem is part of the technical specification and was released as part of the library in C++17, it is an important feature of C++17, providing an API for filesystem operations.

#include <filesystem>

int main() {
    namespace fs = std::filesystem;
    if (fs::exists("example.txt")) {
        // File exists
    }
    return 0;
}

New Features and Characteristics in C++20

Concepts

Concepts are one of the most revolutionary features in C++20. They allow you to define type constraints in template metaprogramming. Concepts make template code more expressive, easier to understand, and better at catching errors at compile time.

concept std::integral auto add_one(auto x) {
    return x + 1;
}

Ranges

The ranges library provides a safer and more efficient way to handle iteration and algorithms. It is based on iterators but provides a higher-level abstraction.

#include <range/v3/all.hpp>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    auto sum = vec | ranges::view::all | ranges::actions::accumulate;
    return 0;
}

Coroutines

Coroutines allow the creation of lightweight cooperative programs and can be used to implement asynchronous programming patterns such as generators and coroutines.

#include <coroutine>

struct generator {
    struct promise_type {
        generator get_return_object() { return {}; }
        std::suspend_never initial_suspend() { return {}; }
        std::suspend_never final_suspend() noexcept { return {}; }
        void unhandled_exception() {}
        void return_void() {}
    };

    generator(generator&&) = default;
    generator get_executor() { return *this; }
};

generator co_yield(int x) {
    co_yield x;
}

Modules

Modules are an important feature in C++20. They provide a new way to organize and share code, replacing the traditional header file preprocessing mechanism.

// module Hello;
// import std.core;

// export module Hello;

// export void greet() {
//     std::cout << "Hello, World!" << std::endl;
// }

Template Lambda Expressions

In C++20, Lambda expressions can use template syntax, making Lambda functions more generic.

auto lambda = []<typename T>(T x, T y) { return x + y; };
int sum = lambda(1, 2);  // Can accept parameters of any type

Explicit Capture of this

In C++20, Lambda expressions no longer implicitly capture this by default and must explicitly specify it.

class MyClass {
public:
    void doSomething() {
        auto lambda = [=, this] { /* Use this */ };
    }
};

consteval and constinit

consteval is used to define compile-time constant functions, and constinit is used to define variables that are constant at initialization.

consteval int factorial(int n) {
    return (n <= 1) ? 1 : n * factorial(n - 1);
}

constinit int fact = factorial(5);  // Compile-time constant

requires Keyword

The requires keyword is used to specify requirements in concept constraints.

template <requires std::integral<T>> T add_one(T x) {
    return x + 1;
}

alignas(auto) and alignof(auto)

These keywords can be used to automatically deduce alignment and alignment requirements.

alignas(auto) int a;
alignof(auto) int b;

std::span

std::span provides a safe view for accessing array contents without owning the array.

#include <span>

int main() {
    int arr[] = {1, 2, 3};
    std::span<int> span(arr);
    return 0;
}

std::format

std::format is a string formatting tool similar to Python, making string formatting simpler.

#include <format>

int main() {
    std::string s = std::format("Hello, {}!", "World");
    return 0;
}

std::ranges::join

std::ranges::join allows multiple ranges to be joined into one range.

#include <ranges>

int main() {
    std::vector<int> v1 = {1, 2, 3};
    std::vector<int> v2 = {4, 5, 6};
    auto joined = std::ranges::join(v1, v2);
    return 0;
}

std::launder

std::launder is used to bypass certain optimizations, ensuring that the memory pointed to by a pointer is valid.

#include <bit>

int main() {
    int* p = nullptr;
    std::launder(p);  // Ensure p points to valid memory
    return 0;
}

std::source_location

std::source_location provides source code location information for debugging and logging.

#include <source_location>

int main() {
    auto loc = std::source_location::current();
    std::cout << "Current location: " << loc.file_name() << ":" << loc.line() << std::endl;
    return 0;
}

Enhancements to the std::pmr Library

C++20 enhanced the std::pmr (polymorphic memory resource) library, providing more memory resource options.

#include <memory_resource>

int main() {
    std::pmr::monotonic_buffer_resource res;
    std::pmr::polymorphic_allocator<int> alloc(&res);
    return 0;
}
Share your love