【问题标题】:If QList instance is const, does it mean each element is constant?如果 QList 实例是常量,是否意味着每个元素都是常量?
【发布时间】:2015-04-23 04:51:41
【问题描述】:

以下代码编译失败:

void func(const QList<int>& list){
  auto& elem = list[0];
}

问题是我无法将 const 元素绑定到非 const 引用。以下代码有效:

const auto& elem = list[0];

有人可以解释为什么将列表传递为const 会使所有元素都成为const

【问题讨论】:

  • 如果您可以修改列表中的元素,那不是很const,对吗? C++ 复合对象经常尝试模仿struct 的默认行为,也就是说,如果对象是const,那么该对象的元素也是const

标签: c++ qlist


【解决方案1】:

有人可以解释为什么将列表传递为const 会使所有元素都成为const 吗?

这是标准容器遵循的语义。这是我能看到的原因:

const int arr1 = {10, 20};
arr1[0] = 40; // Error. Elements of arr1 cannot be modified.

const std::vector<int> arr2 = {10, 20};
arr2[0] = 40; // Same semantics. Error. Elements of arr2 cannot be modified.

将该逻辑扩展到QList,如果QListconst,则QList 的元素是const

【讨论】:

  • 行为很明显,我的问题是为什么会这样?对标准的任何引用或任何合乎逻辑的原因,或者至少在不遵循标准时有任何问题?
  • 它们遵循内置数组和标准容器的语义,这对我来说很有意义。
【解决方案2】:
auto& elem = list[0];

这意味着您通过引用将list[0] 的值分配给elem,这可以改变您的list[0] 的值。

void func(const QList<int>& list)

您已将列表传递为 const,这意味着 func 不应更改列表。

以下代码将起作用:

auto elem = list[0]; //This will work, as it will create copy
const auto& elem = list[0]; //will not allow to change the value

【讨论】:

  • 我将列表作为 const 传递,但该列表的成员不是 const(或至少不是明确的)
  • @Rakib 正如 Mankarse 所说,如果可以修改 list 的元素,那它怎么能是 const 呢?
猜你喜欢
  • 2012-08-16
  • 1970-01-01
  • 2014-01-23
  • 2016-05-13
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
相关资源
最近更新 更多