Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>From what I've observed, the move constructor takes precedence over the copy constructor. As Yakk says, you cannot elide the move constructor because of the multiple return paths.</p> <p><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2002/n1377.htm#Copy%20vs%20Move" rel="nofollow">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2002/n1377.htm#Copy%20vs%20Move</a></p> <blockquote> <p>rvalues will prefer rvalue references. lvalues will prefer lvalue references. CV qualification conversions are considered secondary relative to r/l-value conversions. rvalues can still bind to a const lvalue reference (const A&amp;), but only if there is not a more attractive rvalue reference in the overload set. lvalues can bind to an rvalue reference, but will prefer an lvalue reference if it exists in the overload set. The rule that a more cv-qualified object can not bind to a less cv-qualified reference stands ... both for lvalue and rvalue references.</p> <p><b>A further language refinement can be made at this point. When returning a non-cv-qualified object with automatic storage from a function, there should be an implicit cast to rvalue:</b></p> <pre><code>string operator+(const string&amp; x, const string&amp; y) { string result; result.reserve(x.size() + y.size()); result = x; result += y; return result; // as if return static_cast&lt;string&amp;&amp;&gt;(result); } </code></pre> <p>The logic resulting from this implicit cast results in an automatic hierarchy of "move semantics" from best to worst:</p> <pre><code>If you can elide the move/copy, do so (by present language rules) Else if there is a move constructor, use it Else if there is a copy constructor, use it Else the program is ill formed </code></pre> </blockquote> <p>So what if you remove the <code>const &amp;</code> in the parameters? It will still call the move constructor, but will call the copy constructor for the parameters. What if you return a const object instead? It will call the copy constructor for the local variable. What if you return a <code>const &amp;</code>? It will also call the copy constructor.</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