- In the case of empty class
sample code:
class B{
};
int _tmain(int argc, _TCHAR* argv[])
{
cout << sizeof(B) << endl; //占8个字节
system("pause");
return 0;
}
申明了一个空类B,并在main函数中输出B类的占据字节数
- Output Results:
can clearly be seen, Class B comprises a size of 1 byte.
Reason that accounts for 1 byte:
empty class can be instantiated, as long as the instantiation must occupy memory addresses in memory, and does not have any empty class constructor and a virtual function, the compiler will default to an empty class plus an implicit byte. The system will think he is instantiated.
- Class virtual function
class B{
public:
B(){
};
virtual ~B(){
}
};
int _tmain(int argc, _TCHAR* argv[])
{
cout << sizeof(B) << endl; //占8个字节
system("pause");
return 0;
}
-
Output:
-
The main reason is the need to construct a virtual function class virtual function table, virtual function table needs to determine the specific virtual function pointer memory address using that function (which relates to the problem of overloaded functions), a virtual function pointer 4 bytes, examples therefore requires 4 bytes of memory address.
-
Class members include
class B{
public:
B(){
};
int demo;
char ss;
};
int _tmain(int argc, _TCHAR* argv[])
{
cout << sizeof(B) << endl; //占4个字节
system("pause");
return 0;
}
Run Results:
Causes occupies 8 bytes here is an int 4 bytes, a 1 byte char, but because of byte alignment, so the second element accounted for 4 bytes .
What is byte aligned:现代计算机中内存空间都是按照byte划分的,从理论上讲似乎对任何类型的变量的访问可以从任何地址开始,但实际情况是在访问特定类型变量的时候经常在特定的内存地址访问,这就需要各种类型数据按照一定的规则在空间上排列,而不是顺序的一个接一个的排放,这就是对齐。
Simple introduction, we can follow further in-depth look, basically, so that we can account for the number of bytes C ++ class to have a clear understanding of the