Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should write code that is maintainable, compilers are really good at doing the right thing for performance in most cases. If you feel that things go slowly, then measure the performance and after you have located the bottleneck, try to figure out how to improve it.</p> <p>You are right in that <em>logically</em> the code triggers different copy constructions: from <code>custom_img</code> to the returned temporary and then to the <code>img</code> object in the caller code, but the fact is that both copies will be elided.</p> <p>In the particular case of <em>return by value</em> versus <em>default-construct + pass-by-reference</em>, all calling conventions that I know of implement <em>return by value</em> by having the caller allocate the memory and pass a hidden pointer to the callee, which effectively implements what you would be trying to do. So from a performance point of view, they are basically equivalent.</p> <p>I wrote about this (value semantics in function arguments and return values) in the past in this two blog entries:</p> <ul> <li><a href="http://definedbehavior.blogspot.com/2011/08/value-semantics-nrvo.html" rel="noreferrer">Named Return Value Optimization</a></li> <li><a href="http://definedbehavior.blogspot.com/2011/08/value-semantics-copy-elision.html" rel="noreferrer">Copy Elision</a></li> </ul> <p><strong>EDIT</strong>: I have intentionally avoided the discussion of the cases where NRVO cannot be applied by the compiler, the reason being that any function <code>f</code> that can take a reference to the object for processing: <code>void f( T &amp; out ) { /* code */ }</code> can be trivially convertible to a function where NRVO is trivial for the compiler to implement that returns by value by a simple transformation into: <code>T f() { T out; /* code */ return out; }</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload