简体   繁体   中英

Deleting an array of pointers to functions?

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?

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM