2

In the following code, it seems that I can't get the correct address of the second function.
Link to Ideone : http://ideone.com/r07UZc

#include <stdio.h>

class A
{
public:
    __attribute__((noinline)) int func1();
    __attribute__((noinline)) int func2();
};

int A::func1()
{
    return 1;
}

int A::func2()
{
    return 2;
}

int main()
{
    printf("%p %p\n", &A::func1, &A::func2);
    return 0;
}

The printed values are : 0x80484d0 (nil)
The first address seem to be correct but not the second. Why ?

4

1 回答 1

2

指向成员函数的指针是非常奇怪的野兽。它们很少只是函数代码的地址。

即使它们是,它们仍然是与void*预期的非常不同的类型printf,因此printf调用未定义的行为试图将它们解释为void*.

在您的特定情况下,原因可能是成员函数指针比void*(可能是两倍宽?),因此第二个%p打印&A::func1. 但这只是一个猜想——唯一可以确定的是它是 UB。

鉴于标准中没有用于从指向成员函数的指针中获取地址的工具,如果没有特定于编译器的骇客、未定义的行为或两者兼而有之,可能无法做到这一点。

于 2013-09-11T13:18:04.443 回答