在C ++块范围内,重用堆栈存储器是优化的领域吗? [英] In C++ block scope, is re-using stack memory the area of optimization?

查看:59
本文介绍了在C ++块范围内,重用堆栈存储器是优化的领域吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我测试了以下代码:

void f1() {
  int x = 1;
  cout << "f1  : " << &x << endl;
}

void f2() {
  int x = 2;
  cout << "f2  : " << &x << endl;
}

void f3() {
  {
    int x = 3;
    cout << "f3_1: " << &x << endl;
  }
  {
    int x = 4;
    cout << "f3_2: " << &x << endl;
  }
}

int main() {
  f1();
  f2();
  f3();
}

release 版本中,输出为...

in release build, the output is...

f1  : 00FAF780
f2  : 00FAF780 
f3_1: 00FAF780
f3_2: 00FAF780  <-- I expected

但在 debug 构建中,

f1  : 012FF908
f2  : 012FF908
f3_1: 012FF908
f3_2: 012FF8FC  <-- what??

我认为规则是在块结束时移动堆栈指针以再次使用堆栈存储器.
这是优化领域吗?

I thought the rule was to move the stack pointer to use the stack memory again when the block is ended.
Is this principle the area of optimization?

推荐答案

调试版本通常是故意未优化的.可能是每个变量(无论作用域如何)在堆栈上都有其自己的位置,以便在代码崩溃时可以向您显示每个变量的状态.如果他们都共享一个地址,这将是不可能的.

A debug build is usually very unoptimized on purpose. It might be that each variable, regardless of scope, is given its own spot on the stack so that when your code crashes it can show you the state of each one. This wouldn't be possible if they all shared an address.

这篇关于在C ++块范围内,重用堆栈存储器是优化的领域吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆