https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108846
Bug ID: 108846 Summary: std::copy, std::copy_n on potentially overlapping subobjects Product: gcc Version: 13.0 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: --- // https://gcc.godbolt.org/z/EfdG4nzv9 #include <algorithm> #include <cassert> struct B { B(int i, short j) : i(i), j(j) {} int i; short j; /* 2 byte padding */ }; struct D : B { D(int i, short j, short x) : B(i, j), x(x) {} short x; }; int main() { D ddst(1, 2, 3); D dsrc(4, 5, 6); B *dst = &ddst; B *src = &dsrc; std::copy_n(src, 1, dst); // should do `*dst = *src` assert(ddst.x == 3); // FAILS } Similarly if you use `std::copy(src, src+1, dst)`. The problem here is that `std::copy` and `std::copy_n` (and presumably some other algorithms too, like `std::move`) believe that if a type is trivially copyable, then it's safe to use `memcpy` or `memmove` on it. But in fact that's safe only if either - the type's "sizeof" is equal to its "data size, without trailing padding"; or - you happen to have external information proving that the object being copied is not a potentially overlapping subobject. I think it's safe for `std::copy` and `std::copy_n` to use memcpy/memmove if they are given a destination range of 2-or-more elements; but if it's just a single object, then (by the letter of the law) they must assume the destination object might be a potentially overlapping subobject, and not memcpy into it. (Full disclosure: I will be THRILLED if you close this as "not a bug," because that will be ammunition to go to LWG and say "look, vendors think this behavior is fine, we should actually standardize this behavior and remove the expectation that STL algorithms can ever handle potentially overlapping subobjects.")