c++ - 新分配指向函数的指针是否合法?
问题描述
指向函数的指针不是纯数据指针,因为它们不能存储在 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 ;
}
解决方案
虽然函数指针不是对象指针,但“指向某种类型函数的指针”仍然是对象类型[basic.types]/8。因此,函数指针本身就是对象,只是它们指向的东西不是。
因此,您肯定可以通过 new 表达式创建函数指针类型的对象……</p>
推荐阅读
- c# - 如何为项目列表编写通用移动平均线?
- javascript - 正则表达式对字符串中的递归模式进行分组并将捕获组作为数组返回
- angular - Angular + Firebase 错误“传播类型只能从对象类型创建。”
- mongodb - 聚合 Mongo - 在对象数组中按其中一个值排序
- xml - 使用 XSL/XSLT 从同名的兄弟元素中选择一个子元素
- reactjs - Next JS getInitialProps 中缺少请求信息
- javascript - 如何在 AR 模式下放置 a-image 以使其旋转面向用户?
- opengl - 在 OpenGL 中使用多个光源时如何解决我的光照问题(片段着色器问题?)
- html - 每当我将它放在引导导航栏上时,svg 徽标格式都会发生变化
- python - 如何使用numpy将嵌套数组合并到维度更大的数组?