C ++ 11中的类型的字节字节副本? [英] Byte-for-byte copies of types in C++11?
问题描述
C ++ 11标准保证逐字节复制对POD类型始终有效。
The C++11 standard guarantees that byte-for-byte copies are always valid for POD types. But what about certain trivial types?
Here's an example:
struct trivial
{
int x;
int y;
trivial(int i):x(2 * i){std :: cout< 建。 << std :: endl; }
};
struct trivial
{
int x;
int y;
trivial(int i) : x(2 * i) { std::cout << "Constructed." << std::endl; }
};
如果我复制这个struct,byte-for-byte,即使它在技术上不是POD?
If I were to copy this struct, byte-for-byte, is it guaranteed to copy properly, even though it isn't technically a POD? When is the line drawn as to when it's not okay to byte-copy an object?
推荐答案
是什么意思?是的,保证正确复制。
Yes, it is guaranteed to copy properly.
引用FDIS,§3.9/ 2:
Quoting the FDIS, §3.9/2:
对于 trivially可复制类型 c c> T 的任何对象(基类子对象除外),无论对象是否包含类型
T
的有效值,组成对象的基础字节可以复制到char
或unsigned char
。如果将char
或unsigned char
数组的内容复制回对象,则对象将随后保留原始值。
For any object (other than a base-class subobject) of trivially copyable type
T
, whether or not the object holds a valid value of typeT
, the underlying bytes making up the object can be copied into an array ofchar
orunsigned char
. If the content of the array ofchar
orunsigned char
is copied back into the object, the object shall subsequently hold its original value.
和§3.9/ 3:
对于任何平凡可复制类型
T
,如果两个指向T
to distinctT
objectsobj1
和obj2
code> obj1 也不是obj2
是一个基类子对象,如果底层字节组成obj1
将被复制到
。obj2
,obj2
obj1
For any trivially copyable type
T
, if two pointers toT
point to distinctT
objectsobj1
andobj2
, where neitherobj1
norobj2
is a base-class subobject, if the underlying bytes making upobj1
are copied intoobj2
,obj2
shall subsequently hold the same value asobj1
.
因此,你要求的要求是§3.9/ 9:
So the requirements you're asking about are, §3.9/9:
算术类型,枚举类型,指针类型,指向成员类型的指针,
std :: nullptr_t
,这些类型的cv限定版本统称为标量类型。标量类型,POD类,这种类型的数组和这些类型的cv限定版本被统称为 POD类型。 标量类型,简单可复制类类型,此类类型的数组和这些类型的cv限定版本统称为平凡可复制类型 。
Arithmetic types, enumeration types, pointer types, pointer to member types,
std::nullptr_t
, and cv-qualified versions of these types are collectively called scalar types. Scalar types, POD classes, arrays of such types and cv-qualified versions of these types are collectively called POD types. Scalar types, trivially copyable class types, arrays of such types, and cv-qualified versions of these types are collectively called trivially copyable types.
和§9/ 6:
是一个类:
- 没有非平凡的复制构造函数,
- 没有非平凡的移动构造函数,
- 没有非平凡的复制赋值运算符,
- 没有非平凡的移动赋值运算符, / li>
- 有一个简单的析构函数。
- has no non-trivial copy constructors,
- has no non-trivial move constructors,
- has no non-trivial copy assignment operators,
- has no non-trivial move assignment operators, and
- has a trivial destructor.
这篇关于C ++ 11中的类型的字节字节副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!