Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>So why not simply write a <code>swap</code> template that does exactly that: <em>swap</em> the object representations*?</p> </blockquote> <p>There's many ways in which an object, once being constructed, can break when you copy the bytes it resides in. In fact, one could come up with a seemingly endless number of cases <strong><em>where this would not do the right thing</em></strong> - even though in practice it might work in 98% of all cases. </p> <p>That's because the underlying problem to all this is that, other than in C, in C++ we <strong><em>must not treat objects as if they are mere raw bytes</em></strong>. That's why we have construction and destruction, after all: to turn raw storage into objects and objects back into raw storage. Once a constructor has run, the memory where the object resides is more than only raw storage. If you treat it as if it weren't, you will break some types. </p> <p>However, essentially, moving objects shouldn't perform that much worse than your idea, because, once you start to recursively inline the calls to <code>std::move()</code>, you usually ultimately arrive at where <strong><em>built-ins are moved</em></strong>. (And if there's more to moving for some types, you'd better not fiddle with the memory of those yourself!) Granted, moving memory en bloc is usually faster than single moves (and it's unlikely that a compiler might find out that it could optimize the individual moves to one all-encompassing <code>std::memcpy()</code>), but that's the price we pay for the abstraction opaque objects offer us. And it's quite small, especially when you compare it to the copying we used to do. </p> <p>You could, however, have an optimized <code>swap()</code> using <code>std::memcpy()</code> for <strong><em>aggregate types</em></strong>. </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