在结构外部调用指向函数的指针

Joh*_*Doe 3 c++ member-function-pointers

我有一个结构,里面是一个指向同一结构的函数的指针.现在我需要调用一个指向结构外部函数的指针.我举一个下面的代码示例:

#include <iostream>

struct test {
    void (test::*tp)(); // I need to call this pointer-to-function
    void t() {
        std::cout << "test\n";
    }
    void init() {
        tp = &test::t;
    }
    void print() {
        (this->*tp)();
    }
};
void (test::*tp)();

int main() {
    test t;
    t.init();
    t.print();
    (t.*tp)(); // segfault, I need to call it
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 7

(t.*tp)();尝试调用tp在全局命名空间中定义的成员函数指针void (test::*tp)();,注意它实际上被初始化为空指针(通过零初始化1),调用它导致UB,一切皆有可能.

如果你想调用的数据成员tpt(即,t.tp在对象上)t,你应该将其更改为

(t.*(t.tp))();
     ^
     |
     ---- object on which the member function pointed by tp is called
Run Code Online (Sandbox Code Playgroud)

如果您确实想要调用全局tp,则应该适当地初始化它,例如

void (test::*tp)() = &test::t;
Run Code Online (Sandbox Code Playgroud)

然后你可以

(t.*tp)(); // invoke global tp on the object t
Run Code Online (Sandbox Code Playgroud)

1关于零初始化

在以下情况下执行零初始化:

1)对于具有静态或线程本地存储持续时间的每个命名变量that is not subject to constant initialization (since C++14),在任何其他初始化之前.