1

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.

Nathan Wood
  • 209
  • 2
  • 12
  • *How can you tell if an array created this way was created with new, so you can delete it properly.* -- This is a serious design flaw if you're resorting to trying to figure out where your buffer was created. Let the creator of the buffer know where and how the buffer got created, whether dynamically, whether it is a regular array, etc. – PaulMcKenzie Oct 05 '17 at 21:37
  • "`delete[]` is supposed to be used with arrays created by `new`". Wrong. `delete[]` is supposed to be used with arrays created by `new[]`. Plain `new` pairs with plain `delete`. – MSalters Oct 06 '17 at 08:14

2 Answers2

9

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[]>.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Out of interest, is there any good use case for `std::unique_ptr` over `std::vector`? –  Oct 05 '17 at 21:21
  • 2
    @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. – juanchopanza Oct 05 '17 at 21:23
  • 1
    @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 Oct 05 '17 at 21:26
  • @david OK,. I'd just observe that in that situation you would want a custom deleter. –  Oct 05 '17 at 21:35
  • 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 ... – davidbak Oct 05 '17 at 21:57
-1

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.
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Stefano Buora
  • 1,052
  • 6
  • 12