Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you implement this with move operators there is a way:</p> <pre><code>Bar &amp; Bar :: operator = (Bar &amp;&amp; source) { this -&gt; ~ Bar (); new (this) Bar (std :: move (source)); return *this; } </code></pre> <p>You shouldn't really use this trick with copy constructors because they can often throw and then this isn't safe. Move constructors should never <em>ever</em> throw, so this should be OK.</p> <p><code>std::vector</code> and other containers now exploit move operations wherever possible, so resize and sort and so on will be OK.</p> <p>This approach will let you keep const and reference members but you still can't <em>copy</em> the object. To do that, you would have to use non-const and pointer members.</p> <p>And by the way, you should never use memcpy like that for non-POD types.</p> <h3>Edit</h3> <p>A response to the Undefined Behaviour complaint.</p> <p>The problem case seems to be</p> <pre><code>struct X { const int &amp; member; X &amp; operator = (X &amp;&amp;) { ... as above ... } ... }; X x; const int &amp; foo = x.member; X = std :: move (some_other_X); // foo is no longer valid </code></pre> <p>True it is undefined behaviour if you continue to use <code>foo</code>. To me this is the same as</p> <pre><code>X * x = new X (); const int &amp; foo = x.member; delete x; </code></pre> <p>in which it is quite clear that using <code>foo</code> is invalid.</p> <p>Perhaps a naive read of the <code>X::operator=(X&amp;&amp;)</code> would lead you to think that perhaps <code>foo</code> is still valid after a move, a bit like this</p> <pre><code>const int &amp; (X::*ptr) = &amp;X::member; X x; // x.*ptr is x.member X = std :: move (some_other_X); // x.*ptr is STILL x.member </code></pre> <p>The member pointer <code>ptr</code> survives the move of <code>x</code> but <code>foo</code> does not.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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