文章目录
类里面的函数占用内存吗?
类占用成员变量的4个字节,类里面的函数占用内存吗?
每个对象都有自己的成员变量(非公用),但对于成员函数,每次调用时都是经由内存地址找到唯一的函数进行调用(是公用)【函数被调用,才会编译;函数一旦编译完,就有自己的内存地址;函数放在代码区】
代码如下:
#include <iostream>
using namespace std;
struct Person {
int age;
void run() {
cout << "person::run()" << age << endl;
}
};
int main()
{
Person person;
person.age = 11;
person.run();
Person person2;
person2.age = 12;
person2.run();
Person person3;
person3.age = 13;
person3.run();
getchar();
return 0;
}
查看反汇编
每次对象调用类中的函数,都是call 函数地址
13: Person person;
14: person.age = 11;
002423F2 mov dword ptr [ebp-0Ch],0Bh
15: person.run();
002423F9 lea ecx,[ebp-0Ch]
002423FC call 00241442
16:
17: Person person2;
18: person2.age = 12;
00242401 mov dword ptr [ebp-18h],0Ch
19: person2.run();
00242408 lea ecx,[ebp-18h]
0024240B call 00241442
20:
21: Person person3;
22: person3.age = 13;
00242410 mov dword ptr [ebp-24h],0Dh
23: person3.run();
00242417 lea ecx,[ebp-24h]
0024241A call 00241442