Do the padding bytes of a POD type get copied?

后端 未结 4 1117
忘了有多久
忘了有多久 2021-01-03 17:21

Suppose I have a POD type like this:

struct A {
    char a;
    int b;
};

On my system, sizeof(A) == 8, even though size

4条回答
  •  鱼传尺愫
    2021-01-03 17:55

    Answering your second question:

    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?

    As an object of your type may contain padding bytes, another program generally can not compare two such objects for equality:

    Knowing which bits of the bytes that make out the object semantically is the key for defining its value representation. However, in this scenario, the target program only knows the object representation, i.e. the sequence of bytes representing such an object in memory, including padding bytes. A function like memcmp can only compare such objects whose value representation is identical to its object representation in a meaningful way. If you use it to compare objects value-wise even though they have padding, it may fail to give the right results as it cannot tell which bits in the object representation are irrelevant for the value representations of two objects to be equal.

    See http://en.cppreference.com/w/cpp/language/object

提交回复
热议问题