Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Check <a href="http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/" rel="noreferrer">this answer for C++11</a>. Basically, if you pass an lvalue the rvalue reference </p> <p>From <a href="http://blogs.msdn.com/b/xiangfan/archive/2012/02/03/c-98-gt-c-11-pass-by-value-or-pass-by-reference.aspx" rel="noreferrer">this article</a>:</p> <pre><code>void f1(String s) { vector&lt;String&gt; v; v.push_back(std::move(s)); } void f2(const String &amp;s) { vector&lt;String&gt; v; v.push_back(s); } </code></pre> <p>"For lvalue argument, ‘f1’ has one extra copy to pass the argument because it is by-value, while ‘f2’ has one extra copy to call push_back. So no difference; for rvalue argument, the compiler has to create a temporary ‘String(L“”)’ and pass the temporary to ‘f1’ or ‘f2’ anyway. Because ‘f2’ can take advantage of move ctor when the argument is a temporary (which is an rvalue), the costs to pass the argument are the same now for ‘f1’ and ‘f2’."</p> <p>Continuing: " This means in C++11 we can get better performance by using pass-by-value approach when:</p> <ol> <li>The parameter type supports move semantics - All standard library components do in C++11</li> <li>The cost of move constructor is much cheaper than the copy constructor (both the time and stack usage).</li> <li>Inside the function, the parameter type will be passed to another function or operation which supports both copy and move.</li> <li>It is common to pass a temporary as the argument - You can organize you code to do this more.</li> </ol> <p>"</p> <p>OTOH, for C++98 it is best to pass by reference - less data gets copied around. Passing const or non const depend of whether you need to change the argument or not.</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