c++ - C++11 中类型的逐字节拷贝?

标签 c++ c++11 language-lawyer standard-layout

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 type T, the underlying bytes making up the object can be copied into an array of char or unsigned char. If the content of the array of char or unsigned 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 to T point to distinct T objects obj1 and obj2, where neither obj1 nor obj2 is a base-class subobject, if the underlying bytes making up obj1 are copied into obj2, obj2 shall subsequently hold the same value as obj1.

所以您要询问的要求是,§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/

相关文章:

C++ 多态性 : return type of a virtual method

c++ - 如何强制仅提取特定的私有(private)类(class)成员?

c++ - 在同一个程序中混合 cout 和 wcout

c++ - 在c++中使用gsl时如何避免静态成员函数

c++ - 结束的随机访问迭代器可以递增零吗?

c++ - 为什么输入迭代器在递增后会使其自身失效?

xcode - 项目 header Xcode 11中的Cant访问变量或类型

c++ - 在 C++ 中构造数组元素在循环中调用 new 而不是 new[] 是否合法?

c++ - 为什么 getenv 是标准化的而不是 setenv?

c++11 - 用较小的 std::vector 替换 std::vector 的一部分