Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>I was wondering, was this restriction lifted in C++11?</p> </blockquote> <p>How could it be? By returning something by value, you are by definition copying (or moving) it. And while C++ can allow that copy/move to be elided in certain circumstances, it's still copying (or moving) by the specification.</p> <blockquote> <p>I remember it could be useful to allow callers of a function use the returned object, but that they are not able to copy the value and store it somewhere. </p> </blockquote> <p>Yes. You get rid of the copy constructor/assignment, but allow the value to be <em>moved</em>. <code>std::unique_ptr</code> does this.</p> <p>You can return a <code>unique_ptr</code> by value. But in doing so, you are returning an "prvalue": a temporary that is being destroyed. Therefore, if you have a function <code>g</code> as such:</p> <pre><code>std::unique_ptr&lt;SomeType&gt; g() {...} </code></pre> <p>You can do this:</p> <pre><code>std::unique_ptr&lt;SomeType&gt; value = g(); </code></pre> <p>But not <em>this</em>:</p> <pre><code>std::unique_ptr&lt;SomeType&gt; value1 = g(); std::unique_ptr&lt;SomeType&gt; value2 = g(); value1 = value 2; </code></pre> <p>But this <em>is</em> possible:</p> <pre><code>std::unique_ptr&lt;SomeType&gt; value = g(); value = g(); </code></pre> <p>The second line invokes the move assignment operator on <code>value</code>. It will delete the old pointer and <em>move</em> the new pointer into it, leaving the old value empty.</p> <p>In this way, you can ensure that the contents of any <code>unique_ptr</code> is only ever stored in one place. You can't stop them from referencing it in multiple places (via pointers to <code>unique_ptr</code> or whatever), but there will be at most one location in memory where the actual pointer is stored.</p> <p>Removing both the copy and move constructors creates an <em>immobile</em> object. Where it is created is where it's values stay, <em>forever</em>. Movement allows you to have unique ownership, but without being immobile.</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