I saw an example of using the function: delete in cpp and I didn’t completely understand it.
the code is:
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 aim was to delete all the pointers in the container Table.
The brackets in delete[] give me a clue that it deletes an array of pointers to Name but the size of the array is not specified, so how does the destructor “know” how many pointers to delete?
deleteisn’t a function, it’s an operator.A
deleteexpression using[]destroys objects created withnew ... []and releases the associated memory.delete[]must be used for pointers returned bynew ... []; non-arraydeleteonly on pointers returned by non-arraynew. Using the non-matchingdeleteform is always incorrect.The
deleteexpression in~Table()(missing()in your code) will destroy the dynamically created array ofNameobjects ensuring that theNamedestructor is called for each member of the array.It is up the the implementation to implement some mechanism of recording the number of elements in arrays allocated with
new ... []the programmer doesn’t have to worry about this.In many implementations, where the array elements have non-trivial destructors, a
new[]expression will allocate extra space to record the element count before the space for all the array members. This hidden count is then looked up whendelete[]is used to ensure the correct number of destructors are called. This is just an implementation detail, though, other implementations are possible.