I need to define a class like this:
class Color { private: union Data { unsigned int intValue; unsigned char argbBytes[4]; } private: Data m_data; };
Another way is of course define the data as integer and cast it to char array whenever necessary.
I'm wondering which one is the preferred way. The contradiction here is that I have remote memory of someone's remind not to use union anymore however it seems to be a cleaner solution in this case.
Advantages of unionIt occupies less memory compared to structure. When you use union, only the last variable can be directly accessed. Union is used when you have to use the same memory location for two or more data members. It enables you to hold data of only one data member.
With a union, you're only supposed to use one of the elements, because they're all stored at the same spot. This makes it useful when you want to store something that could be one of several types. A struct, on the other hand, has a separate memory location for each of its elements and they all can be used at once.
One popular alternative to union is Boost. Variant. The types you use in it have to be copy-constructible. Update: C++17 introduced std::variant.
Unions can be fine, as long as you use them carefully.
They can be used in two ways:
To allow a single type of data to be accessed in several ways (as in your example, accessing a colour as an int or (as you probably intended) four chars)
To make a polymorphic type (a single value that could hold an int or a float for example).
Case (1) Is fine because you're not changing the meaning of the type - you can read and write any of the members of the union without breaking anything. This makes it a very convenient and efficient way of accessing the same data in slightly different forms.
Case (2) can be useful, but is extremely dangerous because you need to always access the right type of data from within the union. If you write an int and try to read it back as a float, you'll get a meaningless value. Unless memory usage is your primary consideration it might be better to use a simple struct with two members in it.
Unions used to be vital in C. In C++ there are usually much nicer ways to achieve the same ends (e.g. a class can be used to wrap a value and allow it to be accessed in different ways). However, if you need raw performance or have a critical memory situation, unions may still be a useful approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With