A question about sizeof and class member function

核能气质少年 提交于 2019-12-10 21:39:07

问题


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

If I create an object of B, using

B* pb = new B;

Where is the memory of fn() locate?

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

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


回答1:


Where is the memory of fn() locate?

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.

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.

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.




回答2:


This:

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

Is for all practical purposes equivelant to the C code:

struct B
{
   int a;
};

void fn(B* bInstance);

Except in the C++ version bInstance is replaced with the this pointer. Both function's memory exists on the stack. So converting to the struct equivelant, what do you think the sizeof(B) would be?




回答3:


There will only be a pointer stored for a virtual function (in the vtable), not for non-virtual functions.




回答4:


1) B* pb = new B will allocate the memory on the heap. That means, among other things, that you will need to clean it up yourself via delete operator. Alternatively, you can place the pointer inside the smart pointer (shared_ptr, auto_ptr. scope_ptr) and let it do the clean up.

2) Because pointer is type, pointing to an object or null, has a defined size, usually equal to int.

3) fn() is NOT a virtual function, hence no memory is allocated in the object to vtable.



来源:https://stackoverflow.com/questions/561339/a-question-about-sizeof-and-class-member-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!