Hard Light Productions Forums
Off-Topic Discussion => Programming => Topic started by: blackhole on February 26, 2009, 08:25:51 pm
-
Never, ever, ever, ever use memcpy(this, ©, sizeof(class)) in a copy constructor when you have an std::vector<> member.
-
Okay.
-
If my member ever becomes an std vector, I'll be sure to avoid that particular copy function for a while... Or at least make sure the memory protection works properly.
-
If my member ever becomes an std vector...
I know I really shouldn't, but :lol:.
-
Who the f*** decided to give the standard library a namespace of std...
-
Shouldn't you be defining class::operator=( const class& c ) anyway?
-
That's not the problem, the problem arises in the copy constructor itself when its invoked, because the vector has variable size or something like that and you end up with overwritten memory that causes trouble to no end.
-
(disclaimer: I've not grep'd through the code to verify this, so it is a hunch)
I think the vector could be deleting a pointer twice. A vector is just a resizable array, and is allocated as a block. So if you copy the vector using memcpy you end up with an _exact_ copy of the vector, including the pointer. When next you do modify the vector, it may reallocate the array at a different spot, and in doing that it 'delete's the the memory at the previous pointer and allocates a new block. When the other vector tries to do anything to that pointer, it runs into memory problems.
Besides, the vector does define the '=' operator for copying vectors - no need to use memcpy. Even the default copy constructor uses '=' on all the members, so there shouldn't be a problem unless you're explicitly overriding it (which I don't know!)
-
(disclaimer: I've not grep'd through the code to verify this, so it is a hunch)
I think the vector could be deleting a pointer twice. A vector is just a resizable array, and is allocated as a block. So if you copy the vector using memcpy you end up with an _exact_ copy of the vector, including the pointer. When next you do modify the vector, it may reallocate the array at a different spot, and in doing that it 'delete's the the memory at the previous pointer and allocates a new block. When the other vector tries to do anything to that pointer, it runs into memory problems.
Besides, the vector does define the '=' operator for copying vectors - no need to use memcpy. Even the default copy constructor uses '=' on all the members, so there shouldn't be a problem unless you're explicitly overriding it (which I don't know!)
Well yeah, thats the exact conclusion I came to, which is why I changed it to use the vector's copy constructor.