对函数指针数组声明有疑问
Doubt about array of function pointers declaration
我已经设法用这段代码制作了一个"指针到成员函数数组",它工作得很好…
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基本上毫无价值。使用std::function
可能发生的事情是你搞砸了大小计算,而VS只碰巧注意到它是静态的。在两个版本中,它可能同样被破坏了。这就是你的UB。
再次编辑:您将类型为string
的对象传递给printf
?如果这是不是一个类型定义为const char*
,那么你好UB。如果是…
string result = (helper.*reportFunArray[i])();
printf("%s", result);
我假设string
实际上是std::string
?你是using namespace std;
吗?
在这种情况下,printf("%s", result);
很可能崩溃,因为它会将天知道的东西解释为c风格字符串的第一个字符。下面的工作吗?
string result = (helper.*reportFunArray[i])();
std::cout << result;
相关文章:
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 在C++中声明一个函数时,它需要有函数本身的参数吗
- 我在范围内未声明的错误类有问题
- 如果 x.h 仅由函数声明组成,为什么有必要在 x 中包含 x.h.cpp
- 有没有办法一次声明相同类型的多个对象,并通过一个表达式立即使用相同的右值初始化它们?
- 我对 gdb 内存地址有疑问
- 这个模板声明有什么问题
- 符号"重新声明(有符号/无符号,精度)与
- 这个从 std::vector 继承的类声明有问题吗?
- 这两个声明有什么区别?
- 我的成员模板函数声明有什么问题
- 如果我声明有符号的字符,ASCII值会改变吗
- 这个结构声明有什么问题?
- C++:"vector<int>::size_type variable"——以这种方式声明有什么意义?
- &C和*C声明有什么区别?
- 对文件I/O有疑问
- 类成员函数声明有疑问
- 这个迭代器声明有什么问题
- 对循环中的作用域有疑问
- 对函数指针数组声明有疑问