I read about this paragraph from a few questions posted on SO.
I can\'t quite figure out why memcpy isn\'t guaranteed to be safe for a non-POD type.
Imagine a class that holds some pointer to a buffer like this:
class Abc {
public:
int* data;
size_t n;
Abc(size_t n)
{
this->n = n;
data = new int[n];
}
// copy constructor:
Abc(const Abc& copy_from_me)
{
n = copy_from_me.n;
data = new int[n];
memcpy(data, copy_from_me.data, n*sizeof(int));
}
Abc& operator=(const Abc& copy_from_me)
{
n = copy_from_me.n;
data = new int[n];
memcpy(data, copy_from_me.data, n*sizeof(int));
return *this;
}
~Abc()
{
delete[] data;
}
} ;
If you just memcopy one of its constructed instance, you'll get two instances pointing onto the same buffer data, because they will have the same address of buffer in data pointer. If you modify the data in one instance, it will be modified in the other too.
This means you didn't truly cloned it into two independent classes. Moreover, if you then delete both classes, the buffer would be freed twice from the memory which would crash. So the class has to have a copy constructor defined and you have to rather copy it using the constructor.