Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Let's say you have two functions on a class, both with the same name and signature. But one of them is declared <code>const</code>:</p> <pre><code>void SomeFunc() const; void SomeFunc(); </code></pre> <p>If a class instance is not <code>const</code>, overload resolution will preferentially select the non-const version. If the instance is <code>const</code>, the user can only call the <code>const</code> version. And the <code>this</code> pointer is a <code>const</code> pointer, so the instance cannot be changed.</p> <p>What "r-value reference for this` does is allow you to add another alternative:</p> <pre><code>void RValueFunc() &amp;&amp;; </code></pre> <p>This allows you to have a function that can <em>only</em> be called if the user calls it through a proper r-value. So if this is in the type <code>Object</code>:</p> <pre><code>Object foo; foo.RValueFunc(); //error: no `RValueFunc` version exists that takes `this` as l-value. Object().RValueFunc(); //calls the non-const, &amp;&amp; version. </code></pre> <p>This way, you can specialize behavior based on whether the object is being accessed via an r-value or not.</p> <p>Note that you are not allowed to overload between the r-value reference versions and the non-reference versions. That is, if you have a member function name, all of its versions either use the l/r-value qualifiers on <code>this</code>, or none of them do. You can't do this:</p> <pre><code>void SomeFunc(); void SomeFunc() &amp;&amp;; </code></pre> <p>You must do this:</p> <pre><code>void SomeFunc() &amp;; void SomeFunc() &amp;&amp;; </code></pre> <p>Note that this declaration changes the type of <code>*this</code>. This means that the <code>&amp;&amp;</code> versions all access members as r-value references. So it becomes possible to easily move from within the object. The example given in the first version of the proposal is (note: the following may not be correct with the final version of C++11; it's straight from the initial "r-value from this" proposal):</p> <pre><code>class X { std::vector&lt;char&gt; data_; public: // ... std::vector&lt;char&gt; const &amp; data() const &amp; { return data_; } std::vector&lt;char&gt; &amp;&amp; data() &amp;&amp; { return data_; } }; X f(); // ... X x; std::vector&lt;char&gt; a = x.data(); // copy std::vector&lt;char&gt; b = f().data(); // move </code></pre>
 

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