问题
What is difference between new
and new[1]
? Can I use delete
with new[1]
?
Edit
Well well well, I should've provided the background, sorry for that. I was evaluating BoundsChecker at work with VS 2010 and it complained about a memory leak when I used delete[] on new[1]. So in theory I know how the new and delete pair should be used but this particular situation confused me about the things under the hood. Any idea whats happening?
回答1:
Ed and aix are right, but there is much more going on underneath the hood.
If you use new, then delete, the delete call will execute one destructor.
If you use new[], you must use delete[], but how can delete[] know how much destructors to call? There might be an array of 2 instances, or one of 2000 instances? What some (possibly most or all) compilers do, is to store the number of instances right before the memory it returns to you.
So if you call new[5], then new will allocate memory like this:
+---+-----------+-----------+-----------+-----------+-----------+
| 5 | instance1 | instance2 | instance3 | instance4 | instance5 |
+---+-----------+-----------+-----------+-----------+-----------+
And you get a pointer back to instance1.
If you later call delete[], delete[] will use the number (in this case 5) to see how many destructors it needs to call before freeing the memory.
Notice that if you mix new with delete[], or new[] with delete, it can go horribly wrong, because the number might be missing, or the number might be incorrect.
If mixing new[1] with delete works, you might be just lucky, but don't rely on it.
回答2:
new
creates an instance, whereas new[1]
creates a single-element array. new[1]
will almost certainly incur (small) memory overhead compared to new
to store the size of the array. You can't use non-default constructors with new[]
.
new
must be used with delete
.
new[]
must be used with delete[]
.
回答3:
new[] is an operator to allocate and initialize an array of objects and return a pointer to the first element. This differs from the new operator which has the same behavior but for one allocation, not an array. For deallocation and object destruction, new should be used with delete and new[] with delete[].
// operator new[] and new example
// create array of 5 integers
int * p1 = new int[5];
delete[] p1;
// regular allocation of one int
int * p1 = new int;
delete p1;
(see here for more details)
回答4:
'new[1]' creates an array of one item. Need to use delete[]
to free the memory. new
just creates an object. Use delete
with it.
来源:https://stackoverflow.com/questions/7510603/what-is-difference-between-new-and-new1