栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

  • 一个空的类的内存空间大小
#include "stdafx.h"
#include 
#include 
#include 
#include 
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 
#include 
#include 
#include 
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 
#include 
#include 
#include 
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 
#include 
#include 
#include 
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 
#include 
#include 
#include 
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 
#include 
#include 
#include 
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个字节,是因为虚函数的存在,因为有了虚函数的存在,导致系统往类对象中添加了一个指针,而这个指针正好指向这个虚函数表。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/384838.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号