[英]c++ - copy constructor, deep copy and how to write it correctly
我需要帮助,我不知道如何注册我的复制构造函数来执行深层复制。
我的问题是我的复制构造函数是否正确注册,如果没有,那么我怎么能写下来非常感谢你。
我的ArrayList.h:
template<class T>
class ArrayList{
private:
T* storage;// T pointer array
int size;// size of array
public:
ArrayList();//constructor
ArrayList(const &ArrayList);//copy constructor
};
template<class T>//constructor
ArrayList<T>::ArrayList(){
size = 0;// size of array in start
}//end ArrayList
template<class T>//copy constructor
ArrayList<T>::ArrayList(const &ArrayList){
T* _storage = T* storage;
int _size = size;
}
template<class T>//destructor
ArrayList<T>::~ArrayList(){
delete[]storage;
}//end ~ArrayList
谢谢
不,这不正确。 现在你正在执行一个浅拷贝,即只是复制指针(这是默认的拷贝构造函数无论如何都会这样做),所以当副本和原始版本超出范围时,你会得到2个析构函数试图解除分配同样的记忆和bam!
您需要在复制构造函数中分配内存,复制元素,然后将指针更改为指向新分配的内存,例如
template<class T>//copy constructor
ArrayList<T>::ArrayList(const ArrayList&){
T* copy_storage = new T[size];
for(std::size_t i = 0; i < size; ++i)
copy_storage[i] = storage[i];
storage = copy_storage;
}
我认为这是一个练习。 如果没有,只需使用std::vector<T>
,一切都将自动处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.