use*_*514 1 c++ nested structure deep-copy memcpy
我有
struct Parent
{
int child1;
int child2;
char child3;
float child 4;
anotherStruct child5;
};
typedef struct
{
unsigned char x;
int y;
char z;
float a;
int b;
char c;
etc ..
} anotherStruct;
Parent myFirstParent;
Parent mySecondParent;
///I want to do a deep copy of myFirstParent into mySecondParent.
//does the follwowing work for that purpose??
memcpy (&mySecondParent, &myFirstParent, sizeof(myFirstParent);
Run Code Online (Sandbox Code Playgroud)
我正在调查答案,但同时由于极端时间限制我发布了这个问题.提前致谢.
在你的情况下,作业应该工作得很好:
mySecondParent = myFirstParent;
Run Code Online (Sandbox Code Playgroud)
毕竟,没有结构定义指针.
此外,如果有指针,甚至memcpy不会工作,因为它不会做深拷贝.在这种情况下,您必须手动复制指针的内容.
顺便说一下,你的代码不会编译,因为你anotherStruct 在定义之前就已经使用了.请anotherStruct在之前定义Parent.