Reputation: 3061
I know that we can not use memcpy() because it can crash the program.
This is the structure that I want to copy. What is the best way to do this?
#pragma pack (push, 1)
typedef struct tagTEST_INFO
{
char szCountryCode[100];
char szOpFlag[100];
string strOrginName;
vector<RESP_INFO> vctInfo;
vector<RESP_HCR_INFO> vctHcrInfo;
} TEST_INFO, *P_TEST_INFO;
#pragma pack (pop)
Upvotes: 1
Views: 263
Reputation: 234795
The best thing equipped to write the code to perform your copy is the compiler. But it needs your help.
If RESP_INFO
and RESP_HCR_INFO
are trivially copyable then the compiler will generate adequate copy constructors and assignment operators automatically.
Also drop the C-style typedef
idiom - it's unnecessary in C++. And is that non-portable packing directive really needed? Let the compiler figure out the best way. Moving on, the std::string
class would probably be a better type for szCountryCode
and szOpFlag
.
Upvotes: 1
Reputation: 119
All of your members have assignment operators defined, meaning the built-in assignment operator will copy just fine. It will do a memberwise copy, which in turns calls the assignment operator of the members. You don't need to define your own copy assignment operator.
Upvotes: 0