Where are member functions stored for an object?(对象的成员函数存储在哪里?)
问题描述
我正在试验 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.
这篇关于对象的成员函数存储在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对象的成员函数存储在哪里?


基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01