简体   繁体   中英

Lazy copying - how to create a deep copy from shallow copy

I have a class which is using lazy copying - when a copy constructor is called, it creates shallow copy and when one method is called it creates a deep copy and add some more data.

I'm stuck in part where I should create a deep copy from that shallow copy.

Deep copy should look like this:

  m_count = copy.m_count;
  k = copy.k;
  m_record = new TRecord * [k*SIZE];
  char * temp;
  for(int i=0;i<m_count;i++) {
    m_record[i] = new TRecord;
    temp = new char[12];
    strcpy(temp, copy.m_record[i]->Id);
    m_record[i]->Id = temp;

    temp = new char[strlen(copy.m_record[i]->Name) + 1];
    strcpy(temp, copy.m_record[i]->Name);
    m_record[i]->Name = temp;

    temp = new char[strlen(copy.m_record[i]->Surname) + 1];
    strcpy(temp, copy.m_record[i]->Surname);
    m_record[i]->Surname = temp;
  }

but I don't know how to implement it that method. I have tried to create a temporary object and fill it with *this

temp.m_count = this->m_count;...

and at the end

*this=temp;

but it doesn't work.

Why I don't create deep copy in first place? Because there are so many copies and just few of them are changed and they take so much memory.

How should I do it?

PS I am forbidden to use STL and string in this task.

You can separate all data members to a class or struct and share this data between your copies (using reference counting). All methods which wants to change the data must check that current object is the exclusive data owner or else make a deep copy of the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM