为什么valarray分配不按文档调整受让人的大小? [英] Why does valarray assignment not resize assignee per the documentation?

查看:120
本文介绍了为什么valarray分配不按文档调整受让人的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

#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 );

应该使用,并且根据文档,我相信应该调整v1的大小,并将v0的内容复制到其中,逐个元素.那到底是怎么回事?

should be used and according to the documentation, I believe v1 should be resized and the contents of v0 copied into it, element for element. So what's actually happening?

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

推荐答案

因为您使用的是旧的C ++.

Because you're using old C++.

从C ++ 11开始,调整了目标大小以匹配源.
这就是为什么这里的一些贡献者无法重现您的问题的原因(此外,UB具有不可预测的结果). 这也是为什么 cppreference.com文章指出首先调整大小的原因执行(尽管免责声明仅适用于C ++ 11,因为它可能不错). [现在已解决.]

As of C++11, the destination is resized to match the source.
That's why some contributors here could not reproduce your issue (plus, UB has unpredictable results). It's also why the cppreference.com article states that a resize is first performed (though a disclaimer that this applies only since C++11 might have been nice). [This has now been fixed.]

[C++11: 23.6.2.3] valarray分配[valarray.assign]

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

1   为*this数组的每个元素分配了参数数组的相应元素的值.如果v的长度不等于*this的长​​度,请在执行赋值之前重新调整*this的大小以使两个数组具有相同的长度,就像通过调用resize(v.size())一样.

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  后置条件:size() == v.size().

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

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

However, in C++03, your code had undefined behaviour.
That's why you're getting a segmentation fault with your older toolchain. It's also why, when this issue was raised as a GCC bug back in 2003, it was rejected as invalid because the implementation was actually conformant at that time.

[C++03: 23.3.2.2] valarray分配[valarray.assign]

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

1   为*this数组的每个元素分配了参数数组的相应元素的值.如果参数数组的长度不等于*this数组的长度,则结果行为是不确定的.

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.

这篇关于为什么valarray分配不按文档调整受让人的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆