Examples of C and C++ shallow copy and deep copy

  • 2020-05-27 06:45:40
  • OfStack

Examples of C/C++ shallow copy and deep copy

Deep copy refers to the specific content of the copy object, and the memory address is allocated autonomously, after the copy is over, although the two objects save the same value, but the memory address is not the same, the two objects do not affect each other, do not interfere with each other.

Shallow copy is a copy of the memory address, so that the target object pointer and the source object point to the same piece of memory space.

Shallow copy is just a simple copy of the object, let several objects share a piece of memory, when the memory is destroyed, several Pointers to this piece of memory need to be redefined can be used, otherwise it will become wild pointer.

Shallow and deep copies are also involved in iOS development. In short:

Shallow copy: copies the value of the pointer variable

Deep copy: copies the pointer to the memory space

But this time we did it with C:

// The statement 1 A structure 
typedef struct Person {
  char name[20];
  int age;
  char *alias;

// Copy the method 
void copyPerson(Person *from, Person *to){

  *to = *from;
//main function 
int main(int argc, const char * argv[]) {

  Person p1;
  p1.age = 11;
  strcpy(p1.name, "royce");
  p1.alias = "owen";
  Person p2;

  copyPerson(&p1, &p2);

  printf("p2:%p p1:%p\np2-alias:%p p1-alias:%p\n",&p2,&p1,p2.alias,p1.alias);

  return 0;
// print 
p2-alias:0x100000f80 p1-alias:0x100000f80

We found that alias of p1 and alias of p2 point to the same block of memory space, and the compiler = sign assigns the default shallow copy

Implement deep copy

void copyPerson(Person *from, Person *to){

  *to = *from;
  to->alias = (char *)malloc(100);
  strcpy(to->alias, from->alias);

// print 
p2-alias:0x1003069a0 p1-alias:0x100000f82

We allocated memory to the alias override of p2 and then copied alias of p1

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!

Related articles: