1

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

david
  • 15
  • 6

1 Answers1

3

No it is not correct. Right now you are performing a shallow copy, i.e. 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.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • tahnk's. but why i get Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\projects\template\ArrayList.h 33 1 Template – david May 07 '17 at 18:04
  • @david The reference sign `&` has to be **after** the type, i.e. `const ArrayList&` (corrected in the answer), make sure you change the code accordingly. Also right now you define the destructor but don't declare it in the class, make sure also that you declare the destructor. – vsoftco May 07 '17 at 18:07
  • thank's i understand. now i get this error: Error 1 error LNK1104: cannot open file 'c:\Projects\Template\Release\Template.exe' c:\Projects\Template\LINK Template – david May 07 '17 at 18:15
  • @david Just put the declarations and definitions in a single header file, in other words, don't put the definitions in a separate .cpp. For templates, you cannot separate them (technically you can if you explicitly instantiate them, but that's another story). See [this](http://stackoverflow.com/q/495021/3093378) for more details. If you have them like this already, then clean the project and recompile, I don't use Windows so I cannot help you more here. – vsoftco May 07 '17 at 18:17
  • 1
    @david that happens when an instance of your program is still running when you rebuild on Windows. – Quentin May 07 '17 at 18:18