一个空的类的内存空间大小
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
class Base
{
public:
};
int _tmain(int argc, _TCHAR* argv[])
{
Base b;
int size = sizeof(b);
cout << size << endl;
return 0;
}
在类空间中添加非静态成员函数后的内存空间大小
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
class Base
{
public:
void fun1(){};
void fun2(){};
};
int _tmain(int argc, _TCHAR* argv[])
{
Base b;
int size = sizeof(b);
cout << size << endl;
return 0;
}
在类中添加非静态的成员变量后的内存空间大小
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
class Base
{
public:
//void fun1(){};
//void fun2(){};
int a;
};
int _tmain(int argc, _TCHAR* argv[])
{
Base b;
int size = sizeof(b);
cout << size << endl;
return 0;
}
在类中添加虚函数后的内存空间大小
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
class Base
{
public:
//void fun1(){};
//void fun2(){};
//int a;
virtual void fun3(){};
//static int b;
//static void fun4(){};
};
int _tmain(int argc, _TCHAR* argv[])
{
Base b;
int size = sizeof(b);
cout << size << endl;
return 0;
}
在类中添加静态成员变量和静态成员函数后的内存空间大小
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
class Base
{
public:
//void fun1(){};
//void fun2(){};
//int a;
static int b;
static void fun4(){};
};
int _tmain(int argc, _TCHAR* argv[])
{
Base b;
int size = sizeof(b);
cout << size << endl;
return 0;
}
计算类对象的内存空间大小
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
class Base
{
public:
void fun1(){};
void fun2(){};
int a; // 占4字节
virtual void fun3(){}; //占4字节
static int b;
static void fun4(){};
char c; //占4字节 (内存对齐)
};
int _tmain(int argc, _TCHAR* argv[])
{
Base b;
int size = sizeof(b);
cout << size << endl;
return 0;
}
总结:
-
一个类对象至少占用一个字节的内存空间。
-
类对象的非静态成员函数以及其静态的成员变量和静态的成员函数都不占用类对象的内存空间。
-
类对象中如果至少存在一个虚函数则其占用类对象的内存空间为4个字节。类对象增加4个字节,是因为虚函数的存在,因为有了虚函数的存在,导致系统往类对象中添加了一个指针,而这个指针正好指向这个虚函数表。
拓展
另推荐一门深蓝学院开设讲解C++基础与深度解析的线上课程,可以对整体框架的细节理解和运用都能起到很好的帮助:
链接:C++基础与深度解析