Saturday 21 December 2019

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

As you have raw pointers to owned dynamically allocated objects in the class, you have to provide copy constructor and copy assign operator function properly.


Consider below class definition


class Array
{
public:
Array()
{
ptr = new int[10];
}
~Array(){
delete [] ptr;
}
private:
int *ptr;
};

when you instantiate two object of Array:


Array a1, a2;
a1 = a2;

Now a1.ptr is pointing to the same memory address as p2.ptr
during the destruction of a1, a2 the ptr memory will deleted twice which is undefined behavior.


use std::vector int_collection_; is good solution instead of using raw pointer.


class Array
{
public:
Array()
{
}
~Array(){
}
private:
std::vector int_collection_;
};

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...