【问题标题】:auto and auto& and constauto 和 auto& 和 const
【发布时间】:2021-09-23 12:57:27
【问题描述】:
auto x1 = exp1;
auto& x2 = exp2;

我是否正确理解使用auto (x1) 声明的变量永远不会是const,即使exp1const(例如,返回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 autoconst const_iterator,而不是 const_iterator
  • 限定符如何通过 C++ 中的类型系统隐式关联有点令人费解,而且与模板更复杂。请记住,auto 是由编译器推导出的 type,它将是它自己的对象。但是auto& 是一个引用,并且限定符对引用更粘,因为它们是别名。 (正交,但也增加了混乱:const 不传递。)

标签: c++ c++11 constants auto


【解决方案1】:

我是否正确理解用 auto (x1) 声明的变量永远不会是 const

正确。

当使用 auto&(x2) 时,如果 exp2 为 const,则为 const。

引用永远不是 const;引用不能是 cv 限定的。 x2 可以是 const 的引用。

auto it = find(cont.cbegin(), cont.cend(), value);

尽管我使用了 cbegin 和 cend,但这里将是非常量迭代器

it 将是 const_iterator 类型的非 const 限定对象。

const auto it1 = find(cont.cbegin(), cont.cend(), value);

it1 将是 const_iterator 类型的 const 限定对象。

通过 const_iterator 间接(通常)为您提供对 const 的引用,因此您无法修改指向的对象。

一个 const 对象(通常)不能被修改。因此,例如,您不能增加 const 限定的迭代器。

【讨论】:

    猜你喜欢
    • 2012-05-29
    • 2016-08-02
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多