结构深拷贝

Kir*_*ran 11 c++ structure deep-copy

这可能是一个非常基本的问题,但不知何故它让我受骗......当我编写测试代码时,它似乎有效,但生产中出现了问题.

// 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;
Run Code Online (Sandbox Code Playgroud)

test2是一份深刻的副本test1吗?或者有问题吗?如果代码是用C编译器或C++编译器编译的,那有关系吗?

Chr*_*utz 11

深副本只能通过指针阻碍,所以你struct会在C正确地复制它会用C++的工作,以及除非你定义自己operator=正确复制.您只需要operator=为带有指针的类型定义,因为指针的浅表副本将复制指针但共享数据.