Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trusting the Return Value Optimization

How do you go about using the return value optimization?
Is there any cases where I can trust a modern compiler to use the optimization, or should I always go the safe way and return a pointer of some type/use a reference as parameter?

Is there any known cases where the return value optimization cant be made?, Seems to me that the return value optimization would be fairly easy for a compiler to perform.

like image 847
Viktor Sehr Avatar asked Jan 25 '10 11:01

Viktor Sehr


2 Answers

Whenever compiler optimizations are enabled (and in most compilers, even when optimizations are disabled), RVO will take place. NRVO is slightly less common, but most compilers will perform this optimization as well, at least when optimizations are enabled.

You're right, the optimization is fairly easy for a compiler to perform, which is why compilers almost always do it. The only cases where it "can't be made" are the ones where the optimization doesn't apply: RVO only applies when you return an unnamed temporary. If you want to return a named local variable, NRVO applies instead, and while it is slightly more complex for a compiler to implement, it's doable, and modern compilers have no problem with it.

like image 86
jalf Avatar answered Sep 29 '22 01:09

jalf


See: http://en.wikipedia.org/wiki/Return_value_optimization#Compiler_support

like image 36
kennytm Avatar answered Sep 29 '22 02:09

kennytm