COMS W4995 C++ Deep Dive for C Programmers

Move Semantics

Lecture outline

  1. defining and calling createIntArray()

    • does not compile because we deleted the copy constructor

    • explain that the copy constructor would have to deep-copy

    • returning a large object by value is a very nice and clean pradigm (think Java), but old C++ avoided it due to the cost of copying

  2. move constructor

    • motivation: make returning local objects efficient

    • if you are copying from an object that will be destroyed, just steal the internals instead of copying from it

    • code: copy the interal pointer to the new object, and then sever the connection from the old object

    • enabling copy elision eliminates the move constructor calls

  3. rvalue reference

    • ravlue examples: 5, MyString{"abc"}

    • rvalue-test.cpp: regular ref vs. const ref vs. rvalue ref

    • why does move constructor need rvalue reference?

      • regular reference cannot be bound to rvalue
      • const reference can be, but you cannot then change the object
  4. move assignment

    • code: self-assign check, delete mine, copy rhs, sever rhs, return *this
    • casting to rvalue reference
    • std::move()
  5. Essential 6, Rule of Five, and Rule of Zero