简体   繁体   English

延迟复制-如何从浅表副本创建深表副本

[英]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 我试图创建一个临时对象并用* 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. PS我被禁止在此任务中使用STL和字符串。

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. 所有想要更改数据的方法都必须检查当前对象是否为独占数据所有者,否则将对数据进行深层复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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