Hi there,
Hopefully someone can answer this basic question. I'll post some sample code to help me explain:
My question is, in the Run.cpp,Code:**********Start Run.cpp *********** #include "MyClass.h" using namespace std; int main(char args[]) { MyClass *mc = new MyClass[10]; delete [] mc; } **********End Run.cpp *********** **********Start MyClass.h *********** #ifndef MYCLASS_H #define MYCLASS_H #include <string> #include <iostream> using namespace std; class MyClass { public: string s; int i; MyClass(); }; #endif **********End MyClass.h *********** **********Start MyClass.cpp *********** #include "MyClass.h" MyClass::MyClass() { i = -1; s = "Hello"; } MyClass::~MyClass() { cout<<"Destructing MyClass"<<endl; } **********End MyClass.cpp ***********
MyClass *mc = new MyClass[10];
will construct 10 instances of MyClass and have a pointer 'mc' point to the first one. We can then reference any via 'mc[0...9].
Now as we are using the 'new' operator, this creates these 10 objects at runtime, presumably therefore placing them on the 'heap'. As I understand it (which I may be wrong), the stack grows from one end of the memory and the heap in the other, growing towards each other until they run out of room (I read this in an old book on compiler construction, so it may be wrong, please correct me if so).
So... when I call
delete [] mc;
This deletes the pointer to these objects, but leaving the 10 objects on the heap ? This would be a memory leak ?
Do these objects remain on the heap after the program has finished ? If so, how do I destroy them and free the memory ?
I could call mc[0...9].~MyClass but this would simply call the destructor, but not actually freeing the memory as delete does ?
For example, if this wasn't an array, and I had
MyClass *mc = new MyClass();
delete mc;
Presumably this is actually freeing the memory ?
I imagine that delete [] mc can't free memory of all the objects, as it doesn't know how many objects its pointing to (being a standard pointer only pointing to the first object?).
Any general advice and information on this would be much appreciated.
Cheers.