您的位置:首页 > 编程语言 > C语言/C++

C++11 auto关键字介绍

2015-12-27 16:09 344 查看

C++11 auto关键字介绍

1.auto关键字的作用

提示编译器对变量的类型进行自动推导,能够增加代码的灵活度,减少代码的书写量

2.auto关键字的注意事项

当不声明为引用时,auto的初始化表达式即使是引用,编译器也不会将其推导为对应的类型的引用。在实际编码中一定要注意。具体分析请见 auto关键字的推导规则

在实际编码中,建议显式的声明指针和引用。这样既能够增强代码的可读性,也能够避免引用失效的情况。

int x = 25;
auto *a = &x;//显式的声明指针
auto &b = x;//显式的声明引用


3.auto关键字的使用场景

3.1自动推导stl容器的迭代器

vector<int> aa;
for (vector<int>::iterator iter = aa.begin();
iter != aa.end();
++iter){}
//等同于
for (auto iter = aa.begin(); iter != aa.end();++iter){}


3.2增强代码的灵活性

class Window
{
public:
static int get()
{
return 1;
}
};

class Bar
{
public:
static string get()
{
string str = "hello auto";
return str;
}
};

template<class T>
void Func()
{
auto val = T::get();
// ...
}

int main()
{
Func<Window>();
Func<Bar>();
return 0;
}


4.auto关键字的推导规则

当不声明为引用时,auto的初始化表达式即使是引用,编译器也不会将其推导为对应的类型的引用,auto的推导结果等同于初始化表达式去除引用和const限定符后的类型。见d

当声明为引用时,auto的推导结果将保留初始化表达式的const或者非const属性,见c,g,h

初始化表达式为指针类型时,auto的推导结果能够推导出正确的类型,其结果能够保留初始化表达式的const或非const属性,见a,b,i,j

#include <iostream>
using namespace std;
int main()
{
int x = 0;
auto *a = &x;//类型为int*,auto为int
++(*a);
cout << "after ++(*a) *a:" << *a << " x:" << x << endl;
auto b = &x;//类型为int*,auto为int*
++(*b);
cout << "after ++(*b) *b:" << *b << " x:" << x << endl;
auto &c = x;//类型为int&,auto为int
++c;
cout << "after ++c c:" << c << " x:" << x << endl;
auto d = c;//类型为int,auto为int
++d;
cout << "after ++d d:" << d << " x:" << x << endl;

const auto e = x;//类型为const int,auto为int
//++e; error C3892: “e”: 不能给常量赋值
auto f = e;//类型为int,auto为int
++f;
cout << "after ++f f:" << f << " x:" << x << endl;
const auto &g = x;//类型为const int&,auto为int
//++g; error C3892: “g”: 不能给常量赋值
auto& h = g;//推导为const int&,auto为const int
//++h; error C3892: “g”: 不能给常量赋值
auto *i = &e;
//++(*i);  error C3892: “i”: 不能给常量赋值
auto j = i;
//++(*j); error C3892: “j”: 不能给常量赋值
return 0;
}


运行结果如下:



5.auto关键字的使用限制

5.1不能用于函数参数

//void func(auto a = 1){} error C3533: 参数不能为包含“auto”的类型


5.2不用用于非静态成员变量

struct Foo
{
//auto v1 = 0;  error C2853: “v1”: 非静态数据成员不能具有包含“auto”的类型
static const auto  v0 = 25;
};


5.3无法定义数组

int arr[10] = { 0 };
//auto rr[10] = arr; error C3318: “auto [10]”: 数组不能具有其中包含“auto”的元素类型


5.4无法推导出模板参数

vector<int> aa;
//vector<auto> bb = aa; error C3539 : 模板参数不能为包含“auto”的类型


6.感谢

本文为《深入应用C++11代码优化与工程级应用》的读书笔记。感谢该书作者的辛勤劳动和分享。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: