首页 > 解决方案 > 新分配指向函数的指针是否合法?

问题描述

指向函数的指针不是纯数据指针,因为它们不能存储在 void* 指针中。尽管如此,我似乎可以将函数指针的副本存储在动态内存中(在 gcc 和 clang 中),如下面的代码所示。根据 C++ 标准,这样的代码是否合法,或者这可能是某种编译器扩展?

此外,生成的指向函数指针的指针表现为纯数据指针:我可以将它存储在 void* 中,并通过 static_cast 从 void* 中检索它。标准是否保证了这种行为?

int main()
{
  extern void fcn();
  void (*fcnPtr)() = &fcn;
  void (**ptrToFcnPtr)() = nullptr;

  //Make the copy of fcnPtr on the heap:
  ptrToFcnPtr = new decltype(fcnPtr)(fcnPtr);
  //Call the pointed-to function : 
  (**ptrToFcnPtr)();

  //Save the pointer in void* :
  void *ptr = ptrToFcnPtr;
  //retrieve the original ptr: 
  auto myPtr = static_cast< void(**)() > (ptr) ; 
  //free memory:
  delete ptrToFcnPtr ;

}

标签: c++

解决方案


虽然函数指针不是对象指针,但“指向某种类型函数的指针”仍然是对象类型[basic.types]/8。因此,函数指针本身就是对象,只是它们指向的东西不是。

因此,您肯定可以通过 new 表达式创建函数指针类型的对象……</p>


推荐阅读