Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Edit:</strong> This answer is wrong, even though, strictly speaking, the code works. I'm only leaving it here because the discussion under it is too useful. This other answer is the best answer given at the time I last edited this: <a href="https://stackoverflow.com/questions/8114276/how-passing-a-unique-ptr-as-argument-of-a-constructor-or-a-method/8114339#8114339">How do I pass a unique_ptr argument to a constructor or a function?</a></p> <p>The basic idea of <code>::std::move</code> is that people who are passing you the <code>unique_ptr</code> should be using it to express the knowledge that they know the <code>unique_ptr</code> they're passing in will lose ownership.</p> <p>This means you should be using an rvalue reference to a <code>unique_ptr</code> in your methods, not a <code>unique_ptr</code> itself. This won't work anyway because passing in a plain old <code>unique_ptr</code> would require making a copy, and that's explicitly forbidden in the interface for <code>unique_ptr</code>. Interestingly enough, using a named rvalue reference turns it back into an lvalue again, so you need to use <code>::std::move</code> <strong>inside</strong> your methods as well.</p> <p>This means your two methods should look like this:</p> <pre><code>Base(Base::UPtr &amp;&amp;n) : next(::std::move(n)) {} // Spaces for readability void setNext(Base::UPtr &amp;&amp;n) { next = ::std::move(n); } </code></pre> <p>Then people using the methods would do this:</p> <pre><code>Base::UPtr objptr{ new Base; } Base::UPtr objptr2{ new Base; } Base fred(::std::move(objptr)); // objptr now loses ownership fred.setNext(::std::move(objptr2)); // objptr2 now loses ownership </code></pre> <p>As you see, the <code>::std::move</code> expresses that the pointer is going to lose ownership at the point where it's most relevant and helpful to know. If this happened invisibly, it would be very confusing for people using your class to have <code>objptr</code> suddenly lose ownership for no readily apparent reason.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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