首页 > 编程语言 > 详细

Effective Modern C++: 右值引用

时间:2020-03-21 16:55:58      阅读:50      评论:0      收藏:0      [点我收藏+]

一:C语言中的右值概念

 

左值:既能出现在等号左边,又能出现在等号右边的变量(或表达式),可以寻址

右值:智能出现在等号右边的变量或表达式,无法寻址

例如:a = 10, a是左值,10就是右值

 

二:右值引用 rValue reference

 

 

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 }

 

三:std::move

  • move函数的参数T&&是一个指向模板类型参数的右值引用【规则2】,通过引用折叠,此参数可以和任何类型的实参匹配,因此move既可以传递一个左值,也可以传递一个右值;

  在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. 

 

四:std::forward

  • std::forward实现了参数在传递过程中保持其值属性的功能,即若是左值,则传递之后仍然是左值,若是右值,则传递之后仍然是右值。
  • std::move 和 std::forward的差别:
  1. std::move执行到右值的无条件转换。就其本身而言,它没有move任何东西。
  2. std::forward只有在它的参数绑定到一个右值上的时候,它才转换它的参数到一个右值。
  3. std::move和std::forward只不过就是执行类型转换的两个函数;std::move没有move任何东西,std::forward没有转发任何东西。在运行期,它们没有做任何事情。它们没有产生需要执行的代码,一byte都没有。
  4. std::forward<T>()不仅可以保持左值或者右值不变,同时还可以保持const、Lreference、Rreference、validate等属性不变;
  • 示例:
 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 }

 



 

Effective Modern C++: 右值引用

原文:https://www.cnblogs.com/Asp1rant/p/12539784.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!