C ++中成员函数的内存分配 [英] Memory allocation for member functions in C++

查看:65
本文介绍了C ++中成员函数的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
using namespace std;
class A
{

};
class B
{
        public:
                void disp()
                {
                        cout<<" This is not virtual function.";
                }
};
class C
{
        public:
                virtual void disp()
                {
                        cout<<"This is virtual function.";
                }
};
int main()
{
        cout<<"class A"<<sizeof(A)<<endl;
        cout<<"class B"<<sizeof(B)<<endl;
        cout<<"class C"<<sizeof(C)<<endl;
        return 0;
}

A类和B类的大小都只有1个字节。

sizeof class A and class B are both 1 byte only.What about the memory allocation for member function disp in B.

推荐答案

对于类的每个实例,仅将内存分配给其成员变量,即该类的每个实例都无法获得其自身的成员函数副本。所有实例共享相同的成员函数代码。您可以想象它是编译器为每个成员函数传递一个隐藏的 this 指针,以便它在正确的对象上运行。在您的情况下,由于C ++标准明确禁止大小为0的对象,因此类A和类B的最小可能大小为1。对于类C,由于存在虚函数,因此类C的每个实例都将具有指向其v的指针。 -table(尽管这是特定于编译器的)。因此,此类的大小将为sizeof(pointer)。

For each instance of the class, memory is allocated to only its member variables i.e. each instance of the class doesn't get it's own copy of the member function. All instances share the same member function code. You can imagine it as compiler passing a hidden this pointer for each member function so that it operates on the correct object. In your case, since C++ standard explictly prohibits 0 sized objects, class A and class B have the minimum possible size of 1. In case of class C since there is a virtual function each instance of the class C will have a pointer to its v-table (this is compiler specific though). So the sizeof this class will be sizeof(pointer).

这篇关于C ++中成员函数的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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