sizeof(class) 转载,偶的笔记

原创 2007年09月23日 22:17:00

Determining the Size of a Class Object

By Girish Shetty

There are many factors that decide the size of an object of a class in C++. These factors are:
  1. Size of all non-static data members
  2. Order of data members
  3. Byte alignment or byte padding
  4. Size of its immediate base class
  5. The existence of virtual function(s) (Dynamic polymorphism using virtual functions).
  6. Compiler being used
  7. Mode of inheritance (virtual inheritance)


<script type="text/javascript"><!-- google_ad_client = "pub-2560316224908115"; google_ad_width = 336; google_ad_height = 280; google_ad_format = "336x280_as"; google_ad_type = "text_image"; google_ad_channel ="4570121886"; google_color_border = "FFFFFF"; google_color_bg = "FFFFFF"; google_color_link = "C30000"; google_color_url = "C30000"; google_color_text = "000000"; //--></script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script> <iframe width="336" scrolling="no" height="280" frameborder="0" name="google_ads_frame" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-2560316224908115&amp;dt=1190556476875&amp;lmt=1163954482&amp;prev_fmts=120x90_0ads_al&amp;format=336x280_as&amp;output=html&amp;correlator=1190556476828&amp;channel=4570121886&amp;url=http%3A%2F%2Fwww.cprogramming.com%2Ftutorial%2Fsize_of_class_object.html&amp;color_bg=FFFFFF&amp;color_text=000000&amp;color_link=C30000&amp;color_url=C30000&amp;color_border=FFFFFF&amp;ad_type=text_image&amp;ref=http%3A%2F%2Fwww.google.com%2Fsearch%3Fsource%3Dig%26hl%3Den%26q%3Dthe%2Bsize%2Bof%2Bc%252B%252B%2Bclass%26btnG%3DGoogle%2BSearch&amp;cc=61&amp;ga_vid=1884489229.1190556477&amp;ga_sid=1190556477&amp;ga_hid=506384435&amp;flash=9&amp;u_h=768&amp;u_w=1024&amp;u_ah=715&amp;u_aw=1024&amp;u_cd=32&amp;u_tz=480&amp;u_his=1&amp;u_java=true&amp;u_nplug=16&amp;u_nmime=61" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true"></iframe>

Size of all non-static data members

Only non-static data members will be counted for calculating sizeof class/object.
class A { 
private:
float iMem1;
const int iMem2;
static int iMem3;
char iMem4;
};
For an object of class A, the size will be the size of float iMem1 + size of int iMem2 + size of char iMem3. Static members are really not part of the class object. They won't be included in object's layout. <2>Order of data members The order in which one specifies data members also alters the size of the class.
class C { 
char c;
int int1;
int int2;
int i;
long l;
short s;
};
The size of this class is 24 bytes. Even though char c will consume only 1 byte, 4 bytes will be allocated for it, and the remaining 3 bytes will be wasted (holes). This is because the next member is an int, which takes 4 bytes. If we don't go to the next (4th) byte for storing this integer member, the memory access/modify cycle for this integer will be 2 read cycles. So the compiler will do this for us, unless we specify some byte padding/packing.

If I re-write the above class in different order, keeping all my data members like below:
class C { 
int int1;
int int2;
int i;
long l;
short s;
char c;
};
Now the size of this class is 20 bytes.

In this case, it is storing c, the char, in one of the slots in the hole in the extra four bytes.

Byte alignment or byte padding

As mentioned above, if we specify 1 byte alignment, the size of the class above (class C) will be 19 in both cases.

Size of its immediate base class

The size of a class also includes size of its immediate base class.

Lets take an example:
Class B { 
...
int iMem1;
int iMem2;
}

Class D: public B {
...
int iMem;
}
In this case, sizeof(D) is will also include the size of B. So it will be 12 bytes.

The existence of virtual function(s)

Existence of virtual function(s) will add 4 bytes of virtual table pointer in the class, which will be added to size of class. Again, in this case, if the base class of the class already has virtual function(s) either directly or through its base class, then this additional virtual function won't add anything to the size of the class. Virtual table pointer will be common across the class hierarchy. That is
class Base { 
public:
...
virtual void SomeFunction(...);
private:
int iAMem
};

class Derived : public Base {
...
virtual void SomeOtherFunction(...);
private:
int iBMem
};
In the example above, sizeof(Base) will be 8 bytes--that is sizeof(int iAMem) + sizeof(vptr). sizeof(Derived) will be 12 bytes, that is sizeof(int iBMem) + sizeof(Derived). Notice that the existence of virtual functions in class Derived won't add anything more. Now Derived will set the vptr to its own virtual function table.

Compiler being used

In some scenarios, the size of a class object can be compiler specific. Lets take one example:
class BaseClass { 
int a;
char c;
};

class DerivedClass : public BaseClass {
char d;
int i;
};
If compiled with the Microsoft C++ compiler, the size of DerivedClass is 16 bytes. If compiled with gcc (either c++ or g++), size of DerivedClass is 12 bytes.

The reason for sizeof(DerivedClass) being 16 bytes in MC++ is that it starts each class with a 4 byte aligned address so that accessing the member of that class will be easy (again, the memory read/write cycle).

Mode of inheritance (virtual inheritance)

In C++, sometimes we have to use virtual inheritance for some reasons. (One classic example is the implementation of final class in C++.) When we use virtual inheritance, there will be the overhead of 4 bytes for a virtual base class pointer in that class.
class ABase{ 
int iMem;
};

class BBase : public virtual ABase {
int iMem;
};

class CBase : public virtual ABase {
int iMem;
};

class ABCDerived : public BBase, public CBase {
int iMem;
};
And if you check the size of these classes, it will be:
  • Size of ABase : 4
  • Size of BBase : 12
  • Size of CBase : 12
  • Size of ABCDerived : 24
Because BBase and CBase are dervied from ABase virtually, they will also have an virtual base pointer. So, 4 bytes will be added to the size of the class (BBase and CBase). That is sizeof ABase + size of int + sizeof Virtual Base pointer.

Size of ABCDerived will be 24 (not 28 = sizeof (BBase + CBase + int member)) because it will maintain only one Virtual Base pointer (Same way of maintaining virtual table pointer).
<iframe width="336" scrolling="no" height="160" frameborder="0" name="ch_ad53" src="http://mm.chitika.net/minimall?w=336&amp;h=160&amp;client=cprogram&amp;noctxt=1&amp;sid=c++%20compiler&amp;url=http%3A//www.cprogramming.com/tutorial/size_of_class_object.html&amp;query=c++%20compiler&amp;nosearch=1&amp;cl_border=FFFFFF&amp;cl_title=C30000&amp;cl_text=000000&amp;ref=http%3A//www.google.com/search%3Fsource%3Dig%26hl%3Den%26q%3Dthe+size+of+c%252B%252B+class%26btnG%3DGoogle+Search&amp;cb=53" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true"></iframe>
 

C++类的大小——sizeof(class)

第一:孔磊d class CBase { }; 运行cout sizeof(CBase)=1; 为什么空的什么都没有是1呢?查资料……查啊查……OK这里了:先了解一个概念:类的实例化,所谓类的...
  • yangyangye
  • yangyangye
  • 2014年08月03日 22:06
  • 6305

sizeof class 详解(类的大小问题实验剖析)

类的大小问题实验剖析: 1、空类:C++编译器强制给这种类插入一个缺省成员,长度为1。如果有自定义的变量,变量将取代这个缺省成员。 class A {}; cout输出1 2...
  • u010069101
  • u010069101
  • 2016年04月02日 22:56
  • 589

类的大小——sizeof 的研究(1)

先看一个空的类占多少空间? class Base{public: Base(); ~Base();};      注意到我这里显示声明了构造跟析构,但是sizeof(Base)的结果是1.     因...
  • hairetz
  • hairetz
  • 2009年05月12日 17:09
  • 20423

C++ sizeof() Class / C++ Class sizeof()

// test1.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "iostream" using namespace std; cla...
  • weixingstudio
  • weixingstudio
  • 2013年09月28日 22:09
  • 1251

关于sizeof(空struct和空class)

struct empty_struct { }empty_struct; struct empty_class { }empty_class; 问:sizeof(empty_struct)和...
  • summer_liuwei
  • summer_liuwei
  • 2011年05月10日 17:02
  • 1867

C# struct class 在Marshal.SizeOf 的区别

struct 和 class 的区别 最重要的就是 value 和 object 区别了. 但是最近发现另外一个有趣的现象,但是很重要. 一个工程中,因为需要各种结构,于是在开始使用了 ...
  • norsd
  • norsd
  • 2011年12月09日 14:49
  • 3452

使用sizeof()计算类的大小

《剑指offer》这本书里第22页有讲到sizeof()计算类大小的问题,在网上查阅了一些资料,进行了一些总结。欢迎补充指正! 1、类的大小       类的sizeof()大小一般是类中的所有成员的...
  • JIEJINQUANIL
  • JIEJINQUANIL
  • 2016年05月18日 21:12
  • 2285

C++类的实例化对象的大小之sizeof()

C++类的实例化对象的大小之sizeof()
  • houqingdong2012
  • houqingdong2012
  • 2014年10月19日 20:02
  • 2282

C++类的大小——sizeof()

先看这么个问题——已知:class CBase{    int  a;    char *p;};那么运行cout这个应该很简单,两个成员变量所占的大小有嘛——8。可由时候人就是爱犯这个错误:这么简单...
  • lishengwei
  • lishengwei
  • 2008年05月08日 14:54
  • 12376

sizeof(class)

本文标题的形式显然是非正规化的,意在说明对一个类
  • lc_910927
  • lc_910927
  • 2014年06月13日 00:01
  • 977
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:sizeof(class) 转载,偶的笔记
举报原因:
原因补充:

(最多只允许输入30个字)