【深入探索c++对象模型】类对象所需内存大小讨论续写

本文深入探讨了C++对象大小计算及其内存布局,包括char类型在对象中的大小变化,以及不同访问级别下数据成员的排列情况。通过代码示例展示了char类型的内存占用从1字节变为4字节的原因,并解释了public与private数据成员在内存中的存储顺序与声明顺序的关系。

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

#include<iostream>
#include<list>
using namespace std;
class Point3d
{
public:
	float x;
	static list<Point3d*> *freeelist;
	float y;
	static const int size = 250;
	char n;
	float z;
};

int main()
{
	Point3d model;
	cout << "char:" << sizeof(char) << endl;
	cout << "int:" << sizeof(int) << endl;
	cout << "float:" << sizeof(float) << endl;
	cout << "对象大小为:" << sizeof(model) << endl;
	cout << "the address of model:	"<<&model << endl;
	cout << "the address of the x member:	" << &(model.x) << endl;
	cout << "the address of the y member:	" << &(model.y) << endl;
	cout << "the address of the z member:	" << &(model.z) << endl;
	
}

这段代码的执行结果如下图所示:

          

单独对char类型进行sizeof运算时,是大小为1byte,但是放在对象中是,对类对象记性sizeof运算时,char的大小被调整为4bytes,这是基于编译器和计算机的Alignment的限制。在大部分机器中,为了更有效率的存取,此处将char补齐为4bytes。此外,对于c++对象,类中会出现多个access sections,为了验证在我机器上,gcc 4.7.3 编译器下,不同访问级别下数据成员的排列情况,代码如下图所示:

#include<iostream>
#include<list>
using namespace std;
class Point3d
{
public:
	float x;
	static list<Point3d*> *freeelist;
	float y;
	static const int size = 250;
private:
	char n;
public:
	float z;
};

int main()
{
	Point3d model;
	cout << "char:" << sizeof(char) << endl;
	cout << "int:" << sizeof(int) << endl;
	cout << "float:" << sizeof(float) << endl;
	cout << "对象大小为:" << sizeof(model) << endl;
	cout << "the address of model:	"<<&model << endl;
	cout << "the address of the x member:	" << &(model.x) << endl;
	cout << "the address of the y member:	" << &(model.y) << endl;
	cout << "the address of the z member:	" << &(model.z) << endl;
	
}

对于char数据仍然占有4bytes,保存在两个public access label中间,和其声明顺序相同。

此处有个疑问没有理解:在这种情况下,即public数据和private数据存储顺序和声明顺序相同,但是靠什么来识别它们不同数据成员的访问级别呢?根据对象的大小可以看出并没有添加其他成员来标示它们的访问级别?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值