Content #
编译器会自动调用析构函数,包括在函数执行发生异常的情况。在发生异常时对析构函数的调用,还有一个专门的术语,叫栈展开(stack unwinding)。
Not every unary or binary function that returns a Boolean value is a valid predicate.
In addition, the STL requires that predicates be stateless, meaning that they should always yield the same result for the same value. This rules out functions that modify their internal state when they are called.
Since C++11, the standard uses the term function object for every object that can be used as a function call. 下面所列均可称为function object:
1.Function objects are “functions with state.” 2.Each function object has its own type. 3.Function objects are usually faster than ordinary functions.
...int id = 0;
auto f = [id] () mutable {
std::cout << "id: " << id << std::endl;
++id;
};
id = 42;
f();
f();
f();
std::cout << id << std::endl;
程序输出: id: 0 id: 1 id: 2 42
改写成重载操作符():
class {
private:
int id;
public:
void operator() () {
std::cout << "id: " << id << std::endl;
++id;
}
};
By using the new decltype keyword, you can let the compiler find out the type of an expression.
下面的C++ Template声明的函数,注意其返回值类型声明。
template <typename T1, typename T2>
decltype(x + y) add(T1 x, T2 y);
现有如下C++声明的map:
std::map<std::string, float> coll;
用C++11的decltype关键词来声明map中的value_type变量elem:
decltype(coll)::value_type elem;