Is it correct to return a value as a reference to rvalue if I want to avoid unnecessary copying?
Not. Returning rvalue links from something that is not an helper of type std::move or std::forward is incorrect. Rvalue links are still links. Returning a reference to a temporary or local variable has always been wrong, and still not. These are the same old C ++ rules.
Is std::forward used correctly? Should I use std::move (both will work in this example) or something else?
The answer to the previous question of the kind makes this question controversial.
The output of the compiled program is indicated in the comments. Is there a way to avoid dangling links when I declare Value&& vv... (or even deny it syntactically)?
This is not part of Value&& vv = c[2]; which creates a freeze link. This is operator[] : see the answer to the first question.
In this case, Rvalue links do not change much. Just do what you always did:
Value operator[](int i) { return Value(data_[i]); }
Any compiler that is worth using will optimize it to directly initialize the return value without any copy or move or anything else. With dumb / useless / weird / experimental compilers, it will move in the worst case (but why would anyone use such a thing for serious things?).
So, the string Value v = c[2]; will be initialized directly v . String Value&& vv = c[2]; initializes the temporary and binds it to the rvalue reference variable. They have the same property as const& , and they extend the lifetime of a temporary link to the lifetime of a link, so it won’t hang out.
In general, the same old C ++ always works and still produces results that are correct and efficient. Do not forget about it.
source share