auto x1 = exp1;
auto& x2 = exp2;
我是否正确理解,使用 auto
(x1) 声明的变量永远不会是 const
,即使 exp1
是 const
(例如,返回 const
的函数)。当使用 auto&
时,如果 exp2 将是 const,则 (x2) 将是 const。即使 auto 是一个指针。
auto it = find(cont.cbegin(), cont.cend(), value);
尽管我使用了 cbegin 和 cend,但它仍然是非常量迭代器,并且我应该编写为 const_iterator
const auto it1 = find(cont.cbegin(), cont.cend(), value);
最佳答案
Do I understand correctly that variables declared with auto (x1) will never be const
正确。
When with auto&(x2) will be const if exp2 will be const.
引用永远不是 const;推荐人的简历不能合格。 x2
可以是对 const 的引用。
auto it = find(cont.cbegin(), cont.cend(), value);
Here despite I use cbegin and cend it will be non-const iterator
it
将是 const_iterator 类型的非常量限定对象。
const auto it1 = find(cont.cbegin(), cont.cend(), value);
it1
将是 const_iterator 类型的 const 限定对象。
通过 const_iterator 间接提供对 const 的引用(通常),因此您无法修改指向的对象。
const 对象(通常)不能被修改。因此,例如,您无法增加 const 限定迭代器。
关于c++ - 自动和自动&和常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68379890/