如何检查函数指针是否存在

How to check a function pointer exists

本文关键字:函数 指针 是否 存在 检查 何检查      更新时间:2023-10-16

在C++中,我试图编写一个带有函数指针的函数。如果为不存在的函数传递函数指针,我希望能够抛出异常。我试着像处理普通指针一样处理函数指针,并检查它是否为空

#include <cstddef>
#include <iostream>
using namespace std;
int add_1(const int& x) {
    return x + 1;
}
int foo(const int& x, int (*funcPtr)(const int& x)) {
    if (funcPtr != NULL) {
        return funcPtr(x);
    } else {
        throw "not a valid function pointer";
    }
}
int main(int argc, char** argv) {
try {
    int x = 5;
    cout << "add_1 result is " << add_1(x) << endl;
    cout << "foo add_1 result is " << foo(x, add_1) << endl;
    cout << "foo add_2 result is " << foo(x, add_2) << endl; //should produce an error
}
catch (const char* strException) {
    cerr << "Error: " << strException << endl;
}
catch (...) {
    cerr << "We caught an exception of an undetermined type" << endl;
}
    return 0;
}

但这似乎不起作用。最好的方法是什么?

检查NULL是可以的。但不可能将指针传递给一个一开始就不存在的函数。所以你不必担心这个。虽然可以只声明一个函数而不定义它并传递它的地址。在这种情况下,你会得到链接器错误。

如果你传递的指针不存在,它会自动抛出一个错误,如果你声明一个指针,那么你必须用null初始化它以避免垃圾值,所以与null进行比较没有任何作用。

如果你仍然想检查,然后尝试分配一些函数(如add、sub等(,如果需要,则ok,如果不需要,则会再次显示前面提到的错误。

#include<cstddef>
#include <iostream>
using namespace std;
int foo(const int& x, int (*funcPtr)(const int& x)) {
    if (*funcPtr != NULL) {
        return funcPtr(x);
    }
    else
    {
        cout << "not a valid function pointer";
    }
}

如果您想"抛出"异常,那么您也需要"捕获"它。简而言之,您的代码失败的原因有两个:,1( 您没有检查函数指针的值。2( 您没有正确捕获抛出的异常。