Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep copy structure C++

I am trying to build a deep copy function for my structure. In the main program I try to deep copy a into c so finally it should print the string "B". What am I doing wrong? I know that there is some obscure pointer stuff that I am missing right now.

#include <iostream>

using namespace std;

struct Thing {

        size_t length;
        std::string txt;
        struct Thing *things[];
};

struct Thing *deepCopy(struct Thing *origin) {

        Thing tmp;
        tmp.length = origin->length;
        for(int i=0;i<tmp.length; ++i)
            tmp.things[i] = deepCopy(origin->things[i]);

        return &tmp;
}

int main() {

        Thing a, b, *c;

        a.length = 1;
        a.things[0] = &b;
        a.txt = "A";
        b.txt = "B";
        b.length = 0;
        c = deepCopy(&a);

        cout<<c->txt;
        return 0;
}
like image 478
Alessandro Avatar asked Jun 16 '26 23:06

Alessandro


1 Answers

The best way to perform a deep copy is to write code so that the compiler does it for you. The compiler automatically generates a copy constructor and assignment operator that copies every member of the object. So long as every member knows how to copy itself, this will usually work the way you want. It probably won't work automatically if you have pointers and manually managed memory, as pointers don't know if they own what they point to. If you don't use any pointers, you are usually fine.

So if you write your object like this:

struct Thing
{
    std::string txt;
    std::vector<Thing> things;
};

Copying it will just work automatically.

Thing a;
Thing b = a; // just works

I removed the size field because std::vector knows its own size, so it is not needed.

like image 181
Neil Kirk Avatar answered Jun 19 '26 14:06

Neil Kirk