[C++ job interview Q&A] C++ Unions.

According to https://en.cppreference.com/w/cpp/language/union:

A union is a special class type that can hold only one of its non-static data members at a time.

It means that the following union:

union U
  std::uint8_t a;
  std::uint16_t b;
  std::uint32_t c;

may hold either uint8_t, uint16_t or uint32_t at a time. Such a union is of the size of its largest data, which is 4 bytes in that case. Like in a struct, the default access modifier of members of a union is public.

It’s also very important to know that:

It’s undefined behavior to read from the member of the union that wasn’t most recently written. Many compilers implement, as a non-standard language extension, the ability to read inactive members of a union.

This means that the popular use of unions which is to convert data between types is actually an undefined behaviour acc. to the C++ language standard.

Generally, it’s not recommended to use unions at all. MISRA C/C++ and AUTOSAR C++14 coding guidelines prohibit the use of unions, as it may result in data being misinterpreted by a programmer. Also, C++ Core Guidelines identifies the type-safety problems resulting from the use of C++ unions.

Luckily, since C++17 many uses of the union type may be replaced with std::variant type.

Tagged in
Leave a reply