auto与decltype区别主要有三个方面:
- auto类型计算后推断,decltype不进行计算;
- auto会忽略掉顶层const,保留下层const;decltype全部进行保留;
- 与auto不同,decltype结果类型与表达式形式密切相关;加上括号与不加括号不同。
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
int a = 3;
auto c1 = a;
decltype(a) c2 = a;
decltype((a)) c3 = a;
const int d = 5;
auto f1 = d;
decltype(d) f2 = d;
cout << typeid(c1).name() << endl;
cout << typeid(c2).name() << endl;
cout << typeid(c3).name() << endl;
cout << typeid(f1).name() << endl;
cout << typeid(f2).name() << endl;
c1 ++;
c2 ++;
c3 ++;
f1 ++;
//f2 ++;
cout << a << " " << c1 << ' ' << c2 << " " << c3 << ' ' << f1 << ' ' << f2 << endl;
}
auto的推断策略
推断的精髓在右值,根据右值的形式,简单的简单推断和复合推断。
引用指向指针的时候,要注意隐藏的const 输定,需要用const auto进行声明
例如下面代码
int i=100;
cosnt auto ci=23;//right
auto ci=23;//wrong
auto &test_i=i;//正确,test_i 是int 型,因为i是int型
const auto &p=&i;//right,变量定义后,马上为其分配存储,变量名i与地址&i进行了束定,绑死在一起,是一种隐含的const关系。
auto &q=&i;//wrong,
auto &x=p;//right
完整测试代码
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
int i=1,&ri=i;
const int ci=21,&rci=ci;
//以下全部为int
auto a=1;
auto b=i;
auto c=ri;
auto d=ci;
auto e=rci;
auto f=&i;//整型指针
auto g=&ci;//指向常量的指针,下层的const不可忽略
//以下是复合类型(引用)
//auto &ra=1;//错误
auto &rb=i;rb++;
auto &rc=ri;rc++;
auto &rd=ci;//整型常量, const int 类型
auto &re=rci;//整型常量, const int 类型
//auto &k=21;
const auto &k=21;
const auto ck=ci;
const auto cki=i;
//一样的
auto *p=&ci;
auto q=&ci;
cout<<typeid(p).name()<<' '<<q<<endl;
cout<<typeid(q).name()<<' '<<p<<endl;
return 0;
}