【发布时间】:2021-09-23 12:57:27
【问题描述】:
auto x1 = exp1;
auto& x2 = exp2;
我是否正确理解使用auto (x1) 声明的变量永远不会是const,即使exp1 是const(例如,返回const 的函数)。当使用auto&(x2) 时,如果 exp2 为 const,则为 const。即使 auto 是一个指针。
auto it = find(cont.cbegin(), cont.cend(), value);
尽管我使用了 cbegin 和 cend,但它会是非常量迭代器,而要成为 const_iterator 我应该写
const auto it1 = find(cont.cbegin(), cont.cend(), value);
【问题讨论】:
-
cbegin(和cend)无论如何都会返回const_iterator。 -
"When with auto&(x2) will be const if exp2 will be const." 不,
auto永远不会是const,或引用,除非明确说明指定(即auto const& x2)。没有写答案,因为我懒得从标准中找到引用。 -
const_iterator不是常量。const auto是const const_iterator,而不是const_iterator。 -
限定符如何通过 C++ 中的类型系统隐式关联有点令人费解,而且与模板更复杂。请记住,
auto是由编译器推导出的 type,它将是它自己的对象。但是auto&是一个引用,并且限定符对引用更粘,因为它们是别名。 (正交,但也增加了混乱:const不传递。)