28

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.

8
  • 4
    You mean unsigned char rgbaBytes[4];, right? Right now you only have 1 char.
    – GManNickG
    Jun 3, 2009 at 6:01
  • 2
    Yeah the size of intValue is 4 bytes and rgbBytes only 1 byte so rgbBytes will only access 1 byte of the value.
    – stefanB
    Jun 3, 2009 at 6:03
  • As a side note, you might want to look at how to turn your union into a first class object in c++, builderau.com.au/program/java/soa/…
    – Nixuz
    Jun 3, 2009 at 6:11
  • my bad, it's unsigned char rgbaBytes[4];
    – lyxera
    Jun 3, 2009 at 12:09
  • See stackoverflow question on this topic ("What is the strict aliasing rule?")
    – OJW
    Jun 3, 2009 at 16:55

12 Answers 12

26

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.

6
  • I am not sure if I agree with your case 2. As clearly lyxera is using the union to gain access to the same data with an integer and char array representations, so a struct with two data members would not work.
    – Nixuz
    Jun 3, 2009 at 6:15
  • 7
    In case 2 I would definitely use a BOOST.any or BOOST.variant
    – TimW
    Jun 3, 2009 at 7:16
  • 5
    1. is wrong. Type punning is not the purpose of unions and it's undefined behaviour to write to a union element and read from another. See this stackoverflow.com/questions/2310483/…
    – legends2k
    Aug 17, 2012 at 15:03
  • @legends2k: 'Undefined' simply means that the language specification does not guarantee what will happen when you do this. It does not mean you must never use unions. You need to understand your data - the implications of endianness, structure packing, compiler implementation, caching optimisations, etc. and be aware that your code may not be portable. A union is a way of making two different things occupy the same bytes of memory (though not at the same time), so of course you have to use them extremely carefully, and be aware that you are fiddling at a very low level. (That's why it's fun!) Aug 28, 2012 at 11:24
  • @Jason: All of that, but still the intended purpose is simply to save space, since that's the reason it was created for, using it for punning is simply equivalent to saying "I use the pen as a paperweight".
    – legends2k
    Aug 31, 2012 at 11:16
10

Is it good practice? Yes, but with some caveats.

Back in the days when memory was scarce, unions were popular to re-use memory. Those days are long gone and using unions for that purpose adds needless complexity. Don't do it.

If a union genuinely describes your data, as it does in the example you give, then it is a perfectly reasonable thing to do. However, be warned that you are building in some platform dependencies. On a different platform with different integer sizes or different byte ordering you might not get what you were expecting.

1
  • 2
    inttypes.h with its uint8_t etc. is the right way do this, if the size of data matters (e.g. a wire format), but don't forget about endian issues! Jun 3, 2009 at 8:40
6

In C++ the use of unions is constrained by the fact that that their members must be PODs (plain old data). For example, a union member cannot have a constructor or a destructor, among other restrictions.

4
  • 1
    You can have constructors for unions in C++, as well as methods, virtual functions, etc. Jun 5, 2009 at 23:06
  • Read what I said - union MEMBERS cannot have constructors etc.
    – anon
    Jun 6, 2009 at 7:35
  • 2
    This is not correct. For example, look at C++14 [class.union]/3, it specifically shows an example where a union contains a std::string.
    – M.M
    Jul 18, 2015 at 5:38
  • Putting a non-POD object, like a std::string, in a C++ union sounds data corruption waiting to happen. Not enough space for an example here but STRONGLY suggest avoiding it.
    – Michael J
    Oct 23, 2016 at 5:22
3

In my hypothetical C++ Coding Standards unions would be banned, since they tend violate the "correctness, simplicity and clarity come first" rule.

However, this is not the widespread recommendation, and Sutter and Alexandrescu didn't rule against them in their C++ Coding Standards, as far as I remember.

Fortunately, everybody I know finds them so hard to get right that they don't produce them. If only they had found void *'s in APIs hard to get right, too :)

2
  • 3
    There's lots of things in C++ that should be done only rarely, but which are very useful in very limited circumstances. I think "union" is one of these, although I agree that it should be rare in general. One obvious application would be in decoding byte-level protocols. Jun 3, 2009 at 13:44
  • 1
    @DavidThornley: 100% of the time I've seen them used in byte-level protocols, there was undefined behavior W.R.T alignment. We use serializations libraries for a reason. Sep 4, 2013 at 19:07
3

This code would undefined behaviour if used the way you describe.

In C++, only the last-written member of a union is active at any one time. Accessing other members is like accessing uninitailized variables.

For in-depth discussion see this thread.

Unions maybe be used for saving space; e.g. implementing a Variant. They may not be used for type punning.

2

Using unions is still acceptable practice. Just change rgbBytes to an array :)

In C, unions can be used for different purposes. Sometimes they are used as a Variant type, i.e. to hold values of different type in the same memory location. This usage would be questionable in C++, because you'd use inheritance/polymorphism. However, the other use of unions is to provide different "interface" to the same data. This kind of usage is still valid for C++.

2

Since you are using C++, I'd say that it's not good practice. If you are limited to pure C, sure why not.

The biggest problem imo is that the size of the union is always the size of the largest "member", so if you want to store a byte or a shitloadofdata, the size is sizeof(shitloadofdata) and not a byte.

Polymorphism is a far better option than unions.

2

The thing I don't like about unions is that they are undiscriminating; they give no info about what the underlying type currently is, and it is very very easy to violate type safety by accessing the wrong side of the union.

Boost::variant solves a lot of these problems. As the documentation points out, union is "nearly useless in an object-oriented environment", while boost::variant gives a very object oriented approach to solving the practical union problems. It's interface is designed to not allow access to the variant unless you are using the proper type, and the "visitor" pattern example they provide gives compile time errors if the union is extended to include a type you didn't expect.

As for if it is useful; I think so. I've used them to simply large interfaces

 class some_xml_class {
 public:
    void set_property(const string&, const string&);
    void set_property(const string&, const vector<string>&);
    void set_property(const string&, const set<string>&);
    void set_property(const string&, int);

    void set_super_property(const string&, const string&);
    void set_super_property(const string&, const vector<string>&);
    void set_super_property(const string&, const set<string>&);
    void set_super_property(const string&, int);

verses

 class some_xml_class {
 public:
    typedef boost::variant<string, vector<string>, set<string>, int> property_type;
    void set_property(const string&, const property_type&);
    void set_super_property(const string&, const property_type&);

(templates could also be useful here, but let's say the impl was long enough I didn't want to inline it)

1
  • 1
    Too make matters worse union can not contain types which have destructor defined. For this and other reasons the only wise application of unions in C++ is to access low-level types in a different way. In every other place I am definitely toward boot::variant. Jun 3, 2009 at 14:14
0

Keep in mind that the C++11 standard says that usage is undefined behavior, see M.M's answer (which is IMHO the best answer here). Future standards might define it, but still multibyte number can be stored in big or little endian way. So you should not use unions neither type casting for type puning if portability is an issue.

If it is not an issue, let me try to upgrade your code a bit to show how the unions might find their place under the C++ sun.

class Color {
    union {
        uint32_t value;
        struct {
            uint8_t b, g, r; // LSB value expected
        } part;
    } data;
public:
    uint32_t &value;
    uint8_t &r, &g, &b;
    Color()
        : value(data.value)
        , r(data.part.r)
        , g(data.part.g)
        , b(data.part.b)
    { value = 0; }
    Color(Color const& c) : Color() { value = c.value; }
    Color(uint32_t _value) : Color() { value = _value; }
    Color& operator=(Color const& c) { value = c.value;}
    Color& operator=(uint32_t _value) { value = _value;}
};

Explanation

  • struct inside union should have name: ISO C++ prohibits anonymous structs, however g++ would compile them
  • other constructors delegates to default constructor to copy values, not references (C++11)
  • the third constructor is here for comfortable implicit call
  • the construct assumes that multibyte numbers are stored in LSB order

Usage

Color c1 = 0xAABBCC; // implicit call
std::cout << hex << +c1.r << endl; // AA
Color c2 = c1; // copy constructor
c2.g = 127;
std::cout << hex << +c1.g << " " << +c2.g << endl; // BB 7F
c1 = 0xDEADCD; // assignment operator
std::cout << hex << +c1.g << " " << +c2.g << endl; // AD 7F
-1

That is absolutely a valid use of unions in C++. Depending on what you want to do, you can change your class to a union so you don't have nesting. Unions can have methods and use inheritance. If that is not possible (there are other data members) then you might want to use an anonymous union like this:

class Color
{
private:
   union
   {
       unsigned int intValue;
       unsigned char argbBytes[4];
   };
public:
    unsigned int GetIntValue() { return intValue; }
};
3
  • 1
    It also works for structs and classes: union { unsigned int intValue; struct { unsigned char r, b, g, a; }; }; Jun 13, 2009 at 16:46
  • 1
    @NikiYoshiuchi: This is undefined behavior, and only works on some compilers and is not guaranteed. Sep 4, 2013 at 19:07
  • Unions cannot use inheritance. See C++14 [class.union]/2 "A union shall not have base classes. A union shall not be used as a base class."
    – M.M
    Jul 18, 2015 at 5:47
-2

Yes, it is definitely good practice to use unions - it is the only way of telling the compiler that a piece of memory is used to store different types. Using a union maintains static type safety since no reinterpret_cast<> need to be used and makes the intent of the code easier to read.

It is also necessary to use unions when compiling with strict aliasing, in which case the compiler will assume that pointers to different types will never point at the same memory. Strict aliasing is a topic in itself, but in short reading/writing to the same memory through different pointer types when strict aliasing is enabled will often not behave as expected.

-2

If you are using GCC and going to dereference pointers referring to the same location, its better to stick with unions.

Consider the following code:

int main() {
    char rgba[4] = {0xCC, 0xCC, 0xCC, 0};
    int *value = (int*)&rgba;
}

Compiling this code with -Wstrict-aliasing=2 will raise a warning saying that strict aliasing rules were violated. Accessing a value is undefined behavior. On the other hand using union to access some part of another variable isn't a violation of strict aliasing rules.

1
  • Your comments would be true in C, however C++ has different rules.
    – M.M
    Jul 18, 2015 at 5:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.