Wednesday, June 18, 2008

Why does delete[] exist?

I would like to clarify the existence of special destruction operator for arrays, delete[] in C++.

Operator delete[] is used to destroy dynamically allocated arrays which are created using new[]. But why not have just one version of delete which determines on its own whether the object it is destroying is an array of objects or an individual. When we are allocating memory using new operator the system stores the size of the object in DWORD prior to the actual memory allocated for the object, and that information would be useful for deallocation.

Indeed, "The special destruction operator for arrays, delete[], isn't logically necessary. However, suppose the implementation of the free store had been required to hold sufficient information for every object to tell if it was an individual or an array. The user would have been relieved of the burden, but that obligation would have imposed significant time and space overheads on some C++ implementations."

The C++ Progarmming Language, Bjarne Stroustrup, Special Edition, Pg 251.

The main problem that I see in case of incorrect usage of delete[] is that the destructor will not be called for all instances.

Let consider this:
class A
{
 public:
 A()
 {
  std::cout<<"Constructor"<<std::endl;
 }
 virtual ~A()
 {
  std::cout<<"Destructor"<<std::endl;
 }
};

Here is results of my experiments with VS2005:

Example 1:

int main()
{
 A* p = new A[5];
 delete []p;
};
Output
Constructor
Constructor
Constructor
Constructor
Constructor
Destructor
Destructor
Destructor
Destructor
Destructor
Press any key to continue . .


Example 2:

int main()
{
 A* p = new A[5];
 delete p;
};
Output
Constructor
Constructor
Constructor
Constructor
Constructor
Destructor
Press any key to continue . .


In second example the destructor is called once only.
Actually this is not what we intended.

Good luck.

No comments: