首先要知道c++编译器怎么对内存进行分区的
C++编译的程序占用的内存分为以下几个部分:
1. 栈区(stack): 由编译器自动分配释放,存放函数的参数值,局部变量的值等。其操作方式类似于数据结构中的栈。
2. 堆区(heap): 一般由程序员分配释放,若程序员不释放,程序结束时可能由操作系统回收 。注意它与数据结构中的堆是两回事,分配方式倒是类似于链表。
3. 数据区: 主要包括静态全局区和常量区,如果要站在汇编角度细分的话还可以分为很多小的区。
(1)全局区(静态区static): 全局变量和静态变量的存储是放在一块的,初始化的全局变量和静态变量在一块区域, 未初始化的全局变量和未初始化的静态变量在相邻的另一块区域。 程序结束后有系统释放。
(2)常量区: 常量字符串就是放在这里的。 程序结束后由系统释放。
4. 代码区: 存放函数体的二进制代码。
如下图所示:
然后,我们现有段有意思的程序:
#include "stdafx.h"
#include <iostream>
using namespace std;
class temp_class01
{
public:
int temp_a; //4字节
int temp_b; //4字节
int temp_c; //4字节
};
class temp_class02
{
public:
int temp_a; //4字节
int temp_b; //4字节
int temp_c; //4字节
static int m; //4字节
public:
int getTemp_a() const { return temp_a; } //函数指针4字节
void setTemp_a(int val) { temp_a = val; } //函数指针4字节
};
struct temp_struct01
{
int temp_a; //4字节
int temp_b; //4字节
int temp_c; //4字节
};
struct temp_struct02
{
int temp_a; //4字节
int temp_b; //4字节
int temp_c; //4字节
static int m; //4字节
int getTemp_a() const { return temp_a; } //函数指针4字节
void setTemp_a(int val) { temp_a = val; } //函数指针4字节
};
int _tmain(int argc, _TCHAR* argv[])
{
cout << "temp_class01的大小:" << sizeof(temp_class01) <<"字节"<< endl;
cout << "temp_class02的大小:" << sizeof(temp_class02) << "字节" << endl;
cout << "temp_struct01的大小:" << sizeof(temp_struct01) << "字节" << endl;
cout << "temp_struct02的大小:" << sizeof(temp_struct02) << "字节" << endl;
system("pause");
return 0;
}
从这个程序的运行结果可以看出,类和结构体当中的静态成员和成员函数并没有占有空间,说明他们并没有被安排在栈空间当中。所以在我们定义一个新类的时候编译器只是在对象中保存一个入口地址从而调用它们。