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?
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
.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[]
.