20. 1 Modules
export and import
20. 2 Concepts
template type requires
20. 3 Lambda Templates
[]<>(){}
20. 4 [likely] and [unlikely] Attributes
if (choice) [[likely]]
20. 5 Ranges
ranges::sort(vec);
20. 6 Coroutines
co_await
20. 7 std: : span
span
20. 8 Mathematical Constants
numbers::log2e
1 C++11
C++11 is an ISO C++ standard, published in 2011. To compile for this standard, add the -std=c++11 flag to a command-line compilation string if compiling with g++ or clang. If using Visual Studio, choose Project / Options / Configuration Properties / C/C++ / Language / C++ Language Standard and choose C++11. New Visual Studio versions already support this standard out of the box.
11.1 Automatic Type Deduction
This standard introduces the auto keyword which deduces the type of the variable based on the variable’s initializer:
int main()
{
auto mychar = 'A';
auto myint = 123 + 456;
auto mydouble = 456.789;
}
11.2 Range-based Loops
The range-based loops allow us to iterate over the range, such as C++ standard-library containers:
#include
#include
int main()
{
std::vector v = { 10, 20, 40, 5, -20, 75 };
for (auto el : v)
{
std::cout << el << '
';
}
}
The range-based for loop is of the following form: for (type element : container). This is read as for each element in a container (do something).
11.3 Initializer Lists
Initializer lists, represented by braces { } allow us to initialize objects in a uniform way. We can initialize single objects:
int main()
{
int x{ 123 };
int y = { 456 };
double d{ 3.14 };
}
And containers:
#include
int main()
{
std::vector v = { 1, 2, 3, 4, 5 };
}
List initialization also prevents narrowing conversions. If we tried to initialize our integer object with a double value inside the initializer list, the compilation would fail:
int main()
{
int x = { 123.45 }; // Error, does not allowing narrowing
}
When initializing our objects, we should prefer initializer lists {} to old-style parentheses ().
11.4 Move Semantics
C++ 11 standard introduces the move semantics for classes. We can initialize our objects by moving the data from other objects. This is achieved through move constructors and move assignment operators. Both accept the so-called rvalue reference as an argument. Lvalue is an expression that can be used on the left-hand side of the assignment operation. rvalues are expressions that can be used on the right-hand side of an assignment. The rvalue reference has the signature of some_type&&. To cast an expression to an rvalue reference, we use the std::move function. A simple move constructor and move assignment signature are:
class MyClass
{
public:
MyClass(MyClass&& otherobject) // move constructor
{
//implement the move logic here
}
MyClass& operator=(MyClass&& otherobject) // move assignment operator
{
// implement the copy logic here
return *this;
}
};