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

Joh*_*ohn 5 c++ pointers exception-handling function-pointers exception

在 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Rak*_*kib 4

检查 NULL 就可以了。但是不可能将指针传递给本来就不存在的函数。所以您不必担心这个问题。尽管可以只声明一个函数而不定义它并传递它的地址。在这种情况下,您将收到链接器错误。

  • @KeithThompson 你不能只传递一个未初始化的函数指针吗? (4认同)
  • 所以,综上所述,这个答案的第二句和第三句是错误的。 (4认同)