C++ 类对象的内存空间大小浅析

本文通过实例探讨了C++类对象在不同情况下内存空间的占用情况,包括空类、添加非静态成员函数、非静态成员变量、虚函数以及静态成员变量和函数等。总结指出,一个类对象至少占用一个字节,非静态成员不占用对象内存,虚函数引入4字节用于指向虚函数表,静态成员和函数不计入对象大小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 一个空的类的内存空间大小
#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++基础与深度解析

技术交流可以去我主页左侧扫码进群

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Christo3

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值