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?

Community
  • 1
  • 1
Ephemera
  • 8,672
  • 8
  • 44
  • 84

3 Answers3

5

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." );
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
2

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.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • @LokiAstari: yes, but if you never take the address, the optimizer might remove the instance -- after all, you can't do anything else with it, so effectively it's dead code :) – Fred Foo Feb 22 '13 at 00:42
2

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).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • http://stackoverflow.com/questions/621616/c-what-is-the-size-of-an-object-of-an-empty-class here is a justification. – Alexander Oh Feb 22 '13 at 00:41