I am having a problem with a destructor being called for a class at the end of a subroutine even though it should be defined outside of the scope of the subroutine.
Here is the smallest piece of code I have that displays my problem:
#include <iostream>
using namespace std;
class Foo {
private:
double *array;
public:
Foo(int N) {
array = new double[N];
for (int i=0; i<N; i++) {
array[i]=0;
}
}
~Foo() {
delete[] array;
}
};
void subroutine(Foo x) {
cout << "Hello!" << endl;
}
int main() {
Foo bar(10);
subroutine(bar);
subroutine(bar);
}
Now the destructor for the object bar here gets called after the first subroutine finishes even though it’s scope should be the whole of the main() function? This means that when I call the second subroutine the destructor is called again and I get a memory leak.
I have found I can fix this by calling by reference in the subroutine but I am not very satisfied with this fix since I dont understand why it didn’t work in the first place.
Can anyone shed some light on this for me?
Thanks.
You are passing a
Fooby value to thesubroutinefunction. This means it has it’s own copy, which gets destroyed on exiting it’s scope.Your main problem here is that you have not implemented a copy constructor, so the dynamically allocated array is not copied (only the pointer that points to it is). So, when you copy
Fooobjects, you have each copy referring to the same array. And each copy will try to destroy it.You should follow the rule of three and implement an assignment operator and a copy constructor that make a “deep copy” of the array, such that each
Fooobject owns its own array.