Tuesday 28 March 2017

c++ - why do we need a copy constructor when an array is allocated memory dynamically?











Array(const Array &arraytoCopy)
:size(arraytoCopy.size)
{
ptr=new int[size];
for(i=0;i ptr[i]=arraytoCopy.ptr[i];
}



what is going to happen if i don't provide a copy constructor.


Answer



What will happen is that when you copy the object, you will have more than one instance pointing to the same dynamically allocated array. It isn't clear which instance should take care of de-allocating it upon destruction.



If the class is supposed to own the array, then it will be in charge of de-allocating its resources. In this case, it should have a copy constructor and assignment operator that make a copy of the contents of the array, plus a destructor calling delete[] on it. This is known as the rule of three. In C++11, it should also have move copy and move assignment operators too.



If the class doesn't own the array, it probably shouldn't construct it in the first place. It could receive a pointer to an externally allocated array via its constructor, for example.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...