当我们使用
auto
来推断对象的类型时,顶级 const
会被忽略,例如
const int i = 0; //i is top-level const
auto j = i; //j is an int
但是,低级别的
const
永远不会被忽略,例如
const int * ptr = nullptr //ptr is low-level const;
auto ptr2 = ptr; //ptr2 is also const int*
但是当我定义低级
const
引用并使用 auto
时,它会丢失 const
int var;
const int &ref = var; //ref is low-level const reference
auto ref2 = ref; //ref2 is int&!`
为什么会出现这种行为?
尝试过VS2017 C++编译器
const int
是一个值,复制一个值时不确定你想要它是const
,所以auto
将被推导为int
。
像
const int*
这样的指针是不同的东西:如果源是const
,你不能在它上面放置非常量指针,因为你绕过了它的常量性,因此auto
将不得不保存常量性.
引用在创建后被视为值,因此除非将其指定为
auto&
,否则它将被视为值,并且将是 int