为对象存储的成员函数在哪里? [英] Where are member functions stored for an object?

查看:90
本文介绍了为对象存储的成员函数在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在试验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.

所以,在layman术语中,你会有

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 开。

这篇关于为对象存储的成员函数在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆