https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114817
Bug ID: 114817 Summary: Wrong codegen for std::copy of "trivially copyable but not trivially assignable" type Product: gcc Version: unknown Status: UNCONFIRMED Severity: normal Priority: P3 Component: libstdc++ Assignee: unassigned at gcc dot gnu.org Reporter: arthur.j.odwyer at gmail dot com Target Milestone: --- Jiang An raises an interesting issue over at https://github.com/llvm/llvm-project/pull/89652#discussion_r1575540420 namely: // https://godbolt.org/z/64KGP1avE template<class T, class U> struct EvilPair { T& first; U& second; EvilPair(T& t, U& u) : first(t), second(u) {} EvilPair(const EvilPair&) = default; void operator=(const volatile EvilPair&) = delete; template<class = void> EvilPair& operator=(const EvilPair& rhs) { first = rhs.first; second = rhs.second; return *this; } }; static_assert(std::is_trivially_copyable_v<EvilPair<int&, int&>>); int main() { int a[] = {1,2,3}; int b[] = {4,5,6}; int c[] = {0,0,0}; int d[] = {0,0,0}; EvilPair<int&, int&> ps[] = { {a[0], b[0]}, {a[1], b[1]}, {a[2], b[2]}, }; EvilPair<int&, int&> qs[] = { {c[0], d[0]}, {c[1], d[1]}, {c[2], d[2]}, }; std::copy(ps, ps+3, qs); printf("%d %d %d\n", c[0], c[1], c[2]); } Here, EvilPair is trivially copyable, and also copy-assignable, but it is not trivially copy-assignable. libstdc++'s std::copy assumes that any trivially copyable type can be... well, trivially copied. So it copies the object representation of EvilPair, instead of doing overload resolution to discover that in fact the templated `operator=` should be called instead. Looks like the std::copy optimization was introduced in the GCC 9 release. Allegedly Microsoft STL's `std::pair<int&, int&>` is isomorphic to `EvilPair` these days. libc++'s `std::copy` avoids this issue (AFAICT) by gating their optimization on *both* is_trivially_assignable and is_trivially_copyable. I suspect there will be similar issues with `uninitialized_foo` functions and/or vector reallocation, for types that are trivially copyable (or trivially relocatable!) and yet not trivially destructive-movable.