A union is a particular data type where all members start at the same address. A union can hold only one type at a time; therefore, you can save memory. A tagged union is a union that keeps track of its types.
Here are the four rules for unions.
- C.180: Use
unions to save memory
- C.181: Avoid “naked”
- C.182: Use anonymous
unions to implement tagged unions
- C.183: Don’t use a
unionfor type punning
Let’s start with the most obvious rule.
Because a union can hold only one type at one point at a time, you can save memory. The union will be as big as the biggest type.
Value is a “naked” union. You should not use it according to the next rule.
“Naked” unions are error-prone because you must keep track of the underlying type.
The union holds a double in the first iteration and an int value in the second iteration. If you read a double as an int (1) or an int as a double (2), you get undefined behavior.
To overcome this source of errors, you should use a tagged union.
Implementing a tagged union is quite sophisticated. In case you are curious, have a look at rule C.182. I will just make it easy and will write about the new C++ standard.
With C++17, we get a tagged union: std::variant. std::variant is a type-safe union. Here is a first impression.
In (2), I define the two variants v and w. Both can have an int and a float value. Their initial value is 0. This is the default value for the first underlying type. v becomes 12. std::get<int>(v) returns the value using the type. Line (3) and the following two lines show three possibilities to assign the variant v the variant w. But you have to keep a few rules in mind. You can ask for a variant’s value by type or index. The type must be unique and the index valid (4). If not, you will get a std::bad_variant_access exception. If the constructor or assignment call is unambiguous, a conversion occurs. This is why it’s possible to construct a std::variant<std::string> with a C-string or assign a new C-string to the variant (5).
At first, what is type punning? Type punning is the possibility of a programming language intentionally subverting the type system to treat a type as a different type. One typical way to do type punning in C++ is to read the member of a union with a different type from the one with which it was written.
What is wrong with the following function bad?
Expression (1) has two issues. First and foremost, it’s undefined behavior. Second, the type punning is quite challenging to find. If you have to use type punning, do it with an explicit cast such as reinterpret_cast in (2). With reinterpret_cast you have at least the possibility to spot your type punning afterwards.
Admittedly, this final post on rules for classes and class hierarchies was a bit short. with the next post, I will write about the next significant section: enumerations.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, and Philipp Lenk.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
|My special thanks to SHAVEDYAKS|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,