问题
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?
回答1:
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.
回答2:
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
.
回答3:
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
来源:https://stackoverflow.com/questions/28651860/difference-between-new-delete-vs-new-delete-in-c