Archive for September 2nd, 2010

Size of empty classes

Thursday, September 2nd, 2010

Little trivia about empty classes…. Here’s the setup:

Question: what’s the size of Test0? What’s the size of Test1?

It’s a relatively well known fact that embedded empty classes are not actually free, and add 1 byte to the class containing them. So, knowing this, it shouldn’t be a surprise that sizeof(Test0)==2.

A more surprising fact, maybe, is that sizeof(Test1)==1. Yep, not free either, and a different size from Test0. It has to do with an obscure rule saying that the addresses of base classes must be different, or something. Can’t remember. Still, you need to keep this in mind if you don’t want to discover weird “ghost bytes” in your binary-serialized data.

Oh well.

Controlling the size of enums

Thursday, September 2nd, 2010

The size of enums is compiler-dependent, and usually you don’t have any control over it. For example let’s have this simple enum for some types:

Then let’s check the size of the enum type:

With MSVC 2008, s = 4. This is clearly a waste of space in this case, since the type could be safely encoded on a single byte. So how do you tell the compiler about this? Well it turns out MSVC allows this nice syntax to control the size of the enum:

And that’s it! Compile with this, and s = 1. This is very useful when trying to save some bytes in a class while retaining the type safety provided by the enum. I think this notation is part of C++0x and will be supported in all compilers at some point. Right now though, it doesn’t seem to work with GCC.

For a portable solution, one probably needs to use templates, maybe something like:

…you get the idea.
shopfr.org cialis