C ++类的大小 [英] Size of C++ classes
问题描述
以下是打印不同类的大小的代码
Here is the code which prints size of different classes
#include <iostream>
using namespace std;
class EmptyClass
{
};
class AbstractClass
{
public:
virtual void funcOne() = 0;
virtual void funcTwo() = 0;
};
class NotAbstrClass
{
public: int virtFunc( int );
};
class MixClass
{
public:
virtual void clFunc( int );
static int i;
int j;
};
int main()
{
// Print size of class or class objects
cout<<"Size of empty class: "<< sizeof(EmptyClass)<<endl;
cout<<"Size of Abstract class :"<< sizeof(AbstractClass)<<endl;
cout<<"Size of Non Abstract class: "<< sizeof(NotAbstrClass)<<endl;
cout<<"Size of Mix class: "<< sizeof(MixClass)<<endl;
return 0;
}
C ++ 11编译器上的程序输出为
The output of the program on C++11 compiler is
Size of empty class: 1
Size of Abstract class :4
Size of Non Abstract class: 1
Size of Mix class: 8
我了解为什么Empty类的大小为1 空类对象的大小。对于抽象类,对象存储用于实现虚拟函数调用机制的指针。但是其他类对象(NotAbstrClass和MixClass)的大小又如何呢?
I understand why Empty class has size 1 Size of empty class object. For abstract class, the object stores a pointer for implementing virtual function call mechanisms. But what about the sizes of other class objects (NotAbstrClass and MixClass) ?
推荐答案
根据Girish Shetty:
According to Girish Shetty:
有很多因素决定C ++中类对象的大小。
There are many factors that decide the size of an object of a class in C++.
这些因素是:
- 所有非静态数据成员的大小
- 数据成员的顺序
- 字节对齐或字节填充
- 直接基类的大小
- 存在虚函数(使用虚函数的动态多态性)。
- 正在使用编译器
- 继承方式(虚拟继承)
- Size of all non-static data members
- Order of data members
- Byte alignment or byte padding
- Size of its immediate base class
- The existence of virtual function(s) (Dynamic polymorphism using virtual functions).
- Compiler being used
- Mode of inheritance (virtual inheritance)
这里有一些相关的网站,我认为这对您有帮助。
Here there are some related website, I think it can be helpful to you.
确定类对象的大小: http://www.cprogramming.com/tutorial/size_of_class_object.html
内存布局: http://www.phpcompiler.org/articles/virtualinheritance.html
并且,如果您使用MVSC,则可以使用 -d1reportAllClassLayout
转储解决方案中所有类的所有内存布局那:
And, if you use MVSC, you can dump all memory layout of all class in your solution with -d1reportAllClassLayout
like that:
cl -d1reportAllClassLayout main.cpp
这篇关于C ++类的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!