Afterword, Further Reading

Uses In The Standard Library

  • Container classes (e.g. std::vector, std::map, …)

    • Contain possibly many objects

    • ⟶ copy is expensive

    • ⟶ returning a container object is a cheap move

  • Utility classes

Other Uses

  • Move constructor and move assignment operator are most obvious uses

  • ⟶ compiler support when returning locals, for example

  • Other uses: move something into a std::vector

  • ⟶ alternative overloads for push_back()

std::vector<>::push_back(const T& elem);

Adds a copy of elem

String s("Hello");
v.push_back(s);                 // <--- copy requested (s is an lvalue)

std::vector<>::push_back(T&& elem);

Moves (and thereby invalidates) elem

String s("Hello");
v.push_back(std::move(s));      // <--- request move, explicitly invalidating s
v.push_back(String("Hello"));   // <--- temporaries are rvalues -> requesting move

All Said ⟶ Guidelines

Understand what you are doing

Obvious but important

No rvalue references to const type

Useless: rvalue references are there to be modified

No rvalue reference as function return type

Useless: compiler does that anyway (that is the entire plan)

Next operation after std::move is destruction or assignment

Don’t trust the programmer that she left the object in a valid state

Moved-from object must be left in a valid state

Respect from you co-workers

Don’t std::move the return of a local variable

Useless: compiler does that anyway (that is the entire plan)

Move constructor and assignment operator should be explicitly noexcept

Moving resources should not fail (allocation does, generally)

Use =default whenever possible

Think twice though if your members’ move semantics are what you want

Make move-assignment safe for self-assignment

Rare but popular source of errors (s = std::move(s) is stupid but legal C++)

Either implement all of copy/move/dtor or nothing (rule of 5/0)

If you implement one, then you probably do resource management and you will want all

Further Reading (Well, Videos 😉)