c++ - Appropriate way to forward rvalue reference -
i have following code:
#include <iostream> #include <string> using std::cout; using std::endl; void bar(const std::string& str) { cout << "const str - " << str << endl; } void bar(std::string&& str) { cout << "str - " << str << endl; } void foo(std::string&& str) { bar(str); } int main() { foo("hello world"); }
in above code void bar(const std::string& str)
overload gets called. if want void bar(std::string&& str)
overload called either have write bar(std::move(str));
or bar(std::forward<std::string>(str));
obviously forward code longer, makes more sense me. question more commonly used , prefered. writing bar(std::forward(str));
best solution imo, not option :)
citing effective modern c++
from purely technical perspective, answer yes: std::forward can all. std::move isn’t necessary. of course, neither function necessary, because write casts everywhere, hope agree that be,well, yucky. std::move’s attractions convenience, reduced likelihood of error, , greater clarity.
using std::move
here
void foo(std::string&& str) { bar(str); }
will return str
rvalue reference (which you're trying achieve) while using std::forward
return either lvalue reference (which you're not interested in) or rvalue reference (thus equivalent in case std::move
). using none keep calling const std::string& str
1 since str
lvalue in function.
bottom-line: same thing using std::move
preferred since
- it avoids explicitly specifying template arguments
- it more idiomatic
- it goes straight point:
std::forward
not intended used way (cfr. universal references) or in context although surely work
i might agree "i'm forwarding rvalue reference other function" might make sense standalone sentence kind of misses point of matter. re-wire brain think "keep 'moving' rvalue reference other function"
also possibly related: https://stackoverflow.com/a/18214825/1938163
Comments
Post a Comment