This is merely for curiosity sake because I have not used new
and delete
in c++ except for the most basic uses.
I know that delete
releases memory. The thing I'm wondering is how does it handle more complex cases?
For instance, if I have a user-defined class like this:
class MyClass
{
public:
MyClass();
~MyClass()
{
delete [] intArray;
}
//public members here
private:
int* intArray;
};
Assuming the class allocates memory somehow for intArray
, and then release it in the destructor, What if I used the class like this: MyClass* myClass = new MyClass();
and released it later with delete myclass;
How does delete
handle the releasing of all the memory? Does the class destructor get called first to release all of the memory allocated by the class (ie int* intArray
) and then release the memory allocated to hold the class?
What if I had a class like this:
class MyClass
{
public:
MyClass();
~MyClass()
{
delete anotherMyClass;
}
//public members here
private:
MyClass* anotherMyClass;
};
Assuming anotherMyClass
is not allocated with the constructor, which would use up memory very quickly, what if there was a chain of MyClasses attached to each other like a linked-list? Would the delete statement in the destructor work in this case? Would each anotherMyClass
be recursively released when the destructor gets called?
Are there any specific weird tricks or caveats with the new
and delete
statements that you know about?