C++ auto关键字

1、auto关键一的优点

auto关键字可以知道编译器根据变量的初始表达式来推倒变量的类型,使用auto主要有一下方面的优点:

(1) 鲁棒性:当表达式的类型改变,包括函数返回值类型的转变,程序依然可以正确运行,不需要改变所有的变量类型。

(2) 性能:可以消除类型转换。

(3) 易用性:不用担心类型名错误

(4) 高效:会让程序更加有效率

auto是一个类型占位符,本身并不是一个类型,所以不可以使用sizeof或typeid

2、auto关键字会去掉变量的reference,const,volite volatile 修饰符

// cl.exe /analyze /EHsc /W4
#include <iostream>
 
using namespace std;
 
int main( )
{
    int count = 10;
    int& countRef = count;
    auto myAuto = countRef;
 
    countRef = 11;
    cout << count << " ";
 
    myAuto = 12;
    cout << count << endl;
}

在上面的代码中,myAuto是个int,不是int &,输出的结果是 11 11,不是11 12。

3、auto使用实例

1、下面的两个声明等价,使用auto更简便。

int j = 0;  // Variable j is explicitly type int.
auto k = 0; // Variable k is implicitly type int because 0 is an integer.
map<int,list<string>>::iterator i = m.begin(); 
auto i = m.begin(); 

2、对于for循环,使用auto更加简洁

// cl /EHsc /nologo /W4
#include <deque>
using namespace std;

int main()
{
    deque<double> dqDoubleData(10, 0.1);

    for (auto iter = dqDoubleData.begin(); iter != dqDoubleData.end(); ++iter)
    { /* ... */ }

    // prefer range-for loops with the following information in mind
    // (this applies to any range-for with auto, not just deque)

    for (auto elem : dqDoubleData) // COPIES elements, not much better than the previous examples
    { /* ... */ }

    for (auto& elem : dqDoubleData) // observes and/or modifies elements IN-PLACE
    { /* ... */ }

    for (const auto& elem : dqDoubleData) // observes elements IN-PLACE
    { /* ... */ }
}

3、auto可以用于new 和指针

double x = 12.34;
auto *y = new auto(x), **z = new auto(&x);

4、在一个声明语句中可以声明多个变量

auto x = 1, *y = &x, **z = &y; // Resolves to int.
auto a(2.01), *b (&a);         // Resolves to double.
auto c = 'a', *d(&c);          // Resolves to char.
auto m = 1, &n = m;            // Resolves to int.

5、auto可以用于条件运算符

int v1 = 100, v2 = 200;
auto x = v1 > v2 ? v1 : v2;  

6、在下面代码中x为int,y为const int &,fp为函数指针

int f(int x) { return x; }
int main()
{
    auto x = f(0);
    const auto & y = f(1);
    int (*p)(int x);
    p = f;
    auto fp = p;
    //...
}

 

posted @ 2014-11-04 16:51  践行者123  阅读(421)  评论(0编辑  收藏  举报