According to what I have read, the return value optimisation occurs only when: 1) the type of the local object matches the return type of the function and 2)the object returned is the local object...
so this should be in error:
Widget makeWidget_InCorrectly() {
Widget w {1, 3.4 };
return std::move(w); // violates rule 2- a reference to the local object is being returned, not the local object!!
}
The book says that std::move returns a REFERENCE to the local object, NOT the object itself, and therefore we are going to get a destroyed object (trash). However I tested this and it does not seem to be anything wrong - how can I see if there is any corruption?
std::move doesn't actually do the moving. It's just changes the type to a rvalue-reference which signals to the receiving function that it is safe to move from.
It is best to not use std::move when returning a local variable because it prevents RVO from happening.
So, is the *forward* useful in the template function case above? -- meaning that it is not a local variable but a value that comes from the caller as a parameter..
I assume there is no RVO in this case to worry about...
Speaking of RVO, return std::move(w); prohibits it. It means "use move constructor or fail to compile", whereas return w; means "use RVO, and if you can't, use move constructor, and if you can't, use copy constructor, and if you can't, fail to compile."