c++ - 关于函数指针数组声明的疑问

标签 c++ visual-studio-2010 pointers

我已经成功地用这段代码创建了一个“指向成员函数数组的指针”,并且它工作得很好......

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::beginstd::end,它们已经帮你处理好了。

最后,PTMF 基本上毫无值(value)。使用std::function

编辑:

可能发生的情况是,您搞砸了大小计算,而 VS 仅在它处于静态时才注意到。它在两个版本中可能同样被破坏。这就是 UB 适合您的地方。

再次编辑:您将 string 类型的对象传递给 printf 吗?如果这不是 const char* 的类型定义,那么 UB 你好。如果它...那么哎哟,那真的很糟糕。

关于c++ - 关于函数指针数组声明的疑问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15167864/

相关文章:

c - 我应该释放一个用于遍历链表的临时指针吗?

c++ - 如何将屏幕上的鼠标坐标转换为 3D 坐标

c++ - 来自 QWidget 的 QMainWindow 的 setWindowState

c++ - 为什么 vsperfmon 告诉我被调用函数的包含时间比根函数的包含时间长?

c - 通过 char* 指针将结构传递给 main

c - 计算数组中分配的内存时出现意外输出

c++ - 使用模板参数指定策略

C++ 双端队列 : when iterators are invalidated

c++ - MSVC 无法在 x86 上发送 16 字节对齐的函数参数

c# - 使用 TransformOnBuild 时无法引用 T4 模板中的依赖项程序集