Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to use unions in C++?

Tags:

c++

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.

like image 673
lyxera Avatar asked Jun 03 '09 06:06

lyxera


People also ask

What are the advantages of union over structure in C?

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.

Why should we use structure instead of union?

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.

What can I use instead of union in C++?

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.


1 Answers

Unions can be fine, as long as you use them carefully.

They can be used in two ways:

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

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

like image 58
Jason Williams Avatar answered Sep 20 '22 19:09

Jason Williams