George said:
Thanks Ben!
I appreciate for your kindness on helping this. I am using Visual Studio
2005 and developing C++.
I want to learn,
1. how delete[] is implemented in my environment (I suspect std::delete[]
is used and it will call destructor of each element in the array)?
2. why if we use new[] to allocate memory, then use delete (other than
delete[]) will cause memory leak?
3. why there is a common delete[] which suits for all various types of
object (I ask this question because I always do not overload operator
delete in my class and delete[] always works)?
George:
When you call delete [], the compiler knows both the type of the object
and the number of objects that were allocated. Thus it has all the
information it needs to call *all* the destructors and free the memory. No
overload of operator delete [] is required.
When you call plain delete, the required behavior is to call *one*
destructor and free the memory. If the memory was allocated with new [],
and the objects themselves contain allocated memory, that memory is leaked
for the objects beyond the first. It is possible, I think, that a compiler
could implement delete so that it worked like delete [], but this is not
required by the standard.
The C++ standard says that memory allocated with new must be freed with
delete, and memory allocated with new [] must be freed with delete [].
Anything else is undefined behavior.