Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I just use memcpy for those std::is_trivially_move_* things?

What is the difference between is_trivially_copy_* and is_trivially_move_*? Can I use memcpy to move construct/assignment is_trivially_move_* types?

like image 463
J. Doe Avatar asked Oct 18 '25 13:10

J. Doe


1 Answers

The difference between them is exactly what the standard says it is: are the specific operations trivial. A class can have a trivial copy constructor and a non-trivial move constructor or vice-versa.

However, these traits are not sufficient to be substituted with memcpy. The standard only allows you to use memcpy for objects which are TriviallyCopyable. Not merely trivially copy constructible, but TriviallyCopyable in full. So the trait you want is is_trivially_copyable.

And technically, you should also check to see if the type is copy constructible/assignable, depending on whether you're memcpying to live objects or not. A TriviallyCopyable type can have a deleted copy constructor or assignment operator, in which case the writer of that class expects that copying of that form can't happen. The more usual case for a TriviallyCopyable type is a deleted copy assignment operator (due perhaps to having a const member), in which case you should not memcpy to a live object.

like image 80
Nicol Bolas Avatar answered Oct 20 '25 05:10

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!