繁体   English   中英

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

[英]Calling a C++ member function pointer: this-pointer gets corrupted

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

我是用union来做的。 但是,当我将成员函数指针转换为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;
}

这是输出:

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*和(member)函数指针之间的这种转换不符合标准,但奇怪的是,当将void*转换为C样式函数指针时,它可以工作。

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

cout << "sizeof(void*)=" << sizeof(conv1.ptr) << endl;
cout << "sizeof(test::*)=" << sizeof(conv1.func) << endl;

原因很简单。 考虑:

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

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

class Derived : public Base1, public Base2
{
 Derived();
};

当你在Derived上调用Foo时, this指针必须指向Base1::x 但是当你在Derived上调用Bar时, this指针必须指向Base2::j 因此,指向成员函数的指针必须包含函数的地址和“调整器”以纠正this指针,以指向函数期望作为this指针的正确类型的实例。

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

奇怪的是,在这里(在VS2005下),第一次和第三次调用工作正常,但第二次(使用conv3)失败,因为这被破坏了。

它看起来好像在你的实现上,指向成员函数类型void (test::*) ()的实例的第一个size(void*)字节恰好发生,在这种情况下,是内存中函数的地址。 作为一个实现细节,该函数可以调用,就像它是一个自由函数一样, this作为第一个参数。 这就是为什么conv3似乎有效。

但是,当尝试将第一个sizeof(void*)字节复制到指向成员函数类型的指针的不同实例时,运气已经用完。 conv2的其余部分中的未初始化的垃圾,一旦被解释为初始代码地址之后指向成员函数的其余部分,就会出现问题。 我怀疑那里有一些标志和偏移,记录有关虚函数和多重和虚继承的信息。 当该信息不正确时,东西出错了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM