C++ Deep Copy Vector Pointer Object

自作多情 提交于 2019-12-23 07:00:54

问题


I have a class called Heap that is a Vector of pointers to HeapItem objects

vector<HeapItem*> myHeap;

I want to create a deep copy of Heap so that I can delete all the items in the copy without affecting the original Heap.

EX:

OriginalHeap = new Heap();
OriginalHeap.Insert(HeapItem1);
OriginalHeap.Insert(HeapItem2);
OriginalHeap.Insert(HeapItem3);

CopyHeap = OriginalHeap;
CopyHeap.deleteMin();

print(OriginalHeap);
print(CopyHeap);

Output:

OriginalHeap = HeapItem1,HeapItem2,HeapItem3

CopyHeap = HeapItem2, HeapItem3


回答1:


Since you introduce the notion of Heap class which is a wrapper for vector<HeapItem*> you can define copy constructor for this class that takes care of desired deep copying:

class Heap{
    vector<HeapItem*> data;
public:
    ...  // various constructors if needed
    Heap(const Heap& h) {
        data = new vector<HeapItem*>(h.size());
        for (int i=0; i<h.size(); i++)
            data[i] = new HeapItem(*h.data[i]);    // if HeapItem supports copy construction
    }
    ...  // various member functions if needed
}

One possible modification as was pointed out by Chris is to use HeapItem's clone() method if former is a polymorphic class - see comments to this answer.

In addition, you might define copy assignment (if you want to be able to assigned one existing Heap to another one) and you sure want to define destructor to make sure memory is properly released when the Heap object's life is over.

You can also define Heap as a template class so that you'd be able to parameterize it with the type of HeapItem.



来源:https://stackoverflow.com/questions/27073528/c-deep-copy-vector-pointer-object

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