C++11 中类型的逐字节副本?
C++11 标准保证逐字节复制对于 POD 类型始终有效。但是某些简单的类型呢?
下面是一个示例:
struct trivial
{
int x;
int y;
trivial(int i) : x(2 * i) { std::cout << "Constructed." << std::endl; }
};
如果我要逐字节复制此结构,即使从技术上讲它不是 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 << "Constructed." << std::endl; }
};
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,保证可以正确复制。
引用 FDIS,§3.9/2:
和§3.9/3:
所以您询问的要求是,§3.9/9:
和§9/6:
Yes, it is guaranteed to copy properly.
Quoting the FDIS, §3.9/2:
And §3.9/3:
So the requirements you're asking about are, §3.9/9:
And §9/6:
C++11 将 POD 类型的定义分为更有用的类别,特别是“琐碎”和“标准布局”。您的示例是标准布局,并且可以简单地复制,尽管构造函数阻止它变得完全简单。保证可简单复制的类型能够安全地按字节复制:
因此,不,不需要以这种方式安全复制 POD 状态,但可以识别可以安全复制的非 POD 类型的子集。
C++11 broke the definition of POD types into more useful categories, specifically 'trivial' and 'standard layout'. Your example is standard layout, and trivally copyable, although the constructor prevents it from being fully trivial. Trivially copyable types are guaranteed to be safely byte-wise copied:
So no, POD status is not required to be safely copied that way, but it is possible to identify the subset of non-POD types that can be.
如果标准声明它仅为 POD 类型定义(我还没有详细检查 C++11 标准,所以我不知道您的论点是否正确(a))并且您为非 POD 类型执行此操作,这不是定义的行为。时期。
在某些实现中,在某些环境中,在一天中的某些时间,当行星对齐时,它可能会起作用。它可能在绝大多数情况下都有效。如果您重视可移植性,那么这仍然不是一个好主意。
(a) 经过更多调查,您的具体情况似乎没有问题。标准第 3.9/3 节 (n3242 草案< /a>,但如果它与最新的草案相比发生了很大变化,我会感到惊讶)指出:
第 9 节(在高层次上)定义了“简单可复制”的含义:
引用的部分详细介绍了每个区域,
12.8
用于复制和移动类对象,13.5.3
用于复制和移动类对象作业。If the standard states it's only defined for POD types (I haven't examined the C++11 standard in detail yet so I don't know if your contention is correct or not (a)) and you do it for a non-POD type, it's not defined behaviour. Period.
It may work, on some implementations, in some environments at certain times of the day, when the planets are aligned. It may work the vast majority of times. That still doesn't make it a good idea if you value portability.
(a) After more investigation, it appears your particular case is okay. Section 3.9/3 of the standard (n3242 draft, but I'd be surprised if it had changed much from this late draft) states:
Section 9 defines (at a high level) what "trivially copyable" means:
with the referenced sections going into more detail on each area,
12.8
for copying and moving class objects and13.5.3
for assignments.