|
I think the first thing I should think of is that the union and bit fields in the C++ language are largely left for compatibility with C. This fact itself easily leads to the designers of the language just want to be compatible with them, and not want them to It is “perfectly” integrated with the other features of the language. In other words, on the basis of ensuring maximum compatibility, don’t bother with trouble. The simpler the better.
Regarding references, whether non-POD types can be members of union, this should be able to come up with a lot of negative reasons, such as:
(1) The reference is syntactically an alias of another object. So, how do you imagine a union instance, which can be an int and at the same time a "double alias"? (This is much more difficult to understand than "it can be an int or a double")
(2) Defining a union instance generally does not have explicit initialization, so how do you behave like one of its members (and also the common carrier of all other members) but must be explicitly initialized when it is defined?
(3) During the processing of operator=, the contents of previous objects are often cleaned first. How can one member be responsible for cleaning the information of another member?
(4) If two objects sharing the same memory have destructors, who will destruct when the entire union instance terminates?
(5) Similarly, when a union instance is created, whose constructor is called by default?
(6) What if one of the members does not have a default constructor?
In short, non-POD objects may be extremely complicated, "two objects share the same memory", my God, - don't think about it anymore. : P
There can be no static members in the union, one may be for compatibility, and the other is really not meaningful. The same is true for bit fields.
C++ is compatible with them, and of course, we should try not to change their original intention when they were designed in C language. (Think about what bit field and union are used for in C language? Adding a static member to union or making bit field as a static member should be things that their designers had never considered. ) |
|