Post by PeteOlcottPost by SamPost by Peter OlcottWhy can a union have a member with a copy constructor?
How do you know when that specific union member should be
constructed?
What do you think should happen when two or more union
members have constructors?
You should be able to figure out the answer to your
questions, by yourself.
Now that's what I call a snotty response. It was a perfectly
valid question. All the more so as the restriction is being
lifted in the next version of the standard, so it obviously
wasn't necessary.
Post by PeteOlcottIf a class includes a union the class could also include a
member that indicates which element of the union is intended.
Only one member of a union is active at a time. What do you do
when it isn't the member which indicates which element is
active.
It would have been possible to define yet another type
(generally called a discriminated union), which would be more or
less a struct with the union and an indication of which element
is active. There was some talk about it when the (C++) standard
was being developed, but I don't think it ever got to the point
of a formal proposal. (You'd also want a possibility of
interrogating the type, etc.) The general feeling then was, I
think, that this was basically already supported by a pointer to
a base type and dynamic_cast.
Post by PeteOlcottIn this case I see no reason why this class that includes a
union could not have a copy constructor.
As I said, the next version of the standard will allow
objects with non-trivial copy constructors as members. If the
union has such a member, however, the implicitly defined copy
constructor will be absent, and either the user provides a copy
constructor (which is legal even now), and has some means of
knowing which object is active, or the union cannot be copied.
Post by PeteOlcottCarrying this same idea further this single member could be
the first element of a union of structs. In this case the
union itself could directly support a copy contructor, because
this first element would always indicate which of the structs
is intended.
You're basically trying to reinvent discriminated unions. It
can certainly be done---other languages do it. But it does
require a lot of specification.
--
James Kanze (GABI Software) email:***@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34