开发者

delete function in C++

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开发者_Python百科: 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?


delete isn't a function, it's an operator.

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

The delete expression 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.

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 when delete[] is used to ensure the correct number of destructors are called. This is just an implementation detail, though, other implementations are possible.


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

Because the C++ language standard states that it must know. So when you allocate an array, it is up to the system to store the size somewhere where delete[] can find it.

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

Then delete[] just has to subtract a few bytes from the pointer in order to find the size.

Another option could be to have a global map<void*, int>, where the key is the pointer to a memory allocation, and the value is the size of that allocation. There are plenty of other ways in which delete[] can find out the size. The C++ standard doesn't specify which one to use. It just says that delete[] must know the size, and leaves it up to the implementers to figure out how to pull it off.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜