Search code examples
c++memory-managementnew-operatordelete-operator

How does delete differentiate between built-in data types and user defined ones?


If I do this:

// (1.)
int* p = new int;
//...do something
delete p;

// (2.)
class sample
{
public:
sample(){}
~sample(){}
};
sample* pObj = new sample;
//...do something
delete pObj;

Then how does C++ compiler know that object following delete is built-in data type or a class object?

My other question is that if I new a pointer to an array of int's and then I delete [] then how does compiler know the size of memory block to de-allocate?


Solution

    1. The compiler knows the type of the pointed-to object because it knows the type of the pointer:

      • p is an int*, therefore the pointed-to object will be an int.
      • pObj is a sample*, therefore the pointed-to object will be a sample.
    2. The compiler does not know if your int* p points to a single int object or to an array (int[N]). That's why you must remember to use delete[] instead of delete for arrays.

      The size of the memory block to de-allocate and, most importantly, the number of objects to destroy, are known because new[] stores them somewhere, and delete[] knows where to retrieve these values. This question from C++ FAQ Lite shows two common techniques to implement new[] and delete[].