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
Was not possible in C++ pre 11
- ⟶ std::auto_ptr was the
closest possible attempt (error prone though)
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()
|
Adds a copy of |
String s("Hello");
v.push_back(s); // <--- copy requested (s is an lvalue)
|
|
Moves (and thereby invalidates) |
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 |
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 |
Useless: compiler does that anyway (that is the entire plan) |
Move constructor and assignment operator should be explicitly |
Moving resources should not fail (allocation does, generally) |
Use |
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 ( |
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 |