CppCon 2019: The basics of Move Semantics

Klaus Iglberger

  • Value semantics example with vector
  • v2 = createVector()
  • vs = std::move(v1);
  • simple defn of rvalue, lvalue: lvalue has a name you give it
  • operator=(vector&&rhs) rvalue reference
  • Xvalue: expiring value
  • do not use the moved from value (the xvalue)

New speicial member functions

  • Move constructor
    • Widget (Widget &&w) = default
  • Move assignment operator
    • Widget &operator=(Widget &&w) = default
  • “Rule of zero” if you can avoid defining default operations, good

Move constructor

Widget(Widget &&w)
: i(w.i)
, s (w.s) // bad!
{}

Widget(Widget &&w) noexcept
: i(std::move(w.i)) // not necessary but consistent
, s(std::move(w.s))
, pi(std::move (w.pi))
{
    w.pi = nullptr;
}

, pi(std::exchange(w.pi, nullptr))


  • Make move operations noexcept (Core Guidelines)

Move assignment operator

  • clean up all visible resources
  • Transfer the content of w into this
  • Leave w in a valid but undefined state
  • w = std::move(w);
  • phase 1: cleanup
  • phase 2: member-wise move
  • phase 3:

Generated

  • The default move operations are generate if no copy operation or destructor is user-define
  • The default copy operations are generated if no move operation is user-defined
  • Note: = default and =delete count as user-defined
  • Rule of five or rule of six: if you define or =delete any default operation define or =delete them all.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.