C++ delete[] operator [duplicate]
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.
精彩评论