Delete function in C ++

I saw an example of using the function: delete in cpp, and I did not quite understand this. the code:

class Name { const char* s; //... }; class Table { Name* p; size_t sz; public: Table(size_t s = 15){p = new Name[sz = s]; } ~Table { delete[] p; } }; 

What is the exact action of the command: delete[] p; ?

I think the goal was to remove all the pointers in the container table.

The brackets in delete[] let me know that it deletes an array of pointers to Name, but the size of the array is not specified, since the destructor "knows" how many pointers to delete?

+6
c ++ arrays delete-operator
source share
2 answers

delete not a function, it is an operator.

A delete expression using [] destroys the objects created with new ... [] and frees the associated memory. delete[] should be used for pointers returned by new ... [] ; non-array delete only for pointers returned by the non-array new . Using an inappropriate delete form is always incorrect.

The delete in ~Table() (missing () in your code) will destroy the dynamically created array of Name objects, ensuring that the Name destructor is called for each member of the array.

An implementation to implement some mechanism for recording the number of elements in arrays allocated using new ... [] , the programmer does not need to worry about this.

In many implementations where the elements of the array have non-trivial destructors, the expression new[] allocates additional space for writing the element counter in front of the space for all members of the array. This hidden count is then checked when delete[] used to ensure the correct number of destructors. This is just an implementation detail, but other implementations are possible.

+13
source share

In short, delete[] knows the size of the array, which it deletes because it is required.

Because the C ++ language standard claims it should know. Therefore, when you allocate an array, the system should store the size somewhere where delete[] can find it.

One option is to allocate a few bytes more than necessary. Use the first bytes to indicate the size, and then instead of returning a pointer to the first byte allocated, return the pointer to the first byte for the size field.

Then delete[] just needs to subtract a few bytes from the byte to find the size.

Another option would be a global map<void*, int> , where the key is a pointer to memory allocation, and the value is the size of this distribution. There are many other ways in which delete[] can know the size. The C ++ standard does not indicate which one to use. He simply says that delete[] needs to know the size and leaves it to the developers to figure out how to remove it.

+1
source share