简体   繁体   中英

c++ - copy constructor, deep copy and how to write it correctly

I need help please I do not know so much how to register my copy constructor to perform a deep copy.

My question is whether my copy constructor is correctly registered and if not then how can I write it down Thank you very much.

my 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

thank's

No it is not correct. Right now you are performing a shallow copy, ie just copying the pointer (which is what the default copy constructor would've done anyway), so when the copy and the original get out of scope you'll get 2 destructors trying to deallocate the same memory and bam!

You need to allocate memory in the copy constructor, copy the elements, then change the pointer to point to the new allocated memory, something like

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;
}

I assume this is an exercise. If not, just use std::vector<T> instead and everything will be taken care of automatically.

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