質問

I tried googling this but only objected oriented languages pop up as results.

From my understanding a shallow copy is copying certain members of a struct.

so lets say a struct is

typedef struct node
{
    char **ok;
    int hi;
    int yep;
    struct node *next;
}node_t

copying the char** would be a shallow copy

but copying the whole linked list would be a deep copy?

Do I have the right idea or am I way off? Thanks.

役に立ちましたか?

解決

No. A shallow copy in this particular context means that you copy "references" (pointers, whatever) to objects, and the backing store of these references or pointers is identical, it's the very same object at the same memory location.

A deep copy, in contrast, means that you copy an entire object (struct). If it has members that can be copied shallow or deep, you also make a deep copy of them. Consider the following example:

typedef struct {
    char *name;
    int value;
} Node;

Node n1, n2, n3;

char name[] = "This is the name";

n1 = (Node){ name, 1337 };
n2 = n1; // Shallow copy, n2.name points to the same string as n1.name

n3.value = n1.value;
n3.name = strdup(n1.name); // Deep copy - n3.name is identical to n1.name regarding
                           // its *contents* only, but it's not anymore the same pointer

他のヒント

The copy constructor is used to initialize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory. In order to read the details with complete examples and explanations you could see the portion of this article about difference between Shallow and Deep copy constructors.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top