为什么 valarray 分配不根据文档调整受让人的大小?

Why does valarray assignment not resize assignee per the documentation?

代码:

#include <valarray>
#include <iostream>    

using namespace std;

int main()
{
  valarray<int> v0(2, 4);
  valarray<int> v1;
  v1 = v0;
  cout << "v0.size: " << v0.size() << endl;
  cout << "v1.size: " << v1.size() << endl;
  cout << "v0[0]: " << v0[0] << endl;
  cout << "v1[0]: " << v1[0] << endl;
}

输出:

v0.size: 4
v1.size: 0
v0[0]: 2
Segmentation fault

作业:

v1 = v0;

我认为构造函数:

valarray<T>& operator=( const valarray<T>& other );
应该使用

并且根据 documentation,我认为应该调整 v1 的大小并将 v0 的内容复制到其中,一个元素一个元素。那么实际发生了什么?

$ g++ --version
g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-11)

因为你使用的是旧的 C++。

自 C++11 起,调整目标大小以匹配源。
这就是为什么这里的一些贡献者无法重现您的问题(另外,UB 的结果不可预测)。 这也是 the cppreference.com article states that a resize is first performed 的原因(尽管免责声明这仅适用于 C++11 可能不错)。 [现在已修复。]

[C++11: 23.6.2.3] valarray assignment [valarray.assign]

valarray<T>& operator=(const valarray<T>& v);

1   Each element of the *this array is assigned the value of the corresponding element of the argument array. If the length of v is not equal to the length of *this, resizes *this to make the two arrays the same length, as if by calling resize(v.size()), before performing the assignment.

2   Postcondition: size() == v.size().

但是,在 C++03 中,您的代码有未定义的行为。
这就是为什么您的旧工具链出现分段错误的原因。这也是为什么当这个问题在 2003 年作为 a GCC bug 提出时,它被拒绝为无效,因为当时的实现实际上是一致的。

[C++03: 23.3.2.2] valarray assignment [valarray.assign]

valarray<T>& operator=(const valarray<T>& v);

1   Each element of the *this array is assigned the value of the corresponding element of the argument array. The resulting behavior is undefined if the length of the argument array is not equal to the length of the *this array.