Does the compiler optimise structs of size 0?

If I have a struct defined such as the following:

struct blank {
    int : 0;
};

Will the compiler optimise this away to nothing at runtime?

I ask because of this rather popular SO question. I would like to employ similar compile-time checks in my own C/C++ code. I'm trying to make the program as optimal as possible, so I don't want these empty structs hanging around at runtime if I'm only going to use them for compile-time checking.

On a side note, is there a C++-idiomatic way of achieving the same outcome as in the link?


C++ only allows that optimization when the object implements a base class. (Hence it's called the empty base optimization or EBO.) For an object which stands alone, or as a member of another struct , it must be at least one byte large even if that byte is just padding.

As for constructs like the one in the linked question, don't worry. There is no object there, only a type. Even if there were an object, it would be stripped by the linker. Unreferenced functions and global objects don't go into the executable unless you specifically ask to export everything. Even in that case, it would still probably need to have a name to be kept.

As others have mentioned, the C++11 way of doing that is static_assert . It requires an error message:

static_assert( condition, "Error: condition was false." );

The empty struct is guaranteed to have its own address, but that's about it: you wouldn't spend time building it (after all, it's empty; there's nothing to build).

The C++ idiomatic way of doing the same thing is using static_assert (available in compilers compliant with the C++11 standard).


Depends. If, by the as-if rule, all instances of this struct can be completely eliminated, then the compiler may perform that optimization. Whether your compiler does that depends on which compiler it is and possibly on the optimizer settings.

In practice, passing the address of a struct instance across module boundaries is a pretty sure way of materializing the instance in RAM with a size of at least one byte (unless a whole-program optimizer catches it). So is using this struct as the type of a member in another struct or class .

链接地址: http://www.djcxy.com/p/73566.html

上一篇: 强制函数只接受特定的定义?

下一篇: 编译器是否优化了大小为0的结构?