auto 还有一种特殊用法:后置返回值类型声明
auto foo() -> 返回值类型声明 {}
decltype 相比于 auto,也是在编译阶段可以推导出引用类型,配合 auto 使用,可以更加简洁,同时,也不需要表达式
int x = 0;
decltype(x) x1; // 没有初始化,可以推导出 x1 的类型是 int
decltype(x)& x2 = x; // x2 是 int&,引用必须赋值
decltype(x)* x3; // 推导为int,x3是int*
decltype(&x) x4; // 推导为int*,x4是int*
decltype(&x)* x5; // 推导为int*,x5是int**
decltype(x2) x6 = x2; // 推导为int&,x6是int&,引用必须赋值
decltype(auto) x7 = (x); // 更简洁的写法 auto 相当于右侧表达式的占位,直接通过表达式推导,(expr) 是引用类型
// 需要加上volatile修饰,运行时才能看到效果
const volatileint MAX_LEN = 1024;
auto ptr = (int*)(&MAX_LEN);
*ptr = 2048;
cout << MAX_LEN << endl; // 输出2048
const 还有修饰的位置不同,其含义也不同
string name = "abc";
const string* ptr1 = &name; // 表示指针的内容不可改
// *ptr1 = "b" // raise error
string* const ptr2 = &name; // 表示指针不能变,数据可变
class Demo {
int a() const; // 表示这个过程是幂等的,不会修改对象的状态,即隐式的 const this
const int b(); // 返回一个 const int 类型的值
}