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

Where are member functions stored for an object?(对象的成员函数存储在哪里?)
本文介绍了对象的成员函数存储在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)