In C++ the delete[] is supposed to be used with arrays created by new. You can pass arrays into functions like this: void method_with_array(int* array). How can you tell if an array created this way was created with new, so you can delete it properly.
2 Answers
You can't, so better not pass around pointers to things created with new or new[]. Use for example std::vector or if you really really really need a dynamically allocated array, std::unique_ptr<T[]>.
5 Comments
juanchopanza
@NeilButterworth I have never had to use that specialization. I imagine there could exist very niche situations where the tiny size and/or zero initialization overhead of a vector could matter.
davidbak
@NeilButterworth - using an existing API to some library (or the operating system) you might get from it an unwrapped allocated buffer that you're supposed to manage the lifetime of.
davidbak
oh yeah, of course. You've got to
::LocalFree it (Windows) or whatever. Some libraries have a callback you should use. The API you're calling will document that, of course ...Usually a good rule is that whoever takes care of the allocation of an object should take care of releasing the object.
That said, if you are allocating and deleting the memory for an object in the same object/container/manager, you know what you are dealing with. In case the same pointer is used for one or multiple elements, you have different options:
- keep a variable that tells you which kind of
int*member you have allocated - allocate all the times an array, eventually of size 1
- use an std::vector even for storing a single element, as above.
delete[]is supposed to be used with arrays created bynew". Wrong.delete[]is supposed to be used with arrays created bynew[]. Plainnewpairs with plaindelete.