On Tue, 31 Aug 2004 15:46:38 GMT, "spoc" <> wrote:
>I have been using memcpy to copy one class to another of the same type.
>There are reasons why I had to do this bug am getting some odd crashes and
>maybe I'm doing something dodgy copying classes like this? The classes
>contain no dynamicaly allocated data, just standard types and arrays. Here
>is an example of what I'm doing, I know in isolation it may seem odd. I am
>presuming this will copy all data ok but not really sure of the workings and
>implications of doing it this way:
>
> o* c1 = new o();
> o* c2 = new o();
>
> // various inits on both c1 and c2...
>
>
> // copy c2 over c1 and delete c2
> memcpy(c1, c2, sizeof(*c1));
>
> delete c2;
>
> // continue working with c1 (which is a copy of the deleted c2)
>
>
>Is this ok?
>
>Cheers, spoc
>
(Is this a FAQ??)
It is always a BAD IDEA to copy class objects using "dumb copy"
semantics (i.e. bit-for-bit copying) because you might be copying
pointers to allocated memory which is deleted when the first class to
be deleted is destroyed; accessing them through the other class will
lead to undefined behavior. Without knowing the exact layout of your
class, it is hard to know.
A class is usually much more sophisticated than a struct because it
will implement its own semantics for copying. Also, a class can
prohibit copying (i.e. copying the "normal" way) by declaring its copy
constructor and/or assignment operator private. In my first paragaph,
you might copy pointers (shallow copy) but you are sharing the memory
they point to; typically, the class will arrange either to do a deep
copy, by allocating additional storage and copying all the data the
pointers are referencing, or -- much more complicated -- implementing
some kind of reference count.
Even if the class declaration looks relatively harmless, it might have
some members which are themselves classes (e.g. std::string,
std::list, etc.).
IOW, don't do it!
--
Bob Hairgrove