开发者

Structure deep copy

开发者 https://www.devze.com 2023-03-07 17:50 出处:网络
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.

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.

// 开发者_Python百科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?


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 own operator= that doesn't copy correctly. You only need to define operator= for types with pointers, since a shallow copy of a pointer will copy the pointer but share the data.


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 and t2, 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!)

0

精彩评论

暂无评论...
验证码 换一张
取 消