关于sizeof和类成员函数的问题 [英] A question about sizeof and class member function

查看:147
本文介绍了关于sizeof和类成员函数的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 class B
{
   public:
     int a;
     void fn();
}

如果我创建一个B的对象,使用

If I create an object of B, using

B* pb = new B;

fn()的内存在哪里?

Where is the memory of fn() locate?

对象中是否有指向fn()的内存指针的指针?

Is there a pointer in object that pointing at the memory loaction of fn()?

如果是,为什么sizeof(B)返回值,

If yes, why sizeof(B) returns the value as if there is no pointer in object at all?

推荐答案


fn()的内存位置在哪里?

Where is the memory of fn() locate?

因为这是一个正常的函数,在程序代码部分的某处。此位置对于类的所有实例是相同的。事实上,它与 B 通过 pb 的实例化无关。

Since it's a normal function, somewhere in the code section of your program. This location is the same for all instances of the class. In fact, it has got nothing to do with the instantiation of B via pb.


对象中是否有指向fn()的内存指针的指针?

Is there a pointer in object that pointing at the memory loaction of fn()?

否。对于正常成员函数,这不是必需的,因为地址在编译时是已知的(或者最晚在链接时间);因此不必在运行时单独存储。

No. For a normal member function this isn't required since the address is known at compile time (or, at the latest, at link time); it therefore doesn't have to be stored separately at runtime.

对于虚函数,情况有所不同。虚拟函数指针存储在数组中(简称为虚函数指针表或vtable)。每个类都有一个这样的vtable,每个实例给一个类存储一个指向该vtable的指针。这是必要的,因为如果 Base 类型的指针/引用指向子类 Derived 知道调用哪个函数的方式;而是在运行时通过在相关联的vtable中查找来计算正确的函数。 vtable指针在 sizeof 对象中也很明显。

For virtual functions, the situation is different. Virtual function pointers are stored in an array (called "virtual function-pointer table" or "vtable" for short). Each class has one such vtable and each instance to a class stores a pointer to that vtable. This is necessary because if a pointer/reference of type Base points to a sub-class Derived, the compiler has no way of knowing which function to call; rather, the correct function is calculated at runtime by looking it up in the associated vtable. The vtable pointer is also evident in the sizeof the object.

这篇关于关于sizeof和类成员函数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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