Can we use static_assert to detect padding in a struct?

前端 未结 1 1520
小鲜肉
小鲜肉 2020-12-18 13:10

This is a follow-up to this other question

I was trying to establish at compile time whether a specific implementation had added unnamed padding inside a struct. Spe

相关标签:
1条回答
  • 2020-12-18 13:55

    There may in theory be padding at the end of the struct after t, which your assert does not catch (which may or may not be intended). Your assumption is otherwise correct and this is perfectly fine use of offsetof and static_assert, to detect padding anywhere between member variables.

    A better alternative might be:

    static_assert( offsetof(struct quad, t) == sizeof(struct quad)-sizeof(int),
    

    This also catches padding at the end of the struct. In addition, it makes the assertion more flexible in case the struct members are changed during code maintenance.

    0 讨论(0)
提交回复
热议问题