结构深拷贝
这可能是一个非常基本的问题,但不知怎的,它让我被骗了......当我编写测试代码时,它似乎可以工作,但在生产中出现了问题。
// Header file
#define length 100
typedef struct testStr_t {
int a;
char b;
char t1[length];
char t2[length];
} test;
void populateTest(test*);
// source file
test test1;
test test2;
populateTest(&test1);
test2 = test1;
test2
会是 test1
的深层副本吗?或者这里有什么陷阱吗?代码是用 C 编译器还是 C++ 编译器编译有关系吗?
This may be a very basic question but somehow it got me tricked... when I write test code, it seems to work, but something is going wrong in production.
// Header file
#define length 100
typedef struct testStr_t {
int a;
char b;
char t1[length];
char t2[length];
} test;
void populateTest(test*);
// source file
test test1;
test test2;
populateTest(&test1);
test2 = test1;
Will test2
be a deep copy of test1
? Or are there gotchas here? Does it matter if the code is compiled with a C compiler or a C++ compiler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
深层复制仅受指针阻碍,因此您的
struct
将在 C 中正确复制。它也可以在 C++ 中工作,除非您定义自己的operator=
没有正确复制。您只需为带有指针的类型定义operator=,因为指针的浅拷贝将复制指针但共享数据。Deep copies are only hindered by pointers, so your
struct
will be copied correctly in C. It'll work in C++ as well unless you define your ownoperator=
that doesn't copy correctly. You only need to defineoperator=
for types with pointers, since a shallow copy of a pointer will copy the pointer but share the data.我的答案与C++有关。我只能猜测它仍然适合 C。
这将是一个浅拷贝。
如果对象包含指针
t1
和t2
,每个指针都包含一些间接的、动态分配的内存块的位置,那么您需要一个深的复制。但是,这些对象包含实际数组时间的直接对象,因此您可以使用浅复制。
(这有点误导,这有效,但你不能自己手动分配给数组对象!)
My answer relates to C++. I can only guess that it's still appropriate for C.
It will be a shallow copy.
If the objects contained pointers
t1
andt2
, each containing the location of some indirect, dynamically-allocated memory block, you'd need a deep copy.However, the objects contain direct objects of an actual array time, so you're fine with the shallow copy.
(It's slightly misleading that this works, yet you can't manually assign to array objects yourself!)