If is_trivally_copyable<T>::value
(or in C++14 is_trivially_copyable<T>()
, or in C++17 is_trivially_copyable_v<T>
) is not zero, the type is copyable using memcpy
.
Per the C++ standard, a type being trivially copyable means:
the underlying bytes making up the object can be copied into an array
of char or unsigned char. If the content of the array of char or unsigned char is copied back into the
object, the object shall subsequently hold its original value.
However, it is important to realise that pointers are trivially copyable types, too. Whenever there are pointers inside the data structures you will be copying, you have to brainually make sure that copying them around is proper.
Examples where hazard may be caused by just relying on the object being trivially copyable:
- A tree-structure implementation where your data is placed in a contiguous region of memory, but with nodes storing absolute addresses to child nodes
- Creating multiple instances of some data for sake of multithreading performance (in order to reduce cache crashes), with owning pointers inside, pointing anywhere
- You have a flat object without pointers, but with an embedded third party structure inside. The third party structure at some point in the future includes a pointer that should not exist twice or more.
So whenever memcopying, keep in mind to check whether pointers could be copied in that specific case, and if that would be okay.
Realise that is_trivially_copyable
is only the "Syntax Check", not the "Semantic Test", in compiler parlance.
memcpy
for some particular reason other than speed? Because you can get the same speed from the compiler while retaining type safety just by using the default copy ctor/assignment operator. For trivially copyable types, even very high level things likestd::copy
on an array of your trivially copyable type would be optimized to a singlememcpy
. – Currentmemcpy function
because it can skip all kind of misalignment checks. That's why compilers often implementmemcpy
as an intrinsic, to make it as fast as the default copy constructors. – Bosomed