Home > Software design >  Is there any way to enforce certain size(of) class C by adding appropriate space/padding after its a
Is there any way to enforce certain size(of) class C by adding appropriate space/padding after its a

Time:01-19

Usual way to enforce size of a class is to add a padding of appropriate size:

class C 
{    
    int foo;
    uint8_t padding[PADDINGSIZE];
};

The sizeof(C) may be then also verified using static_assert.

But this is inconvenient. Is there any reliable solution to enforce sizeof(C) to a specific value with or without padding but without a necessity of specifying PADDINGSIZE?

CodePudding user response:

Your best option would probably be to use a union. Roughly speaking, with some details missing:

class C 
{    
    int foo;
};

union CAlloc
{
    C instance;
    std::byte enforced_size[DESIRED_SIZE];
};

Then use CAlloc::instance where needed.

Update: as @Mgetz pointed out in the comments, std::byte is a C 17 addition, you may want/need to use char if you're using an older standard.

CodePudding user response:

C 11 has introduced new keyword: alignas I think this is something more handy from your point of view.

CodePudding user response:

In general, I'd say not possible to enforce certain size(of) class.

Consider a desired size of 13. int foo; uint8_t padding[13 - sizeof(int)]; is not going to make a class a size of 13 as certainly padding will occur after .padding[].

The desired PADDINGSIZE will need to meet conditions depending on prior members in the class and minimum class alignment requirements. Of course there is a minimum as uint8_t padding[some_negative]; will not work.

Consider below where PADDINGSIZE 7 may need to be a multiple of 8 to avoid padding after .padding[].

class C2 {    
    int foo;
    double d;
    int uint8_t b[1];
    uint8_t padding[PADDINGSIZE];
}
  •  Tags:  
  • Related