homework-07

C++ 11新特性:

Modern C++ emphasizes:

  • Stack-based scope instead of heap or static global scope.

  • Auto type inference instead of explicit type names.

  • Smart pointers instead of raw pointers.

  • std::string and std::wstring types (see <string>) instead of raw char[] arrays.

  • Standard template library (STL) containers like vector, list, and map instead of raw arrays or custom containers. See <vector>, <list>, and <map>.

  • STL algorithms instead of manually coded ones.

  • Exceptions, to report and handle error conditions.

  • Lock-free inter-thread communication using STL std::atomic<> (see <atomic>) instead of other inter-thread communication mechanisms.

  • Inline lambda functions instead of small functions implemented separately.

  • Range-based for loops to write more robust loops that work with arrays, STL containers, and Windows Runtime collections in the form for ( for-range-declaration : expression ). This is part of the Core Language support. For more information, see Range-based for Statement (C++).

其中,令我最感兴趣的两条就是自动变量推断和lambda表达式了

Lambda表达式允许你在本地定义函数,即在调用的地方定义,从而消除函数对象产生的许多安全风险,Lambda表达式的格式如下:

[capture](parameters)->return-type {body} 

[]里是函数调用的参数列表,表示一个Lambda表达式的开始,让我们来看一个Lambda表达式例子:

int main()  
{  
    char s[]="Hello World!";  
    int Uppercase = 0; //modified by the lambda  
    for_each(s, s+sizeof(s), [&Uppercase] (char c) {  
        if (isupper(c))  
            Uppercase++;  
    });  
    cout<< Uppercase<<" uppercase letters in: "<< s<<endl;  
} 

这个就是将一个字符串转化为大写。原来要另外定义一个函数。现在直接就能拿来用了。(github上有代码)

自动类型推断

在以往的C++中,声明对象时,必须指定对象的类型,然而,在许多情况下,对象的声明包括在初始化代码中,C++11利用了这个优势,允许声明对象时不指定类型:

auto x=0; //x has type int because 0 is int  
auto c='a'; //char  
auto d=0.5; //double  
auto national_debt=14400000000000LL;//long long 

关键字auto不是什么新生事物,我们早已认识,它实际上可以追溯到前ANSI C时代,但是,C++11改变了它的含义,auto不再指定自动存储类型对象,相反,它声明的对象类型是根据初始化代码推断而来的,C++11删除了 auto关键字的旧有含义以避免混淆,C++11提供了一个类似的机制捕捉对象或表达式的类型,新的操作符decltype需要一个表达式,并返回它的类型。

最后。。依旧是吐槽:

    我已经不知道c++的发展方向是哪儿了。到底是向java走,还是向java走。和c的区别越来越大,也就意味着优秀的c++编译器越来越难以写作。Bjarne Strou-strup一直说c++最大的问题就是没有一个好的编译器。可我觉得,像他这样挖坑,又不肯向java看齐,也难怪没有好的编译器。这就像遇到一道数学题,发出感叹:“我如果知道这道题的答案该多好”一样,个人觉得没啥意义。要不是我喜欢qt还有一些opengl的东西,我对c++没啥热情。如果需要运算,我就用c,如果需要界面,我就用java或者别的。c++唯一能吸引我的就是方便的向量之类的。可是现在c++野心太大,以至于让我感到有点忽略本源了。

    个人愚见,以上。

原文地址:https://www.cnblogs.com/yzong/p/3417726.html