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.

2
  • 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. Commented Oct 5, 2017 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. Commented Oct 6, 2017 at 8:14

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Out of interest, is there any good use case for std::unique_ptr<T[]> over std::vector?
@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.
@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.
@david OK,. I'd just observe that in that situation you would want a custom deleter.
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 ...
-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.