C++ struct array copy
I want to copy elements of a struct array to another by using memcpy. I believe this is开发者_开发百科 miserably causing my program to fail for some reason. Also how can I free the memory in the end ?
struct FaultCodes
{
string troubleFound;
string causeCode;
string actionCode;
string paymentCode;
string suppCode;
u_int16_t multiplier;
};
struct JobFaultInfo
{
static const size_t NUM_CODES = 5;
FaultCodes codes[NUM_CODES];
};
FaultCodes codes[JobFaultInfo::NUM_CODES];
// I have populated codes with the data.
JobFaultInfo info;
memcpy(info.codes, codes, sizeof(FaultCodes)*JobFaultInfo::NUM_CODES);
You are only allowed to use memcpy in case the objects you're copying are so-called PODs (plain old data structures). But your struct contains std::string objects which are not PODs. Thus, your whole struct is not a POD.
Use std::copy from the algorithm header instead.
A std::string
usually contains a pointer to where it stores the characters. By using memcpy
for each string you get two std::string
instances who both think they have to deallocate that memory. Bang.
You can use std::copy
from <algorithm>
instead.
But even better, use a std::vector
instead of a raw array.
Cheers & hth.
The moment you enter into the std:: domain, you can not use memcpy. That is because all the std containers including string store the data in other location and only keep the pointers of that data to themselves. So if you simply do bitwise copy (as in memcpy) you exactly don't know what you have copied.
As suggested instead of using the plain arrays and memcpy use vectors and std::copy respectively. These will not have the benefit of fast copying as memcpy does but it is much more reliable than the former method.
If you still want to stick with memcpy then as I explained you can not use string. In you structure you will have two dimensional char array of static (stack) memory. chat [5][MAX_STRING_LEN]. All the strings in your structures must be mapped into each of the elements of this array. Now your structure will consist of pure data and no pointer, and hence you can use memcpy.
But please don't do this, simply use vector with std::copy.
精彩评论