简体   繁体   中英

return by value function optimization

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.

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.

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??

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM