GLJeff
GLJeff

Reputation: 147

memcpy array of classes revisit

Reference: Can I use memcpy in C++ to copy classes that have no pointers or virtual functions

The above thread caused a storm surrounding the viability of straight memcpying non std::is_pod (plain old data) structs/classes, however, isn't std::is_trivially_copyable sufficient to allow the memcpy of an array of classes?

The implication being that you can have private members, user defined constructors, etc without causing UB.

MyClass Array1[10];
MyClass Array2[10];

static_assert(std::is_trivially_copyable<MyClass >::value, "memcpy not safe");

memcpy(Array1,Array2,10 * sizeof(MyClass));

Upvotes: 0

Views: 87

Answers (1)

eerorika
eerorika

Reputation: 238391

isn't std::is_trivially_copyable sufficient to allow the memcpy of an array of classes?

Yes, it is sufficient. Your example has no UB.

That said, you don't necessarily need to restrict yourself to using std::memcpy because you can use std::copy_n (or std::copy) instead, and that will work with all copyable types, not just trivial ones:

static_assert(std::size(Array1) >= std::size(Array2));
// no need for asserting for triviality
std::copy_n(Array2, std::size(Array2), Array1);

Or, if you wrap the arrays inside a class, then you can use assignment. The standard library has a template for such array wrapper:

std::array<MyClass, 10> Array1;
std::array<MyClass, 10> Array2;
Array1 = Array2;

In case you were expecting that std::memcpy is faster, there is no need to worry. A decent optimiser will produce the same output, likely inlining the call to memcpy as well: https://godbolt.org/z/nEvGMe


P.S. Instead of the hardcoded 10 * sizeof(MyClass), I recommend sizeof Array1.

Upvotes: 3

Related Questions