struct A
{
int a, b;
};
struct B
{
int a;
};
void main ()
{
A *a = new A;
B *b = new B;
a->a = 5;
memcpy (b, a, sizeof B);
cout << b->a << endl; //5
delete a; a = new A;
memcpy (a, b, sizeof B);
cout << a->a << endl; //5
}
I would realy appreciate some useful reference.
Thx in advance.
1. Why do you declare the structure B, as long as it holds only one integer ?
1 2 3 4
struct B
{
int a;
};
2. The correct function call is sizeof(B);.
3. I guess it is safe. As long as you delete the structures after using them, there shouldn't be any problems (that means you should have a delete b; somewhere at the end).
Assuming you fix all compile errors and plug all memory leaks, this is indeed safe, but it's very much borderline.
The key rule here is that a pointer to the object of any standard-layout type can be reinterpret_cast to pointer to its first element (in other words, both leading padding and member reordering are prohibited in standard-layout types)
So, when memcpy() performs reinterpret_cast<unsigned char*>(b) and reinterpret_cast<unsigned char*>(a) (which is what it does before copying), it is the same as reinterpret_cast<unsigned char*>(&b->a) and reinterpret_cast<unsigned char*>(&a->a), so it will, indeed, safely copy a->a into b->a.