我需要将一些成员函数指针转换为void*
指针(因为我需要将它们推送到 Lua 堆栈,但问题与 Lua 无关)。
我使用union
. 但是,当我将成员函数指针转换为 avoid*
并再次转换回来,然后尝试使用类的实例调用指针时,this
指针会损坏。void*
奇怪的是,如果我将指针转换回 C 风格的函数指针,并将指向类的指针作为它的第一个参数,那么这个问题就不会发生。
这是演示问题的一段代码:
#include <iostream>
using namespace std;
class test
{
int a;
public:
void tellSomething ()
{
cout << "this: " << this << endl;
cout << "referencing member variable..." << endl;
cout << a << endl;
}
};
int main ()
{
union
{
void *ptr;
void (test::*func) ();
} conv1, conv2;
union
{
void *ptr;
void (*func) (test*);
} conv3;
test &t = *new test ();
cout << "created instance: " << (void*) &t << endl;
// assign the member function pointer to the first union
conv1.func = &test::tellSomething;
// copy the void* pointers
conv2.ptr = conv3.ptr = conv1.ptr;
// call without conversion
void (test::*func1) () = conv1.func;
(t.*func1) (); // --> works
// call with C style function pointer invocation
void (*func3) (test*) = conv3.func;
(*func3) (&t); // --> works (although obviously the wrong type of pointer)
// call with C++ style member function pointer invocation
void (test::*func2) () = conv2.func;
(t.*func2) (); // `this' is the wrong pointer; program will crash in the member function
return 0;
}
那就是输出:
created instance: 0x1ff6010
this: 0x1ff6010
referencing member variable...
0
this: 0x1ff6010
referencing member variable...
0
this: 0x10200600f
referencing member variable...
zsh: segmentation fault (core dumped) ./a.out
这是编译器(GCC)中的错误吗?我知道void*
和(成员)函数指针之间的这种转换不符合标准,但奇怪的是,它在转换void*
为 C 风格的函数指针时有效。