我已经成功地用这段代码创建了一个“指向成员函数数组的指针”,并且它工作得很好......
typedef string (MyReportHelper::*reportFunctions)();
MyReportHelper helper;
void internalPointersTest(){
reportFunctions reportFunArray[] = {
&MyReportHelper::getVersion,
&MyReportHelper::getModel,
&MyReportHelper::getUsername,
};
int arrSize = sizeof(reportFunArray)/sizeof(reportFunArray[0]);
for(int i = 0; i < arrSize; i++){
string result = (helper.*reportFunArray[i])();
printf("%s", result);
}
}
但是,如果我将数组声明放在函数之外,如下面的代码,我会在 Visual Studio 中遇到缓冲区溢出或访问冲突,尽管代码编译。
typedef string (MyReportHelper::*reportFunctions)();
MyReportHelper helper;
reportFunctions reportFunArray[] =
{
&MyReportHelper::getVersion,
&MyReportHelper::getModel,
&MyReportHelper::getUsername,
};
void internalPointersTest(){
int arrSize = sizeof(reportFunArray)/sizeof(reportFunArray[0]);
for(int i = 0; i < arrSize; i++)
{
//next line will fail
string result = (helper.*reportFunArray[i])();
printf("%s", result);
}
}
有谁知道如何解释为什么我需要将其保留在函数范围内?
最佳答案
您没有使用 i
为数组建立索引。
其次,使用 std::begin
和 std::end
,它们已经帮你处理好了。
最后,PTMF 基本上毫无值(value)。使用std::function
。
编辑:
可能发生的情况是,您搞砸了大小计算,而 VS 仅在它处于静态时才注意到。它在两个版本中可能同样被破坏。这就是 UB 适合您的地方。
再次编辑:您将 string
类型的对象传递给 printf
吗?如果这不是 const char*
的类型定义,那么 UB 你好。如果它是...那么哎哟,那真的很糟糕。
关于c++ - 关于函数指针数组声明的疑问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15167864/