Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero-sized struct

Tags:

c++

According to the C++ standard (inherited from C) empty structs have a non-zero size nevertheless. The reason for this (pitiful IMHO) is that two distinct variables should have different addresses. Now, inheriting an empty struct does not always "inflate" the object. But in some situations this is the case.

I have a pretty sophisticated classes architecture, involving fierce template voodoo. As the result the final classes (instances of which I need to create) may have several empty structs inherited. Due to this fact part of them may be inflated eventually. And the worst part is that their memory layout actually depends on the order of inheritance.

I'd like to get rid of all this, if it's possible.

Is there a C++ compiler that can be configured to eliminate this space waste, in expense of breaking the standard actually?

Edit:

I mean this:

struct Empty1 {};
struct Empty2 {};

struct NonEmpty {
    int Value;
};

struct MyClass1
    :public NonEmpty
    ,public Empty1
    ,public Empty2
{
};

struct MyClass2
    :public Empty1
    ,public NonEmpty
    ,public Empty2
{
};

struct MyClass3
    :public Empty1
    ,public Empty2
    ,public NonEmpty
{
};

STATIC_ASSERT(sizeof(MyClass1) == 8);
STATIC_ASSERT(sizeof(MyClass2) == 4);
STATIC_ASSERT(sizeof(MyClass3) == 8);

Not only empty structs inflate the object (when more than one such a thing inherited), but also the result depends on the order of inheritance of the empty structs.

like image 550
valdo Avatar asked Oct 24 '11 20:10

valdo


People also ask

What is the size of an empty struct?

Generally, it is 1 byte.

What is size of struct in C?

The size of the entire structure is 8 bytes. On knowing the structured padding, it is easier to redesign or rewrite the structure.

Can you have an empty struct?

An empty structIt occupies zero bytes of storage. As the empty struct consumes zero bytes, it follows that it needs no padding.

How many bytes is a struct?

Contrary to what some of the other answers have said, on most systems, in the absence of a pragma or compiler option, the size of the structure will be at least 6 bytes and, on most 32-bit systems, 8 bytes. For 64-bit systems, the size could easily be 16 bytes.


1 Answers

The Empty Base Optimization is what will allow an empty base to not "inflate" the object, as you call it. However, you must be careful so that an object does not inherit from the same empty base twice or this optimization won't be allowed. A way to avoid this is to template the empty bases, instantiating them so that no same empty template instantiation will be inherited more than once.

If your base classes are used to tag concrete classes, then you could consider changing your design to a non-intrusive one.

like image 63
K-ballo Avatar answered Sep 22 '22 01:09

K-ballo