new和new [1]有什么区别? [英] What is difference between new and new[1]?

查看:101
本文介绍了new和new [1]有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

newnew[1]有什么区别?我可以将deletenew[1]一起使用吗?

What is difference between new and new[1]? Can I use delete with new[1]?

编辑

很好,我应该提供背景信息,对此感到抱歉.我正在使用VS 2010评估BoundsChecker,当我在new [1]上使用delete []时,它抱怨内存泄漏.因此,从理论上讲,我知道应如何使用"new"和"delete"对,但是这种特殊情况使我对幕后的事物感到困惑.知道发生了什么事吗?

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?

推荐答案

Ed和aix是正确的,但引擎盖下还有很多其他事情.

Ed and aix are right, but there is much more going on underneath the hood.

如果使用new然后删除,则delete调用将执行一个析构函数.

If you use new, then delete, the delete call will execute one destructor.

如果使用new [],则必须使用delete [],但是delete []如何知道要调用多少个析构函数?可能有2个实例的数组,还是2000个实例之一? 一些(可能是大多数或全部)编译器所做的就是在内存返回给您之前存储实例数.

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.

因此,如果您调用new [5],则new将像这样分配内存:

So if you call new[5], then new will allocate memory like this:

+---+-----------+-----------+-----------+-----------+-----------+
| 5 | instance1 | instance2 | instance3 | instance4 | instance5 |
+---+-----------+-----------+-----------+-----------+-----------+

您将获得一个指向instance1的指针.

And you get a pointer back to instance1.

如果以后调用delete [],则delete []将使用数字(在本例中为5)来查看释放内存之前需要调用多少个析构函数.

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.

请注意,如果将new与delete []混合使用,或者将new []与delete混合使用,则可能会出现严重错误,因为该数字可能丢失,或者该数字可能不正确.

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.

如果将new [1]与delete混合使用,您可能会很幸运,但是请不要依赖它.

If mixing new[1] with delete works, you might be just lucky, but don't rely on it.

这篇关于new和new [1]有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆