对象的成员函数存储在哪里?

我正在试验 C++ 以了解类/结构及其各自的对象在内存中的布局方式,并且我了解类/结构的每个字段都是其各自对象的偏移量(因此我可以有一个成员变量指针).

I'm experimenting with C++ to understand how class/structures and their respective objects are laid out in memory and I understood that each field of a class/structure is an offset into their respective object (so I can have a member variable pointer).

我不明白为什么,即使我可以拥有成员函数指针,以下代码也不起作用:

I don't understand why, even if I can have member function pointers, the following code doesn't work:

struct mystruct
{
    void function()
    {
        cout << "hello world";
    }
    int c;
};

int main() 
{ 
    unsigned int offset_from_start_structure = (unsigned int)(&((mystruct*)0)->c);
    unsigned int offset_from_start_structure2 = (unsigned int)(&((mystruct*)0)->function); // ERROR - error C2276: '&' : illegal operation on bound member function expression



    return 0;
}

我的问题是:为什么行

unsigned int offset_from_start_structure = (unsigned int)(&((mystruct*)0)->c);

编译并返回c"字段从结构和行开始处的偏移量

compile and returns me the offset of the "c" field from the start of the structure and the line

unsigned int offset_from_start_structure2 = (unsigned int)(&((mystruct*)0)->function);

甚至不编译?

推荐答案

成员函数或指向它们的指针不存储在对象中.(virtual 函数通常通过存储在表中的指针调用,对象具有指向该表的单个指针)这将巨大浪费内存.它们通常存储在代码存储器部分中,并且为编译器所知.对象 (*this) 通常作为 invisible 参数传递,以便函数在调用时知道要操作的对象.

Member functions or pointers to them aren't stored in the object. (virtual functions are typically called through a pointer stored in a table to which an object has a single pointer to) This would be a huge waste of memory. They're typically stored in a code memory section, and are known to the compiler. The object (*this) is typically passed as an invisible parameter so the functions know on which object to operate when they are called.

所以,用外行的话来说,你会

So, in layman terms, you'd have

 0x10001000    void A::foo
 ..........    {code for A::foo}

 push a;
 call A::foo (0x10001000)
 pop a;

其中 a 是您在其上调用 foo 的对象.

where a is the object you're calling foo on.

相关文章