Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

c++ - Compile-time check to make sure that there is no padding anywhere in a struct

Is there a way to write a compile-time assertion that checks if some type has any padding in it?

For example:

struct This_Should_Succeed
{
    int a;
    int b;
    int c;
};

struct This_Should_Fail
{
    int a;
    char b;
    // because there are 3 bytes of padding here
    int c;
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit: Check Kerndog73's answer.

Is there a way to write a compile-time assertion that checks if some type has any padding in it?

Yes.

You can sum the sizeof of all members and compare it to the size of the class itself:

static_assert(sizeof(This_Should_Succeed) == sizeof(This_Should_Succeed::a)
                                           + sizeof(This_Should_Succeed::b)
                                           + sizeof(This_Should_Succeed::c));

static_assert(sizeof(This_Should_Fail)    != sizeof(This_Should_Fail::a)
                                           + sizeof(This_Should_Fail::b)
                                           + sizeof(This_Should_Fail::c));

This unfortunately requires explicitly naming the members for the sum. An automatic solution requires (compile time) reflection. Unfortunately, C++ language has no such feature yet. Maybe in C++23 if we are lucky. For now, there are solutions based on wrapping the class definition in a macro.

A non-portable solution might be to use -Wpadded option provided by GCC, which promises to warn if structure contains any padding. This can be combined with #pragma GCC diagnostic push to only do it for chosen structures.


type I'm checking, the type is a template input.

A portable, but not fully satisfactory approach might be to use a custom trait that the user of the template can use to voluntarily promise that the type does not contain padding allowing you to take advantage of the knowledge.

The user would have to rely on explicit or pre-processor based assertion that their promise holds true.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...