gcc/libstdc++-v3/testsuite/26_numerics/valarray/99117.cc
Jonathan Wakely b58f0e5216 libstdc++: Avoid aliasing violation in std::valarray [PR99117]
The call to __valarray_copy constructs an _Array object to refer to
this->_M_data but that means that accesses to this->_M_data are through
a restrict-qualified pointer. This leads to undefined behaviour when
copying from an _Expr object that actually aliases this->_M_data.

Replace the call to __valarray_copy with a plain loop. I think this
removes the only use of that overload of __valarray_copy, so it could
probably be removed. I haven't done that here.

libstdc++-v3/ChangeLog:

	PR libstdc++/99117
	* include/std/valarray (valarray::operator=(const _Expr&)):
	Use loop to copy instead of __valarray_copy with _Array.
	* testsuite/26_numerics/valarray/99117.cc: New test.
2024-02-15 11:43:21 +00:00

17 lines
355 B
C++

// { dg-do run { target c++11 } }
// PR libstdc++/99117 cannot accumulate std::valarray
#include <valarray>
#include <vector>
#include <testsuite_hooks.h>
int main()
{
std::vector<std::valarray<int>> v = {{1,1}, {2,2}};
std::valarray<int> sum(2);
for (const auto& e : v)
sum = sum + e;
VERIFY(sum[0]==3);
VERIFY(sum[1]==3);
}