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++ 类对象的内存大小分析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-29易优CMS安装常见问题汇总-icode9专业技术文章分享
- 2024-06-28易优新手必读安装教程-icode9专业技术文章分享
- 2024-06-28忘记eyoucms后台密码怎么办?-icode9专业技术文章分享
- 2024-06-26终极指南:Scrum中如何设置需求优先级
- 2024-06-26AI大模型企业应用实战(25)-为Langchain Agent添加记忆功能
- 2024-06-26小白家庭 nas 搭建方案-icode9专业技术文章分享
- 2024-06-23AI大模型企业应用实战(14)-langchain的Embedding
- 2024-06-23AI大模型企业应用实战(15)-langchain核心组件
- 2024-06-23AI大模型企业应用实战(16)-langchain核心组件
- 2024-06-23AI 大模型企业应用实战(06)-初识LangChain