POD类型的填充字节是否被复制? [英] Do the padding bytes of a POD type get copied?

查看:77
本文介绍了POD类型的填充字节是否被复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的POD类型如下:

Suppose I have a POD type like this:

struct A {
    char a;
    int b;
};

在我的系统上, sizeof(A)== 8 ,即使 sizeof(char)== 1 sizeof(b)== 4 。这意味着数据结构有3个未使用的字节。

On my system, sizeof(A) == 8, even though sizeof(char) == 1 and sizeof(b) == 4. This means that the data structure has 3 unused bytes.

现在假设我们这样做了

A x = ...;
A y =x;

问题:

是否保证 x y 的所有8个字节都是相同的,甚至是这三个未使用的字节?

Is it guaranteed that all 8 bytes of x and y will be identical, even those 3 unused ones?

等效地,如果我将某些 A 对象的基础字节传输到另一个不理解其含义的程序,或者结构,并将其视为8个字节的数组,该其他程序能否安全地比较两个 A 的相等性?

Equivalently, if I transfer the underlying bytes of some A objects to another program that does not understand their meaning or structure, and treats them as an array of 8 bytes, can that other program safely compare two As for equality?

注意:在gcc 7的实验中,似乎确实复制了这些字节。我想知道是否可以保证。

Note: In an experiment with gcc 7, it appears that those bytes do get copied. I would like to know if this is guaranteed.

推荐答案


隐式定义的复制/移动构造方法对于非联盟类X,对其成员和成员执行成员复制/移动

The implicitly-defined copy/move constructor for a non-union class X performs a memberwise copy/move of its bases and members.

12.8 / 15 [ N4141中的class.copy]

12.8/15 [class.copy] in N4141

因此允许填充字节中的位模式不同。

The bit pattern in the padding bytes is thus allowed to differ.

这篇关于POD类型的填充字节是否被复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆