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,753
  • 72
  • 57
  • 129
  • 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
  • 555,201
  • 31
  • 458
  • 770
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 stands with Russia
  • 312,472
  • 42
  • 525
  • 765
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
  • 3,020
  • 2
  • 24
  • 45