调用C++成员函数指针:this-pointer被破坏

Alf*_*mer 5 c++ pointers function member void

我需要将一些成员函数指针转换为void*指针(因为我需要将它们推送到Lua堆栈,但问题不是Lua相关).

我是这样做的union.但是当我将成员函数指针转换为a void*并再次返回然后尝试使用该类的实例调用指针时,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;
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

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

这是编译器(GCC)中的错误吗?我知道void*和(成员)函数指针之间的这种转换不符合标准,但奇怪的是,它在转换void*为C样式函数指针时起作用.

Dav*_*rtz 5

将这两行添加到您的代码中,答案将是明确的:

cout << "sizeof(void*)=" << sizeof(conv1.ptr) << endl;
cout << "sizeof(test::*)=" << sizeof(conv1.func) << endl;
Run Code Online (Sandbox Code Playgroud)

原因很简单.考虑:

class Base1
{
 public:
 int x;
 void Foo();
 Base1();
};

class Base2
{
 public:
 float j;
 void Bar();
 Base2();
};

class Derived : public Base1, public Base2
{
 Derived();
};
Run Code Online (Sandbox Code Playgroud)

当你调用Fooa时Derived,this指针必须指向Base1::x.但是当你打电话Bar给a时Derived,this指针必须指向Base2::j!因此,指向成员函数的指针必须包含函数的地址和"调整器",以纠正this指针指向函数期望作为this指针的正确类型的实例.

您正在丢失调整器,导致this指针随机调整.