C ++ operator delete []

Is it correct to use the delete [] operator?

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

      

If so, Who (the compiler or GC or whoever) will determine the size of the newly created array? and where will it store the size of the array?

thanks

+2


a source to share


3 answers


For each chunk of memory allocated, the memory allocator stores the chunk size (so it's inefficient to allocate many small chunks versus one large one, for example). When a delete frees memory, the allocator knows how large the memory chunk is pointing to the pointer.



+2


a source


Technically, this usage is perfectly fair. However, it is generally a bad idea to create new arrays, and you should use std :: vector.



+2


a source


By the way, every time you are tempted to write new T[size]

, you should most likely use std::vector<T>

. By using local pointers to dynamic arrays, it is simply too difficult to ensure that memory is deallocated correctly in the event of an exception being thrown.
0


a source







All Articles