删除函数指针数组?
这是我从 MSDN 关于 new
运算符:
new
运算符不能用于分配函数,但可以 用于分配函数指针。下面的例子 分配然后释放一个由七个指向函数的指针组成的数组 返回整数。int (**p) () = new (int (*[7]) ()); 删除*p;
嗯,第一行没有什么奇怪的,它分配了一个指向函数的指针数组,但我只是不明白第二行如何删除该数组?我认为应该是:
delete[] *p;
谁能解释一下吗?
Here is what I've copied from MSDN about new
operator:
The
new
operator cannot be used to allocate a function, but it can be
used to allocate pointers to functions. The following example
allocates and then frees an array of seven pointers to functions that
return integers.int (**p) () = new (int (*[7]) ()); delete *p;
Well there is nothing strange with first line, it allocates an array of pointers to functions, but I just don't understand how the second deletes that array? I think it should be:
delete[] *p;
Can anyone explain this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
坦白说,正确的答案写在avakar的评论中。
正确的代码是
delete *p;
是不正确的,原因有两个:delete[]
。使用delete
将导致未定义的行为。Frankly speaking the right answer was written in the avakar's comment.
The right code is
delete *p;
is incorrect for two reasons:delete[]
for all dynamically allocated arrays. Usingdelete
will cause an undefined behaviour.如果我们添加 typedef,
则可以重写
new
语句,因此很明显,应该按照其他人的解释释放资源
。
顺便说一句,VS 2008 及更高版本的 MSDN 页面确实使用了正确的代码。
If we add a typedef,
the
new
statement can be rewritten asso this is obvious that the resource should be released with
as explained by others.
BTW, the MSDN page for VS 2008 and above does use the correct code.