How to make a deep copy of this constructor?

為{幸葍}努か 提交于 2019-12-13 14:49:50

问题


I made this constructor, and I need to make a deep copy of it. I don't really understand the meaning of a deep copy. I know it makes independent copy of an object that has its own dynamic memory, but I don't understand what the need is for this. I'm also not sure how to actually implement the deep copy. Any suggestions?

Here is my constructor that I need to make deep copy of: Could anyone provide some syntax help, like a skeleton?

template<class t_type>
inline ALIST<t_type>::ALIST()
{
  t_type value;
  capacity=10;  
  DB = new t_type[capacity];
  count=capacity;

  cout<<"Enter value: ";
  cin.clear();
  cin>>value;


  for(int i=0; i<capacity; i++)
  {
    DB[i]=value;
  }
}

回答1:


What is the copy-and-swap idiom?

Deep copies are used so that you can copy all the information that an object has, and then alter the copy without altering the original. Broadly speaking, a shallow copy will copy only the pointer itself, but still point to the same information. This can lead to unexpected changes in data if you're not careful.




回答2:


Go through Stroustrup's presentation slides #14 and #15 in particular

Deep copy: copy the pointer and also what it points to so that the two pointers now each refer to a distinct object

  • What vector, string, etc. do
  • Requires copy constructors and copy assignments for container classes

Basically, what this boils down to is this: manage your pointers correctly, efficiently and safely. You will probably also want to look up the copy-and-swap idiom and Sutter's GOTW articles on Exception-safe class design, Exception Safety and Exception Safe Function calls.




回答3:


An example can be given from games. Let's say you have a strategy game, enemy soldiers have individual attributes such as armour, health etc. Assume the game reads these attributes from a text file and assigns the attributes each time an enemy soldier is created. Instead of reading all the information again and again from the text file or keeping the text file in the memory, which is usually larger then its object form, having a pool of prototype objects, which are created at the loading stage from the same text file, might be a better solution. When an enemy soldier is needed, you can create it from the prototype object by passing it to new object's constructor or in a factory pattern. In the constructor (or factory class) you surely need a deep copy and be careful, create all the objects instead of assigning pointers for having individual objects.



来源:https://stackoverflow.com/questions/10677394/how-to-make-a-deep-copy-of-this-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!