【问题标题】:Padding a struct out to a precise size将结构填充到精确的大小
【发布时间】:2018-10-28 10:09:25
【问题描述】:

考虑以下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...

【问题讨论】:

  • 我不知道任何 ABI 的 Foo *Foo 会有不同的对齐方式
  • 我会发布这个作为答案,但语言律师会因为我说出来而杀了我。 在实践中,您发布的内容有效,许多编译器也会记录它们的填充行为。但是,如果您真的想确定,编译器上有编译指示可以保证这一点。特别是 gcc/g++ 上的 attribute ((packed)) 和 Visual C++ 上的 pack 属性。
  • @selbie 谢谢!关于packed 的事情是我知道如何“打包”的编译器是我已经知道在这里做理智的事情的编译器(即,它们无论如何都不需要打包)。重要的是那些奇怪的东西,因为我知道它们,所以我不知道如何打包......
  • 添加编译时断言:bool cta[(sizeof(Foo) == SIZE) ? 1 : -1]; 如果您的填充假设被破坏,那么它将强制编译器不构建代码。
  • 是的,我已经用static_assert 完成了。在这里,我更想满足我的好奇心。

标签: c++ struct padding


【解决方案1】:

没有关于填充的保证。

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”的兼容性,不能保证填充 - 它是否定义了实现

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-18
    • 2018-02-11
    • 2012-08-22
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    相关资源
    最近更新 更多