I’m doing a practice problem and the question asks to create a destructor to ensure there isn’t any memory leak. When I use this destructor, I am getting this error, after executing system(“pause”);:
https://i.stack.imgur.com/mWu0A.jpg
Here is the copy constructor:
vector_of_int::vector_of_int ( const vector_of_int& a_vector )
{
an_array = new int[ a_vector.size ];
this->size = a_vector.size;
for( int i = 0; i < size; ++i )
{
an_array[i] = a_vector.an_array[i];
}
}
and the assignment operator:
vector_of_int& vector_of_int::operator= ( const vector_of_int& a_vector )
{
if( this == &a_vector )
{
return *this;
}
this->size = a_vector.size;
for( int i = 0; i < size; ++i )
{
an_array[i] = NULL;
an_array[i] = a_vector.an_array[i];
}
return *this;
}
I searched online a bit and it was mentioned that it could be due to the copy constructor pointing to the same memory location. To test this, in my main() function, I pushed data into each vector, a, b, c, and reprinted them and they were all different. This error shows after the destructor is called and it proceeds to the next line system(“pause”); where after pressing any key, it shows. Here is the end of the main():
a_vector.~vector_of_int();
b_vector.~vector_of_int();
c_vector.~vector_of_int();
cout << "\n";
system("pause");
return 0;
Is the main.exe calling the destructors again after the curly braces end of main? When I comment all 3 destructor statements, the error doesn’t show anymore.
Thanks.
Don’t explicity invoke the destructor, that will happen automatically when the object goes out of scope (from the code, I believe the vectors are stack allocated given the
.notation used to invoke the destructor). Even if they were allocated on the heap, usingnew, you would still not invoke the destructor explicitly either but usedelete.Also, in the assignment operator the
this->sizeis updated but thean_arrayis not. Ifa_vector.size > this->sizethen it will result in out of bounds access onan_arrayas it will not have enough elements:delete[]andnew[]an_array.