11.5 Lambda Expressions
Lambda expressions are anonymous function objects. They allow us to write a short code snippet to be used as a standard-library function predicate. Lambdas have a capture list, marked by [ ] where we can capture local variables by reference or copy, parameter list with optional parameters marked with ( ), and a lambda body, marked with { }. An empty lambda looks like [] () {};. A simple example of counting only the even numbers in a set using the lambda as a predicate:
#include
#include
#include
int main()
{
std::vector v = { 1, 2, 3, 4, 5 };
auto counteven = std::count_if(std::begin(v), std::end(v),
[](int x) {return x % 2 == 0; }); // lambda expression
std::cout << "The number of even vector elements is: " << counteven;
}
11.6 The constexpr Specifier
The constexpr specifier promises the variable or a function can be evaluated during compile-time. If the expression can not be evaluated during compile-time, the compiler emits an error:
int main()
{
constexpr int n = 123; //OK, 123 is a compile-time constant // expression
constexpr double d = 456.78; //OK, 456.78 is a compile-time constant // expression
constexpr double d2 = d; //OK, d is a constant expression
int x = 123;
constexpr int n2 = x; //compile-time error
// the value of x is not known during // compile-time
}
11.7 Scoped Enumerators
Enumerator使用时(右值)需显式声明类作用域。
The C++11 standard introduces the scoped enumerators . Unlike the old enumerators, the scoped enumerators do not leak their names into the surrounding scope. Scoped enums have the following signature: enum class Enumerator_Name {value1, value2 etc} signature. A simple example of a scoped enum is:
enum class MyEnum
{
myfirstvalue,
mysecondvalue,
mythirdvalue
};
int main()
{
MyEnum myenum = MyEnum::myfirstvalue;
}
11.8 Smart Pointers
智能指针使用类模板封装原生指针及类指针操作及在自定义析构函数中在适当的时机调用delete或delete[](包括申请的堆内存的所有权控制或引用计数)。
Smart pointers point to objects, and when the pointer goes out of scope, the object gets destroyed. This makes them smart in the sense that we do not have to worry about manual deallocation of allocated memory. The smart pointers do all the heavy lifting for us.
There are two kinds of smart pointers, the unique pointer with an std::unique_ptr signature and a shared pointer with an std::shared_ptr signature. The difference between the two is that we can have only one unique pointer pointing at the object. In contrast, we can have multiple shared pointers pointing at an object. When the unique pointer goes out of scope, the object gets destroyed, and the memory is deallocated. When the last of the shared pointers pointing at our object goes out of scope, the object gets destroyed. The memory gets deallocated.
A unique pointer example:
#include
#include
int main()
{
std::unique_ptr p(new int{ 123 });
std::cout