I have a pointer to a structure and I need to implement a method that will copy all of the memory contents of a structure. Generally speaking I need to perform a deep copy of a structure.
Here’s the structure:
typedef struct {
Size2f spriteSize;
Vertex2f *vertices;
GLubyte *vertex_indices;
} tSprite;
And here’s the method I’ve implemented that should copy the structure:
tSprite* copySprite(const tSprite *copyFromMe)
{
tSprite *pSpriteToReturn = (tSprite*)malloc( sizeof(*copyFromMe) );
memcpy(pSpriteToReturn, copyFromMe, sizeof(*copyFromMe) );
return pSpriteToReturn;
}
The problem is that I’m not sure that arrays “vertices” and “vertex_indices” are going to be copied properly. What is going to be copied in this way? Address of the array or the array itself?
Should I copy the arrays after copying the structure? Or is it enough just to copy the structure?
Something like this:
...
pSpriteToReturn->vertices = (Vector2f*)malloc( sizeof(arraysize) );
memcpy(pSpriteToReturn->vertices, copyFromMe->vertices, sizeof(arraysize) );
...
Thank you in advance.
As a rule of thumb, don’t ever use
memcpyin C++ in normal code (it might crop up in very low-level code, e.g. in allocators)1). Instead, create a suitable copy constructor and overloadoperator =(the assignment operator) to match it (and a destructor – rule of three: “if you implement either of copy constructor,operator =and destructor, you must implement all three).If you do not implement your own versions of the copy constructor an the assignment operator, C++ will create default versions for you. These versions will implement a shallow copy (much like what
memcpywould do), i.e. in your case the array contents would not be copied – only the pointers.1) Incidentally, the same goes for
mallocandfree. Don’t use them, instead usenew/new[]anddelete/delete[].