C++ 类对象的内存大小分析

2021/10/30 7:16:36

本文主要是介绍C++ 类对象的内存大小分析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

  • 一个空的类的内存空间大小
#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++ 类对象的内存大小分析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程