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