什么时候允许c ++ 11中的类型被记忆? [英] When is a type in c++11 allowed to be memcpyed?
问题描述
我的问题如下:
如果我想复制一个类类型,memcpy可以非常快地完成.在某些情况下允许这样做.
If I want to copy a class type, memcpy can do it very fast. This is allowed in some situations.
我们有一些类型特征:
- is_standard_layout.
- is_trivially_copyable.
我想知道的是类型将是按位可复制"的 exact 要求.
What I would like to know is the exact requirements when a type will be "bitwise copyable".
我的结论是,如果is_trivally_copyable
和is_standard_layout
特征都为真,则类型是按位可复制的:
My conclusion is that a type is bitwise copyable if both of is_trivally_copyable
and is_standard_layout
traits are true:
- 正是我需要按位复制吗?
- 约束是否过多?
- 约束不足吗?
P.S .:当然,memcpy的结果必须正确.我知道我可以在任何情况下进行memcpy,但是方法不正确.
P.S.: of course, the result of memcpy must be correct. I know I could memcpy in any situation but incorrectly.
推荐答案
当is_trivially_copyable<T>::value
为true时,可以使用memcpy
复制类型T的对象.该类型不必特别是标准布局类型. 平凡可复制"的定义本质上是可以安全地做到这一点的.
You can copy an object of type T using memcpy
when is_trivially_copyable<T>::value
is true. There is no particular need for the type to be a standard layout type. The definition of 'trivially copyable' is essentially that it's safe to do this.
可以安全地使用memcpy
复制但不是标准布局的类的示例:
An example of a class that is safe to copy with memcpy
but which is not standard layout:
struct T {
int i;
private:
int j;
};
由于该类对不同的非静态数据成员使用不同的访问控制,因此它不是标准布局,但仍然可以轻松复制.
Because this class uses different access control for different non-static data members it is not standard layout, but it is still trivially copyable.
这篇关于什么时候允许c ++ 11中的类型被记忆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!