Note that there are some explanatory texts on larger screens.

plurals
  1. POOverload on reference, versus sole pass-by-value + std::move?
    text
    copied!<p>It seems the main advice concerning C++0x's rvalues is to add move constructors and move operators to your classes, until compilers default-implement them.</p> <p>But waiting is a losing strategy if you use VC10, because automatic generation probably won't be here until VC10 SP1, or in worst case, VC11. Likely, the wait for this will be measured in years.</p> <p>Here lies my problem. Writing all this duplicate code is not fun. And it's unpleasant to look at. But this is a burden well received, for those classes deemed slow. Not so for the hundreds, if not thousands, of smaller classes.</p> <p>::sighs:: C++0x was supposed to let me write <em>less</em> code, not more!</p> <p>And then I had a thought. Shared by many, I would guess.</p> <p>Why not just pass everything by value? Won't std::move + copy elision make this nearly optimal?</p> <h2>Example 1 - Typical Pre-0x constructor</h2> <pre><code>OurClass::OurClass(const SomeClass&amp; obj) : obj(obj) {} SomeClass o; OurClass(o); // single copy OurClass(std::move(o)); // single copy OurClass(SomeClass()); // single copy </code></pre> <p><strong><em>Cons:</em></strong> A wasted copy for rvalues.</p> <h2>Example 2 - Recommended C++0x?</h2> <pre><code>OurClass::OurClass(const SomeClass&amp; obj) : obj(obj) {} OurClass::OurClass(SomeClass&amp;&amp; obj) : obj(std::move(obj)) {} SomeClass o; OurClass(o); // single copy OurClass(std::move(o)); // zero copies, one move OurClass(SomeClass()); // zero copies, one move </code></pre> <p><strong><em>Pros:</em></strong> Presumably the fastest.<br> <strong><em>Cons:</em></strong> Lots of code!</p> <h2>Example 3 - Pass-by-value + std::move</h2> <pre><code>OurClass::OurClass(SomeClass obj) : obj(std::move(obj)) {} SomeClass o; OurClass(o); // single copy, one move OurClass(std::move(o)); // zero copies, two moves OurClass(SomeClass()); // zero copies, one move </code></pre> <p><strong><em>Pros:</em></strong> No additional code.<br> <strong><em>Cons:</em></strong> A wasted move in cases 1 &amp; 2. Performance will suffer greatly if <code>SomeClass</code> has no move constructor.</p> <hr> <p>What do you think? Is this correct? Is the incurred move a generally acceptable loss when compared to the benefit of code reduction?</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