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

自古美人都是妖i 提交于 2020-01-12 14:08:08

问题


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?


回答1:


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.




回答2:


It is not sufficient that an object has a trivial destructor. It also needs to have trivial copy operations. The object may maintain pointers to internal buffers, for example. There is no need to destroy anything but copying would need to set up the pointers in the copied to object because they would otherwise point into the buffer of the source object.




回答3:


Although it's generally rare in practice, there may be a situation where a class has a non-trivial copy constructor, along with a trivial destructor. Consider a class with a static member variable that just counts how many times the class has been copied. If you memcpy it, the counter would be inaccurate.




回答4:


It seems to me that a class with a plain pointer would qualify as has_trivial_destructor, but you usually want to make a deep copy whereas memcpy would create a shallow copy.



来源:https://stackoverflow.com/questions/11979153/can-i-memcpy-any-type-which-has-a-trivial-destructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!