c++ - 自动和自动&和常量

标签 c++ c++11 constants auto

auto x1 = exp1;
auto& x2 = exp2;

我是否正确理解,使用 auto (x1) 声明的变量永远不会是 const,即使 exp1const (例如,返回 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/

相关文章:

c++ - 当我尝试在启用推理引擎的情况下编译OpenCv时,出现错误

c++ - 使用标准库中的代码停止在 Turbo C++ 中退出输出

c++ - 安置新的和继承

c++ - 使用 C++0x decltype 绕过访问说明符

iphone - 在 objective-c 中创建像类属性一样调用的常量? (例如 classA.KEY_FOR_ITEM1)

C++ Static_cast 指向虚拟基类的指针

c++ - 异常安全构造函数

c++ - 了解临时对象上下文中的函数调用

java - JAVA中如何根据环境动态选择配置?

C++ - 常量变量,这是一个正确的术语吗?