将结构填充到精确的大小

时间:2018-05-18 03:24:44

标签: c++ struct padding

考虑以下struct定义:

#define SIZE ...  // it's a positive multiple of sizeof(Foo*)

struct Foo {
  Foo* ptr;
  char padding[SIZE - sizeof(Foo*)];
};

鉴于SIZE是指针大小(sizeof(Foo*))的正数倍,是否由sizeof(Foo) == SIZE标准保证?

如果不能保证,作为一个实际问题,是否有任何常用的平台提供一个反例(等式不成立)?

是的,我知道alignas ...

1 个答案:

答案 0 :(得分:0)

无法保证填充。

C++ Standard (working draft n4741) 6.7(4) Types

4 The object representation of an object of type T is the sequence of N 
unsigned char objects taken up by the object of type T, where N equals 
sizeof(T). The value representation of an object is the set of bits that 
hold the value of type T. Bits in the object representation that are not 
part of the value representation are padding bits. For trivially copyable 
types, the value representation is a set of bits in the object 
representation that determines a value, which is one discrete element of 
an implementation-defined set of values. (41)

(41) The intent is that the memory model of C++ is compatible with that 
of ISO/IEC 9899 Programming Language C.

C++ Standard (working draft n4741) 8.5.2.3(2) Sizeof

When applied to a reference or a reference type, the result is the size 
of the referenced type. When applied to a class, the result is the 
number of bytes in an object of that class including any padding required 
for placing objects of that type in an array. The result of applying 
sizeof to a potentially-overlapping subobject is the size of the type, 
not the size of the subobject.78 When applied to an array, the result is 
the total number of bytes in the array. This implies that the size of an 
array of n elements is n times the size of an element.

我可以指出没有示例,副手,它不会成立,但基于标准的内存模型与“ISO / IEC 9899编程语言C”的兼容性,不能给出关于填充的保证 - 它是实现定义