Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 440
Rajendra Uppal Avatar asked Feb 27 '10 15:02

Rajendra Uppal


People also ask

What is the difference between built in type and user-defined type?

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.

What is the difference between built in data structure and user-defined data structure?

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 .

What is user-defined and pre defined data types?

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.

Is user-defined data type which is used to store different of data in group related to an entity?

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.


1 Answers

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

like image 143
Danilo Piazzalunga Avatar answered Nov 10 '22 00:11

Danilo Piazzalunga