Why does the valarray assignment not resize the recipient in the documentation?

code:

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

Output:

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

For appointment:

 v1 = v0; 

I would have thought that the constructor:

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

and according to the documentation , I believe that v1 should be changed and the contents of v0 copied into it, element for element. So what is really going on?

 $ g++ --version g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-11) 
+5
source share
1 answer

Because you are using old C ++.

Starting with C ++ 11, the destination changes according to the source code.
This is why some participants here were not able to reproduce your problem (plus, UB has unpredictable results). This is also why the cppreference.com article states that resizing is done first (although the disclaimer, which only applies with C ++ 11, may have been nice). [This is fixed.]

[C++11: 23.6.2.3] destination valarray [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 array of arguments. If the length of v not equal to the length of *this , *this is resized to make two arrays of the same length, as if you were resize(v.size()) before doing the job.

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

However, in C ++ 03, your code had undefined behavior.
That's why you get a segmentation error with your old toolchain. This is also why, when this question was raised as a GCC bug back in 2003, it was rejected as invalid because the implementation was actually compatible at that time.

[C++03: 23.3.2.2] destination valarray [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 array of arguments. The resulting behavior is undefined if the length of the argument array is not equal to the length of the *this array.

+6
source

Source: https://habr.com/ru/post/981772/


All Articles