Re: Anonymous union rules against constructors & assignment
"Crosbie Fitch" wrote:
<kuyper@wizard.net> wrote in message
news:1149782827.305720.255770@i39g2000cwa.googlegroups.com...
Crosbie Fitch wrote:
But you said it would have the same effects as the corresponding struct
you showed, which does involve default constructor calls. I think you
might want to come up with some way of describing what you want to have
happen, that doesn't involve that comparison with a struct type.
Please forgive my uncompilable and incomplete examples.
Disregard the other member, thus:
Apart from overlaid storage there should be no difference between:
{ struct S { B b; } s; s.b=B(123); }
and
{ union U { B b; } u; new(&u.b) B(); u.b=B(123); u.b.B::~B(); }
Given:
struct B
{ int a;
B():a(0) { }
B(int i):a(i) {}
B(const B& b):a(b.a) { }
~B() { }
B& operator=(const B& b) { a=b.a; return *this; }
}
I'm saying that if you allow non-POD types in your union, they either
run the risk of not having their constructors called, or of having
constructors called for overlapping objects without an intervening
destructor call.
Not if the compiler butts out the moment a non-POD member is present in the
union.
It won't call any constructors and will refuse to provide a default
constructor for the enclosing class.
That behavior is covered by my comment "they ... run the risk of not
having the constructors called". I don't consider it acceptable if any
union member has a non-trivial constructor.
..
unions should be thought of as overlays, not objects. Thinking of a union as
an object leads you astray - into saying it's an object only as long as what
it contains can be treated as not an object. That's sophistry.
And as such, unions really has no place in C++ - it's a primitive
throwback that makes type safety excessively difficult to achieve. It's
there mainly for backwards compatibility with C.
..
And that's why, when a union has a member with a non-trivial constructor (a
non-POD class) that union cannot have a default constructor created for it.
Instead, the programmer must do it explicitly, in-place.
Which is why it's a bad idea to allow such types in a union.
Placement new is just as esoteric as using an anonymous union in the first
place. If you're using an anonymous union with non-POD members it's as
esoteric as writing your own memory allocator anyway.
Well, that's hardly an endorsement of the idea.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]