C++11 auto自动类型推导

1.auto类型推导

auto x  =5;			//正确,x是int类型
auto pi = new auto(1);		//正确,批是int*
const auto* v = &x, u = 6;	//正确,v是const int*类型,u是const int
static auto y = 0.0;		//正确,y是double类型
auto int r;			//错误,auto不再表示存储类型的指示符
auto s;				//错误,auto无法推导出s的类型(必须马上初始化)

auto并不能代表一个实际的类型声明(上面s编译错误),只是一个类型声明的“占位符”。使用auto声明的变量必须马上初始化,以让编译器推断出它的类型,并且在编译时将auto占位符替换为真正的类型。

2.auto推导规则

int x = 0;
auto *a = &x;		//a->int*,auto被推导为int
auto b = &x;		//b->int*,auto被推导为int*
auto &c = x;		//c->int&,auto被推导为int
auto d = c;		//d->int, auto被推导为int
 
const auto e = x;		//e->const int
auto f = e;			//f->int
 
const auto& g = x;		//e->const int&
auto& h = g;			//g->const int&

(1)当不声明为指针或是引用时,auto的推导结果和初始化表达式抛弃引用和const属性限定符后的类型一致
(2)当声明为指针或是引用时,auto的推导结果将保持初始化表达式的const属性

参考
https://blog.csdn.net/m_buddy/article/details/72828576

原文地址:https://www.cnblogs.com/hunter-w/p/13210028.html