zoukankan      html  css  js  c++  java
  • C++11新特性之 rvalue Reference(右值引用)

    #include <iostream>
    
    int getValue ()
    {
        int ii = 10;
        return ii;
    }
    
    int main()
    {
        std::cout << getValue();
        return 0;
    }
     
    root@ubuntu:~/c++# g++ -std=c++11  right.cpp -o auto
    root@ubuntu:~/c++# ./auto
    10 

    右值有更隐晦的,记住如果一个表达式的结果是一个暂时的对象,那么这个表达式就是右值

    这里需要注意的是 getValue() 是一个右值。

    我们只能这样做,必须要有const

    const int& val = getValue(); // OK
    int& val = getValue(); // NOT OK
    #include <iostream>
    
    int getValue ()
    {
        int ii = 10;
        return ii;
    }
    
    int main()
    {
        int & val = getValue();
        return 0;
    }
    root@ubuntu:~/c++# g++ -std=c++11  right.cpp -o auto
    right.cpp: In function ‘int main()’:
    right.cpp:11:25: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘intint & val = getValue();
                             ^
    root@ubuntu:~/c++# 
    #include <iostream>
    
    int getValue ()
    {
        int ii = 10;
        return ii;
    }
    
    int main()
    {
        const int & val = getValue();
        return 0;
    }

    但是C++11中的右值引用允许这样做:

    const int&& val = getValue(); // OK
    int&& val = getValue(); //  OK
    #include <iostream>
    
    int getValue ()
    {
        int ii = 10;
        return ii;
    }
    
    int main()
    {
        const int & val = getValue();
        const int && val2 = getValue();
        int && val3 = getValue();
        return 0;
    }
    void printReference (const int& value)
    {
            cout << value;
    }
    
    void printReference (int&& value)
    {
            cout << value;
    }

    一个printReference()可以接受参数为左值,也可以接受右值。
    而第二个printReference()只能接受右值引用作为参数。

    #include <iostream>
    
    using namespace std;
    
    void printReference (int& value)
    {
            cout << "lvalue: value = " << value << endl;
    }
    
    void printReference (int&& value)
    {
            cout << "rvalue: value = " << value << endl;
    }
    
    int getValue ()
    {
        int temp_ii = 99;
        return temp_ii;
    }
    
    int main()
    { 
        int ii = 11;
        printReference(ii);
        printReference(getValue());  //  printReference(99);
        return 0;
    }
     
    root@ubuntu:~/c++# ./auto
    lvalue: value = 11
    rvalue: value = 99
  • 相关阅读:
    Openstack API 开发 快速入门
    virtualBox虚拟机到vmware虚拟机转换
    使用Blogilo 发布博客到cnblogs
    Openstack Troubleshooting
    hdoj 1051 Wooden Sticks(上升子序列个数问题)
    sdut 2430 pillars (dp)
    hdoj 1058 Humble Numbers(dp)
    uva 10815 Andy's First Dictionary(快排、字符串)
    sdut 2317 Homogeneous squares
    hdoj 1025 Constructing Roads In JGShining's Kingdom(最长上升子序列+二分)
  • 原文地址:https://www.cnblogs.com/dream397/p/15093309.html
Copyright © 2011-2022 走看看