std::move
class Node {
public:
Node() {}
Node(const Node& nd) {
cout << "const Node& nd" << endl;
}
Node(Node&& nd) {
cout << "Node&& nd" << endl;
}
};
int main() {
const Node nd;
// unfortunitely, print "const Node& nd"
Node cy_nd(std::move(nd));
return 0;
}
Because the move assignment operator takes an rvalue reference to a non-const std::string.
The rvalue can, however, be passed to the copy assignment operator,
because an lvalue reference-to-const is permitted to bind to a const rvalue.
std::forward
// const lvalue reference
void inner(const int& i) { cout << "int&" << endl; }
// non-const rvalue reference
void inner(int&& i) { cout << "int&&" << endl; }
// universal reference
template<typename T>
void outer(T&& i) {
/*i is lvalue reference
* print "int&"
*/
inner(i);
/* using std::forward
* if : i is rvalue reference
* then : print "int&&"
* else : still print "int&"
*/
inner(std::forward<T>(i));
}
int main() {
int i = 2;
outer(2);
return 0;
}
std::move unconditionally casts its argument to an rvalue,
std::forward does it under certain conditions.
std::forward is a conditional cast :
It casts to an rvalue only if its argument was initialized with an rvalue.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。