删除函数指针数组?

发布于 2024-12-16 10:56:40 字数 454 浏览 1 评论 0原文

这是我从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

帅哥哥的热头脑 2024-12-23 10:56:40

坦白说,正确的答案写在avakar的评论中。
正确的代码是

delete[] p;

delete *p; 是不正确的,原因有两个:

  1. 我们必须对所有动态分配的数组使用 delete[]。使用
    delete 将导致未定义的行为。
  2. 无法删除指向静态和成员函数的指针

Frankly speaking the right answer was written in the avakar's comment.
The right code is

delete[] p;

delete *p; is incorrect for two reasons:

  1. we must use delete[] for all dynamically allocated arrays. Using
    delete will cause an undefined behaviour.
  2. pointers to static and member functions cannot be deleted
秋风の叶未落 2024-12-23 10:56:40

如果我们添加 typedef,

typedef int (*FPtr)();

则可以重写 new 语句,

FPtr *p = new FPtr[7];

因此很明显,应该按照其他人的解释释放资源

delete[] p;


顺便说一句,VS 2008 及更高版本的 MSDN 页面确实使用了正确的代码。

int (**p) () = new (int (*[7]) ());
delete [] p;

If we add a typedef,

typedef int (*FPtr)();

the new statement can be rewritten as

FPtr *p = new FPtr[7];

so this is obvious that the resource should be released with

delete[] p;

as explained by others.


BTW, the MSDN page for VS 2008 and above does use the correct code.

int (**p) () = new (int (*[7]) ());
delete [] p;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文