C++各种数据类型所占内存大小详解
作者:_不会dp不改名_
这篇文章主要介绍了C++各种数据类型所占内存大小,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
注意
基本数据类型占用数据大小还与系统位数有关,我们假设为64位的系统
1.基本数据类型
- char : 1
- short: 2
- int: 4
- long long: 8
- float:4
- double:8
- bool:1
2. 指针与引用
2.1指针
指针所占的内存空间不随数据类型变化而变化
其实质是地址空间
所以均为8
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>
using namespace std;
typedef struct _node{
char c1;
char c2;
char c3;
long long i1;
}node;
int main(){
int i = 1;
short t = 12;
char c ='c';
long long ll = 521;
node q;
node *pn = &q;
int *pi = &i;
short *pt = &t;
char *pc = &c;
printf("%d\n",sizeof(pn));
printf("%d\n",sizeof(pi));
printf("%d\n",sizeof(pt));
printf("%d\n",sizeof(pc));
}
// 8 8 8 82.2 引用
引用又叫别名
其所占空间与引用对象所占空间一致
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>
using namespace std;
typedef struct _node{
char c1;
char c2;
char c3;
long long i1;
}node;
int main(){
int i = 1;
short t = 12;
char c ='c';
long long ll = 521;
node q;
node &rn = q;
int &ri = i;
short &rt = t;
char &rc = c;
printf("%d\n",sizeof(rn));
printf("%d\n",sizeof(ri));
printf("%d\n",sizeof(rt));
printf("%d\n",sizeof(rc));
}
// 16 4 1 23.构造类型
3.1 struct
由于struct有**边界对齐(凑4或8)**的要求
所以尽量将同类型的写一块
类型小的放在最前面
关于边界对齐举几个例子就好说了
类型A1的大小为4
struct p{
char c1;
short s1;
}A1;神奇的是类型A2的大小也为4
但多了一个char类型变量
struct p{
char c1;
char c2;
short s1;
}A2;如果交换 类型A3的大小为6
struct p{
char c1;
short s1;
char c2;
}A3;在A1类型 基础上添加一个int 变量成员
类型A4大小为8
struct p{
char c1
short s1;
int i1;
}A4;在A3基础上加一个int 变量成员
A5大小为 12
struct p{
char c1;
short s1;
char c2;
int i1;
}A5;这样似乎还不知道怎么算边界对齐的类型大小
考虑类型A6
typedef struct _p{
char c1;
char c2;
char c3;
}p;这时候A6 的大小为3
说明了边界对齐只发生在有不同数据类型时
在A6 基础上加一个int类型数据得到** A7**
大小为 8
typedef struct _p{
char c1;
char c2;
char c3;
int i1;
}p;如果A6上加上个long long 类型数据呢
A8大小为 16
typedef struct _p{
char c1;
char c2;
char c3;
long long ll1;
}p;总结
- 当变量中不存在8字节的变量时(不足4补充成4的倍数)
- 总是向4字节对齐(多个变量)
- 出现的话就8字节对齐
3.2 union
这个不用说,直接取里面成员需要的最大空间
共用体u所用空间 4
union p{
char c1;
short s1;
char c2;
int i1;
}u;3.3 enum
枚举变量可以当作一个int
占用4B
enum _color{
red = 1,
yellow = 2,
blue = 3
}Color;3.4 class
一个空类占多少字节呢?
输出结果为1
class p{
};
int main(){
printf("%d\n", sizeof(p));
} 给它加上一个自定义的成员函数呢
class p{
public:
void pint(void){
printf("member function\n");
}
};答案还是1,那是不是加的不够多?
class p{
public:
void pint(void){
printf("member function\n");
}
void pint1(void){
printf("member function1\n");
}
void pint2(void){
printf("member function2\n");
}
void pint3(void){
printf("member function3\n");
}
};经过几次实验,类大小似乎与类的成员函数无关
可以猜测一下,一个类的对象只是将成员函数放在
类的相关位置,每个对象调用只是取这个类的位置然后调用成员函数
成员函数并不占用对象空间,所以
类的大小只取决于定义的数据类型的大小
例如
class p{
public:
char c1;
};该类成员对象的大小为1
类会有边界对齐的规则吗?
答案是 是!
实验一下
class p{
public:
char c1;
long long ll1;
int t2;
};这个类(所产生对象)的大小为 24 !
所以类(对象)的大小相当于把它看成结构体的大小
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
