C++ 变量内存分区

236 阅读1分钟
  • C++中在程序运行前分为全局区和代码区

  • 代码区的特点是共享和只读

  • 全局区中存放全局变量,静态变量,常量

  • 常量区中存放在const修饰的全局常量 和字符串常量 image.png

  • 局部变量

int & test02(){
    int a = 10;
    return a;
}
int &ref = test02();
cont << "ref = " << ref << endl;
cont << "ref = " << ref << endl; //结果错误 因为a是局部变量 已经释放
  • 全局变量
int & test02(){
    static int a = 10;
    return a;
}
int &ref = test02();
cont << "ref = " << ref << endl;
cont << "ref = " << ref << endl;