按值返回函数优化
示例功能 1
int func1 (int arg)
{
return arg + 10;
}
示例功能 2
int func1 (int arg)
{
int retval = arg + 10;
return retval;
}
func_xyz (int x);
int main ()
{
int a = 10;
int p = func1 (a);
func_xyz(p);
}
这些函数(示例 1 和示例 2)的运行时行为有什么区别吗?
我的代码中有一个使用示例 1 样式函数定义的函数定义。当我调用此函数一百万次(对于较少的迭代而言不可重现)并尝试将此值传递给 func_xyz 时,我得到了段错误。但是,当我使用示例 2 样式定义时,segfault
消失了。但我无法理解这种行为的原因。
Sample Function 1
int func1 (int arg)
{
return arg + 10;
}
Sample Function 2
int func1 (int arg)
{
int retval = arg + 10;
return retval;
}
func_xyz (int x);
int main ()
{
int a = 10;
int p = func1 (a);
func_xyz(p);
}
Is there any difference between runtime behaviour of these functions (sample 1 and sample 2)?
I have a function definition in my code that uses sample 1 style function definition. When i invoke this function, a million times (not reproducable for lesser iterations) and try to pass this value to func_xyz
, i get a segfault
. However, when i use sample 2 style definition, segfault
goes away. But i am unable to understand the reason for this behavior.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在函数2中的理论中,将启动一个局部变量(这将占用更多空间),然后将进行计算并将值复制到变量的位置。
之后副本将被复制到返回值。所以这是一个额外的复制操作。
在REALITY中,编译器在编译时进行优化,并删除不需要的变量(如果它们的值没有实际使用)。 (重构)
in THEORY in function2 a local variable will be initiated (which will take just a bit more space), then the calculation will be calculated and value will be copied to the variable's location.
After that the copy will be copied to the return value. So that's an extra copy operation.
in REALITY compilers do that optimization in compile time, and remove unneeded variables if their value isn't actually used. (refactoring)
以下是有关编译器中的返回值优化的一些详细信息。
尝试使用具有重要复制构造函数的类来查看实际发生的情况。
Here are some details about the return value optimization in compilers.
Try with a class that has a non-trivial copy constructor to see what is actually happening.
绝对没有区别。任何编译器都可以看到代码只是
int main()
{
func_xyz(20);
?
被调用的函数做了什么
There is absolutely no difference. Any compiler can see that the code is just
int main()
{
func_xyz(20);
}
What does the called function do??