I’m working on some code and stumble onto something like this:
class Foo
{
private:
union {
byte bar;
struct {
byte baz1;
byte baz2;
};
};
};
Now, I’m compiling with warning level 4 under VS 2010 (pure unmanaged) and of course VS complains that nameless struct/union is a nonstandard extension (warning C4201) and I want to fix that warning.
Is there ANY reason at all someone would prefer the above to:
class Foo
{
private:
byte bar;
byte baz1;
byte baz2;
};
Or any reason that changing the former to the latter would break?
I am sure you already know this – if a union is used
memory storage is shared between the members of the union.
Your second example will allocate separate storage for all items
but the first example will not (shared between bar and the anonymous
struct).
Nameless structs /unions are not recommended in general
see this URL:
Why does C++ disallow anonymous structs and unions?
I could see changing example 2 to 1 breaking, but not 1 to 2 breaking
unless you are depending on the fact that the storage is shared in
a union (which is VERY bad practice)..