jeudi 22 juillet 2021

Why are the alignment padding rules different when inheriting from an aggregate? [duplicate]

If we have this class:

class NotAggregate
{
    double foo;
    int bar;
};

The size is 16 bytes because 4 bytes of padding are required to have correct alignment.

If we inherit from this class

struct NotAggregateChild : public NotAggregate
{
    int baz;
};

The sizeof(NotAggregateChild) is still 16, because the compiler is able to use the padding from the parent for the baz member.

However, if NotAggregate was an Aggregate (i.e. we add public: or change to a struct), the sizeof the child changes to 24.

I'm assuming this has to do with optimisations in copying aggregates (i.e. it's likely just a memcpy on the full type, which would end up overwriting child members). But that is just a guess.

Can anyone tell me what the actual reason for this optimisation being disallowed is?

https://godbolt.org/z/8jMfnnEvW

Aucun commentaire:

Enregistrer un commentaire