给定以下函数,是否会在堆栈上声明每个局部变量?
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/