George said:
Hi David,
Sorry for my confusion again.
I will show you a sample. Suppose I have a class Foo and in this class
(constructor), I malloc 10 bytes, and in the destructor of this class I will
call free to release the 10 bytes.
Suppose some other components use new Foo[5] to malloc 10 * 5 = 50 bytes and
5 instances of Foo, then when we call delete[] with the pointer to Foo[5] we
malloced before, then the destructor will be invoked 5 times, and in each
time, 10 bytes will be freed (released). So the memory is balanced, right?
So, in my points, I think in delete[] implementation, invoking the
destructor for each instances is enough (see my sample above). I think I may
not correct and you are more experienced. But from the sample, I can not make
myself convinced about why you mentioned an additonal step should be used to
free the memory of the array?
George:
I would strongly recommend that you read Scott Myers' "More Effective
C++", which has a good discussion of the difference between the "new
operator" and "operator new", and friends, and how to implement the latter.
Basically:
The new operator calls operator new to create the memory and then
constructs the object in that space.
The delete operator calls the destructor, and then calls operator delete
to free the memory.
You have no control over the new operator and delete operator; they are
part of the language. What you can control is the implementation of
operator new and operator delete. The default versions use malloc() and
free().
Likewise the [] forms of these.
You see that the separation of the object creation/destruction from the
memory creation/destruction is an intrinsic part of the C++ language,
and there is no point in discussing how it might be different.
If you provide your own new and delete operators (and [] forms) to
handle the memory part, then it is up to you to make sure that, as a
pair, they do not leak memory.
As others have mentioned, this question should have been asked in
microsoft.public.vc.language, because it has nothing to do with .NET.