Details and simple examples of shallow and deep replication of C++ objects

  • 2020-05-17 06:05:32
  • OfStack

Details and simple examples of shallow and deep replication of C++ objects

Shallow copy: when two objects are copied and share some resources (memory), the destruction of one object affects the destruction of the other

Deep replication: no resources are Shared between two objects after replication, and the destruction of one object does not affect the destruction of the other

Let's take a look at a piece of code for intuition:


#include<iostream> 
#include<string.h> 
using namespace std; 
class Student 
{ 
  int no; 
  char *pname; 
public: 
  Student(); 
  Student(int n,char* p); 
  ~Student(); 
  void display(); 
}; 
 
Student::Student(){} 
 
Student::Student(int n,char* p) 
{ 
  no=n; 
  pname=new char[10]; 
  strcpy(pname,p); 
} 
 
Student::~Student() 
{ 
  delete []pname; 
} 
 
void Student::display() 
{ 
  cout<<" Student number: "<<no<<", Name: "<<pname<<endl; 
} 
 
void main() 
{ 
  Student s(10,"xiaoming"),t; 
  t=s; 
  cout<<"s="; 
  s.display(); 
  cout<<"t="; 
  t.display(); 
} 

This program seems to be correct, but the execution will go wrong, reason is the duplicate statements t = s, replication is shallow copy of the statement execution, s to assign pname pointer to address s pname, they will point to the same memory space, when t is destructor, t. pname refers to memory space was released, then execute s destructor will go wrong.

This problem can be avoided if deep replication is used. Let's use the operator overload function to achieve deep replication:


Student& Student::operator = (Student& s) 
{ 
  no=s.no; 
  int len=strlen(s.pname); 
  pname=new char[len+1]; 
  strcpy(pname,s.pname); 
  return *this; 
} 

When t=s is executed, memory space is allocated for t within the operator overload function.

There are two caveats to the operator overload function above:

1. Formal parameter 1 must be a reference type; otherwise, when t=s is executed, the argument s should be copied to formal parameter s first. This process is shallow replication, and no memory space is allocated for formal parameter s.

2. The return value 1 must be a reference type, because executing t=s is equivalent to executing t.=(s)

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: