将一个结构的值复制到另一个结构

copying value of one struct to another

本文关键字:结构 另一个 复制 一个      更新时间:2023-10-16

我想将一个结构的值复制到具有相同模板的另一个结构的值。以下是示例代码,其中struct list是模板结构。调用func1()必须将li的内容复制到ref。但是,当执行副本时会发生分割故障。我在哪里出错?

foo.cpp

#include<iostream>
#include <cstdlib>
class bar
{
    public:
        void func1(const list& li);
};
void bar::func1(const list& li)
{
    listref ref = nullptr;
    ref = (listref)malloc(sizeof(listref));
    ref->a = li.a;//segfault occurs here
    ref->b = li.b;
    ref->c = li.c;
    ref->d = li.d;
}

foo.h

#include<iostream>
    struct list
    {
        std::string a;
        int b;
        int c;
        const char* d;
    };
    typedef struct list* listref;

main.cpp

#include <iostream>
#include "foo.h"
#include "foo.cpp"
int main()
{
    list l1;
    std::string temp = "alpha";
    l1.a = "alphabet";
    l1.b = 60;
    l1.c = 43;
    l1.d = temp.c_str();
    bar b;
    b.func1(l1);
    return 0;
}

您正在混合C和C 概念,这就是发生的!

您的类list包含C 类型std::string的成员,这是一个需要维护的语义的复杂类。

然后您对其进行malloc

即使您对 malloc的尺寸论点是正确的(这不是;您只是给它的大小是指针的大小(,这也不能正确地构造任何东西。它应该是newstd::make_unique

不要混合C和C 成语。

相关文章: