C++11 标准保证逐字节复制对 POD 类型始终有效。但是某些微不足道的类型呢?
这是一个例子:
struct trivial
{
int x;
int y;
trivial(int i) : x(2 * i) { std::cout << "Constructed." << std::endl; }
};
如果我要逐字节地复制这个结构,它是否能保证正确复制,即使它在技术上不是 POD?什么时候画出关于什么时候不可以字节复制对象的界线?
最佳答案
是的,保证复制正确。
引用 FDIS,§3.9/2:
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:
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:
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:
A trivially copyable class is a class that:
- 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++ - C++11 中类型的逐字节拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7536153/