在C++中复制两个类似的结构

Copy two similar structures in C++

本文关键字:两个 结构 C++ 复制      更新时间:2023-10-16

我想在C++中复制两个类似的结构。考虑以下三种结构。

struct Dest_Bio
{
       int age;
       char name;
};
struct Source_Bio
{
       int age;
       char name;
};
struct Details
{
       int id;
       Dest_Bio* st_bio; //Needs to be populated with values from Source_Bio
};
  • 我用"Source_Bio"结构填充了值
  • 我想将这些Source_Bio中的值复制到"详细信息"结构中的st_bio中。
  • 我不想为Dest_Bio创建成员

我尝试了以下方法。它编译良好,但在运行时使程序崩溃。

Source_Bio st_ob;
st_ob.age = 5;
st_ob.name = 't';    
Details st_a;
st_a.id = 1;
st_a.st_bio = (Dest_Bio*) malloc(sizeof(Dest_Bio));
memcpy((struct Dest_Bio*)&st_a.st_bio, (struct Source_Bio*)&st_ob,sizeof(Dest_Bio));

我怎样才能完成这项工作?提前致谢

简单的方法可能是这样的:

struct Dest_Bio { 
    int age;
    char name; // should this really be a string instead of a single char?
    Dest_Bio(Source_Bio const &s) : age(s.age), name(s.name) {}
};
Details st_a;
st_a.id = 1;
st_a.st_bio = new Dest_Bio(st_ob);

更好的是,您可能应该消除Dest_BioSource_Bio并用Bio替换两者并完成它。你也几乎肯定想用某种智能指针替换你的Dest_Bio *st_bio——一个原始指针几乎是在自找麻烦。或者,只需在Details对象中嵌入一个Bio对象(可能是首选)。

由于您已经要求两种Bio类型都与布局兼容,因此请创建一个通用类型Bio。然后在 C++ 而不是 C 中执行复制:

st_a.st_bio = new Bio(st_ob);

如果它们确实需要是不同的类型,则可以通过构造函数或转换运算符使Source_Bio可转换为Dest_Bio

这是假设您对第三个要求有真正的理由(它是指针而不是成员)。否则,使其成为成员,修复潜在的内存泄漏,并进一步简化代码:

st_a.st_bio = st_ob;

如果你真的想用C函数来混沦,那么你要复制到st_a.st_bio,而不是&st_a.st_bio(即覆盖对象,而不是指向它的指针)。只有当你讨厌任何将维护代码的人时,才这样做。