Re: Anonymous union rules against constructors & assignment
"James Dennett" <jdennett@acm.org> wrote in message
news:4BChg.102685$iU2.73289@fed1read01...
It is not valid to use memcpy on non-PODs. If you
choose to do it, you cannot portably cast the resulting
memory to the non-POD type and expect to use it.
Unless, you wrote that non-POD class, and know that memcpy is safe for it.
This is nothing new, and C++ still isn't C#. It's not
C either; C++'s object model is layered on top of C's,
but non-PODs are a whole world of their own.
I appreciate the complications of C++ in terms of the unknowability of
underlying representations, however, I don't appreciate brick walls being
erected to prevent programmers venturing into risky areas.
template <class NONPOD>
class Risky
{
union
{ NONPOD a; // Currently disallowed
};
Risky() { new(&a) NONPOD(); }
~Risky() { a.NONPOD::~NONPOD(); }
Risky& operator=(const Risky& r) { a=r.a; }
};
foo()
{ Risky<NP> a,b;
a=b;
}
Sods law says I've made a boo-boo, but you get the idea. The class can have
a selector added and additional union members.
There are non-POD classes NP for which the above is safe.
Out of interest, are there any non-POD classes NP (nevertheless compliant
with the template) for which the above code is unsafe?
---
[ 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 ]