c++ - 条件堆栈变量

标签 c++

给定以下函数,是否会在堆栈上声明每个局部变量?

std::string reallyCoolFunction(unsigned int a)
{
   if( a < 20 ) 
   {
     std::string result1 = "This function is really cool";
     return result1;
   }

   if( a >=20 && a <= 40 )
   {
     std::string result2 = "This function is kind of cool";
     return result2;
   }

   if( a > 40 )
   {
     std::string result3 = "This function is moderately cool";
     return result3;
   }

 std::string result4 = "This function really isn't that cool"; 
 return result4; // remove warning

}

在这种情况下,实际上只需要一个 std::string,是全部 4 个都分配到堆栈上,还是只分配 1 个?

最佳答案

由编译器决定:由于自动变量在下一个变量进入作用域之前就离开了作用域,编译器可以重新使用它们的内存。请记住,根据 C++ 规范,“堆栈”变量实际上是具有自动存储持续时间的变量,因此它们可能根本不在堆栈上。

关于c++ - 条件堆栈变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14461817/

相关文章:

c++ - 比较 v8 字符串(Node.js 插件)

c++ - 如何使用 Boost.Spirit.Qi 增量解析(并作用于)大文件?

c++ - Qt/C++ : Is there a way to automatically register meta types?

c++ - 为什么这些算法运行得比它们应该的要快?

c++ - 点运算符可以将表达式作为右操作数吗?为什么?

c++ - ppu 和 spu 之间结构大小的差异

c++ - 曲面 segmentation 的理论与算法

c++ - 返回值存储在哪里?

c++ - 如何避免在 decltype 表达式中指定变量?

c++ - 在过剩显示函数中使用对象