参考
https://www.internalpointers.com/post/c-rvalue-references-and-move-semantics-beginners
精简例子
std::string s1 = "Hello ";
std::string s2 = "world";
std::string&& s_rref = s1 + s2; // the result of s1 + s2 is an rvalue
s_rref += ", my friend"; // I can change the temporary string!
std::cout << s_rref << '\n'; // prints "Hello world, my friend"
修改上面的例子,发现左值不能赋值给右值引用
所谓“右值”,其实就是临时值(或字面值),它们不能取地址,没有对应变量名。
“右值引用”是专门指向这种值的引用,相当于给这种值添加了名称,然后我们可以对其修改。
universal reference & forward
class Monster {
};
Monster createMonster() {
return Monster();
}
void f1(int num) {
std::cout << num << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
//void f2(Monster&& m) {
// std::cout << "monster rvalue reference" << std::endl;
//}
//
//void f2(Monster& m) {
// std::cout << "monster lvalue reference" << std::endl;
//}
void foo(Monster&& m) {
std::cout << "foo rvalue refer" << std::endl;
}
void foo(Monster& m) {
std::cout << "foo lvalue refer " << std::endl;
}
template <typename T>
void f2(T&& m){
std::cout << "universal reference" << std::endl;
// forward as lvalue or as rvalue, depending on T
//foo(std::forward<T>(m));
foo(m);
}
auto inc(int num) -> int {
return num++;
}
int main(int argc, char* argv[]) {
//Monster m = createMonster();
f2(createMonster());
}