左值:既能出现在等号左边,又能出现在等号右边的变量(或表达式),可以寻址
右值:智能出现在等号右边的变量或表达式,无法寻址
例如:a = 10, a是左值,10就是右值
C++11中用&&代表右值引用,左值引用只能引用左值,右值引用只能引用右值。
示例代码:
1 class A{ 2 public: 3 int a; 4 A(){} 5 }; 6 7 A getTemp() { 8 return A(); 9 } 10 11 int testRValue(){ 12 A a; 13 A& refA = a; //lValue reference 14 A&& refA2 = getTemp(); //rValue reference 15 return 0; 16 }
在C++14中std::move模板方法的定义;
1 template<typename T> // C++14; still in 2 decltype(auto) move(T&& param) // namespace std 3 { 4 using ReturnType = remove_reference_t<T>&&; 5 return static_cast<ReturnType>(param); 6 } 7 8 摘录来自: “Effective Modern C++。” Apple Books.
1 void RunCode(int &&m) { 2 std::cout << "rvalue ref" << std::endl; 3 } 4 void RunCode(int &m) { 5 std::cout << "lvalue ref" << std::endl; 6 } 7 void RunCode(const int &&m) { 8 std::cout << "const rvalue ref" << std::endl; 9 } 10 void RunCode(const int &m) { 11 std::cout << "const lvalue ref" << std::endl; 12 } 13 14 template<typename T> 15 void perfectForward(T && t) { 16 RunCode(std::forward<T> (t)); 17 } 18 19 template<typename T> 20 void notPerfectForward(T && t) { 21 RunCode(t); 22 } 23 24 int main() 25 { 26 int a = 0; 27 int b = 0; 28 const int c = 0; 29 const int d = 0; 30 31 notPerfectForward(a); // lvalue ref 32 notPerfectForward(std::move(b)); // lvalue ref 33 notPerfectForward(c); // const lvalue ref 34 notPerfectForward(std::move(d)); // const lvalue ref 35 36 std::cout << std::endl; 37 perfectForward(a); // lvalue ref 38 perfectForward(std::move(b)); // rvalue ref 39 perfectForward(c); // const lvalue ref 40 perfectForward(std::move(d)); // const rvalue ref 41 }
原文:https://www.cnblogs.com/Asp1rant/p/12539784.html