做开发一定会调用到自己定义或者他人定义的函数,而函数调用必须通过堆栈来完成。
函数堆栈实际上使用的是程序的堆栈内存空间,虽然程序的堆栈段是系统为程序分配的一种静态数据区,但是函数堆栈却是在调用到它的时候才动态分配的。
#include "stdafx.h" #include <iostream> using namespace std; class TestArrange { public: long m_lng; char m_ch1; TestArrange() { m_lng = 0; m_ch1 = 'a'; m_int = 0; m_ch2 = 'a'; } const int* GetIntAddr() { return &m_int; } const char* GetChar2Addr() { return &m_ch2; } private: int m_int; char m_ch2; }; int _tmain(int argc, _TCHAR* argv[]) { TestArrange test; cout<<"Address of test object:"<<&test<<endl; cout<<endl; cout<<"Address of m_lng:"<<&(test.m_lng)<<endl; cout<<endl; printf("Address of m_ch1:%p ",&(test.m_ch1)); /*cout<<""<<&(test.m_ch1)<<endl;*/ cout<<endl; cout<<"Address of m_int:"<<test.GetIntAddr()<<endl; cout<<endl; cout<<"Address of m_ch2:"<<(void*)test.GetChar2Addr()<<endl; system("pause"); return 0; }
输出结果:
Address of test object:0031FC9C
Address of m_lng:0031FC9C
Address of m_ch1:0031FCA0
Address of m_int:0031FCA4
Address of m_ch2:0031FCA8
请按任意键继续. . .
在C语言的格式化I/O中,常使用%p来输出内存的地址值;而在C++中,除了字符串的地址无法直接输出外,其他类型的地址都可以使用"&"输出。
堆栈是自动管理的,也就是说局部变量的创建和销毁、堆栈的释放都是函数自动完成的,不需要程序猿的干涉。局部变量在程序执行流到达它的定义的时候创建,在退出其所在程序块的地方销毁,堆栈在函数退出的时候清退(还给程序堆栈段)。
函数堆栈主要有三个用途:在进入函数前保存环境变量和返回地址,在进入函数时保存实参的拷贝,在函数体内保存局部变量。