【发布时间】:2022-01-21 14:36:15
【问题描述】:
std::array<const T, N> 和 const std::array<T, N> 之间有什么实际区别吗?
看起来包含 const 元素的非常量数组仍然无法交换;赋值运算符也不起作用。
什么时候我应该更喜欢一个而不是另一个?
#include <array>
std::array<const int, 5> array_of_const = {1,2,3,4,5};
std::array<const int, 5> array_of_const2 = {1,2,3,4,5};
const std::array<int, 5> const_array = {1,2,3,4,5};
const std::array<int, 5> const_array2 = {1,2,3,4,5};
int main()
{
// Assignment doesn't work for either
array_of_const = array_of_const2;
const_array = const_array2;
// Swapping doesn't work for either
array_of_const.swap(array_of_const2);
const_array.swap(const_array2);
// Indexing...
array_of_const[0] = 0;
const_array[0] = 0;
return 0;
};
【问题讨论】:
-
@DrewDormann 是的,我同意。我想不出有什么好的理由,
-
@KarlKnechtel
[language-lawyer]实际上不是由 OP 添加的 -
我不明白为什么这有很多赞成票。 (最初的可能是平衡投票(我认为这很糟糕)我猜)
-
@ildjarn 什么“巨大的、明显的实际差异”?我没有看到任何
-
@wooc 在 ildjarn 的辩护中,这不是 最清晰 的例子。我最初认为它也指出了不同之处。
标签: c++