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?
Data types define the type of value or data a variable holds in it. Built-in Data types are used to store simple data types such as integers, decimal point values, characters, etc.
Explanation: the data structures which are already installed on given in the programming environment you are using are known as built in data structures. those data structure that are initialised or given by the user are known as user defined data structures .
User Defined Data type in c++ is a type by which the data can be represented. The type of data will inform the interpreter how the programmer will use the data. A data type can be pre-defined or user-defined. Examples of pre-defined data types are char, int, float, etc.
A user-defined data type lets you group data of different types in a single variable. This data type can contain any kind of related information you want to store and use together, such as personnel information, company financial information, inventory, and customer and sales records.
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[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With