Friday 19 January 2018

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 rel="nofollow">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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...