C++14之初窥

之前C++标准委员会憋了好多年的大招,终于憋出了C++11.而且C++11也不负众望,带来了很多的新特性的同时也修补了许多C++原先的一些不足,比如右值引用的问题.而这次C++标准委员会却很快就通过了最新的C++14标准

因此这次改动应该就只是修补了原先C++11上的一些不足,正如C++之父Bjarne Stroustrup所言:

C++14 is simply the completion of the work that became C++11. When you finish a huge project, there are things you know need to be done, but you can’t add them if you want to ship on time. Inevitably, there are refinements that you don’t realize you need until you can try the whole “product” for real. C++14 adds such features and refinements to C++11. More dramatic improvements are targeted for C++17.

所以C++14相比与C++11而言,它的改动是很少.因此如果希望C++有大的改进,那就得期待下一个版本C++17了.

这次的改动不大,所以亮点比较少,我觉得比较重要的应该就是auto的改进,lambda的改进和constexpr的改进了.


auto的自动推导

C++14完善了C++11中的auto功能,支持函数返回类型的自动推导.

auto Correct(int i){
  if (i == 1)
    return i;             // return type deduced as int
  return Correct(i-1)+i;  // ok to call it now
}

constexpr表达式

上半年还专门写过constexpr这个常量表达式,发现它存在挺大的限制,这次C++14则使其支持范围更广:
1. 支持staticthread_local类型的变量.
2. 已经无需在声明时就初始化其值.
3. 表达式可以放在ifswitch语句中(不包括goto).
4. 可以放在循环语句中,包括C++11 for的range-based.
5. 允许在常量表达式计算中对生存期开始的变量进行赋值(这个我觉得才是最重要的).

lambda表达式

  1. 鉴于C++14对于auto的改进,因此lambda表达式可以做到支持真正的泛型函数了.
auto lambda = [](auto x, auto y) {return x + y;};
  1. 以及捕获值的初始化:
auto lambda = [value = 1] {return value;};
  1. 新标准中的std::move函数也可用于捕获Lambda表达式中的变量,这是通过移动对象而非复制或引用对象实现的,效率很高:
std::unique_ptr<int> ptr(new int(10));
auto lambda = [value = std::move(ptr)] {return *value;};