This appears to be undefined behavior
union A { int const x; float y; }; A a = { 0 }; a.y = 1;
The spec says
Creating a new object at the storage location that a const object with static, thread, or automatic storage duration occupies or, at the storage location that such a const object used to occupy before its lifetime ended results in undefined behavior.
But no compiler warns me while it's an easy to diagnose mistake. Am I misinterpreting the wording?
A union can have member functions (including constructors and destructors), but not virtual functions. A union cannot have base classes and cannot be used as a base class. A union cannot have non-static data members of reference types.
In C++17 and later, the std::variant class is a type-safe alternative for a union. A union is a user-defined type in which all members share the same memory location. This definition means that at any given time, a union can contain no more than one object from its list of members.
union { int no; char name[20], float price; }; In this, the size of the member, name is more than the size of other members (sr, price) so the size of a union in memory (char × 20 = 20 byte) will be 20 bytes.
The latest C++0x draft standard is explicit about this:
In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time.
So your statement
a.y = 1;
is fine, because it changes the active member from x
to y
. If you subsequently referenced a.x
as an rvalue, the behaviour would be undefined:
cout << a.x << endl ; // Undefined!
Your quote from the spec is not relevant here, because you are not creating any new object.
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