Suppose you have a simple class like this:
class foo{
private:
int* mData;
int mSize;
public:
foo(int size){
mSize = size;
mData = new int [mSize];
}
~foo() {
mSize = 0;
delete [] mData;
}
};
Then inside main you do:
int main () {
static int HUGE = 100000000;
foo a(HUGE);
// do something useful with a
// .
// .
// .
// Now I'm done with a; I do not need it anymore ...
foo b(HUGE);
// do something useful with b
// Ok we are done with b
return 0;
}
As you can see a is no longer needed after b, but since it is created on the stack, the destructor won’t be called up until the end of the program. Now, I know this is not the same as allocating with new and forgetting to call delete, however this is still wasting memory. Do you consider this as “memory leak” or just a bad programming?
Also, How would you avoid situations like this? One way would be to manually call the destructor when the object is not needed anymore, but, besides looking ugly and unfamiliar!, you get into trouble of double free unless you change the destructor to something like:
foo::~foo(){
if (mData != NULL){
delete [] mData;
mData = NULL;
mSize = 0;
}
}
Another way is to create a on the heap via foo *pa = new foo (HUGE) and then call delete pa once the object is no longer needed. This works but at the danger of introducing another possible memory leak (if one forgets to call delete pa).
Is there any better way to get rid of unneeded objects?
Destructors are called when an object goes out of scope. C++ allows arbitrary scopes inside function bodies. Write your main function this way:
I see your example is simplified, but in a real program, don’t forget to either
operator=forfoooroperator=so it cannot be called.