When is a type in c++11 allowed to be memcpyed?(c++11 中的类型什么时候可以被 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.
我想知道的是当一个类型可以按位复制"时的确切要求.
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
是真的.没有特别需要该类型是标准布局类型.可简单复制"的定义本质上是这样做是安全的.
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 中的类型什么时候可以被 memcpyed?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++11 中的类型什么时候可以被 memcpyed?


基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07