1

I have a very quick question: What is the difference between new[ ] / delete [ ] vs new / delete in C++ when it comes to Dynamic memory?

Is new[ ] / delete [ ] not belong to Dynamic memory?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
  • 1
    You use `new` to allocate one object, and `new[]` to allocate an array of objects. You use the form of delete that matches the new you used. Only please don't actually use any of the above. For a single object, use `make_unique` or `make_shared`, and for an array use `std::vector`. – Jerry Coffin Feb 21 '15 at 22:06

3 Answers3

2

new allocates memory for a single item and calls its constructor, and delete calls its destructor and frees its memory.

new[] allocates memory for an array of items and calls their constructors, and delete[] calls their destructors and frees the array memory.

Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
1

Both memory allocation mechanisms work with dynamic memory. The former creates/destroys a single object, the second creates/destroys a run-time sized array of objects. That's the difference.

Other than that, these two mechanisms are two completely separate independent dynamic memory management mechanisms. E.g. allocating an array consisting of 1 element using new[] is not equivalent to simply using new.

AnT
  • 302,239
  • 39
  • 506
  • 752
0

the difference detween the two is that those with [] are those for array.

The difference is not that visible for the new keyword as there is no error possible

int *i = new int;
Object *array = new Object[100];

however you should make shure to call the good one to make shure destructor are called has the should

delete i; // ok
delete[] array; //ok
delete array; // Careffull, all destructors may not be called
Amxx
  • 2,667
  • 2
  • 22
  • 40