Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I memcpy() any type which has a trivial destructor?

Tags:

c++

c++11

memcpy

I do realize is_pod is a sufficient condition for a type to be memcpy-able, but is has_trivial_destructor also sufficient for this purpose? If not, why?

like image 316
user541686 Avatar asked Aug 16 '12 00:08

user541686


1 Answers

No. The requirement is that the type be trivially copyable (§3.9/2) which has a few more requirements, like the lack of a non-trivial copy constructor (§9/6).

A trivially copyable class is a class that:

— has no non-trivial copy constructors (12.8),

— has no non-trivial move constructors (12.8),

— has no non-trivial copy assignment operators (13.5.3, 12.8),

— has no non-trivial move assignment operators (13.5.3, 12.8), and

— has a trivial destructor (12.4).

So you should use is_trivially_copyable instead.

like image 174
R. Martinho Fernandes Avatar answered Oct 28 '22 07:10

R. Martinho Fernandes