Home > C++ > State Of The Union

State Of The Union

For the multi-threaded CSCI that I’m developing, I’ve got to receive and decode serialized messages off of “the wire” that conform to the design below. Depending on the value of “payloadType” in the message, each instance of the “WireMessage” class will have either an instance of “DataBlock1” or “DataBlock2” embedded within it.

After contemplating how to implement the deserialized replica of the message within my code, I decided to use a union to keep the message at a fixed size as it is manipulated and propagated forward through the non-polymorphic queues that connect the threads together in the CSCI.

The figure below shows side by side code snippets of the use of a union within a class. The code on the left compiled fine, but the compiler barfed on the code on the right with a “data member with constructor not allowed in union” error. WTF?

At first, I didn’t understand why the compiler didn’t like the code on the right. But after doing a little research, it made sense.

Unlike the code on the left, which has empty compiler-generated ctor, dtor, and copy operations, the DataBlock1 class on the right has a user-declared ctor – which trips up the compiler even though it is empty. When an object of FixedMessage type is created or destroyed, the compiler wouldn’t know which union member constructor or destructor to execute for the two class members in the union (built-in types like “int” don’t have ctors/dtors). D’oh!

Note: After I wrote this post, I found this better explanation on Bjarne Stroustrup’s C++0x FAQ page:

But of course, the restrictions on which user-defined types may be included in a union will be relaxed a bit in C++11. The details are in the link provided above.

Categories: C++ Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: