开发者

C++ delete[] operator [duplicate]

This question already has answers here: How does delete[] "know" the size of the operand array? (9 answers) Closed 8 years ago.

Is this the right way to use delete[] operator?

int* a=new int[size];
delete[] a;

If yes, Who (compiler or GC or whoever) will determine the size of the newly开发者_如何学C created array? and where will it store the array size?

Thanks


For each chunk of memory allocated, the memory allocator stores the size of the chunk (that's why it is inefficient to allocate many small blocks compared to one big one for example). When delete frees the memory, the allocator knows how large the memory chunk is the pointer points to.


Technically, that usage is perfectly valid. However, it's generally a bad idea to go newing arrays like that, and you should use a std::vector.


By the way, every time you are tempted to write new T[size], you should probably use std::vector<T> instead. Using local pointers to dynamic arrays, it's simply too hard to guarantee proper memory release in the case of exceptions being thrown.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜