Re: Anonymous union rules against constructors & assignment
"Crosbie Fitch" wrote:
'memcpy doesn't work on non-PODs' !!!
Wow! That's bad news.
So, let's say I had this:
class A {... }* a;
foo()
{void* p=malloc(sizeof(A));
new(p) A();
a=(A*)malloc(sizeof(A));
memcpy(a,p,sizeof(A)); // Doesn't work if A is non-POD?
free(p);
a->method();
delete a;
}
The line "a->method();" has undefined behavior. There is no guarantee
that a points to a valid object of class A. (Assuming class A is
non-POD.)
I suppose it depends on your definintion of "work" of course. memcpy
will indeed copy some bytes. But there's no guarantee that the result
is useable.
If memcpy doesn't work on non-POD objects then something truly fundamental
has changed, e.g. C++ has become C#.
Something fundamental has changed: C++ isn't C, and non-POD types
aren't required to behave like C types. This happened a long time ago,
long before there was C#.
I don't care how non-POD objects are laid out, because I don't intend to
exploit their layout.
Assuming that a bitwise copy of an object is a valid object IS
exploiting the layout.
---
[ 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 ]