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
  • 相关阅读:
    ASP.net:Literal控件用法
    css如何自动换行对于div,p等块级元素(转)
    java ftp操作类
    java文件操作类
    geoserver图层显示
    java csv读取
    geoserver 源码编译(转)
    ArcGIS Engine 空间运算
    ArcMap操作技巧
    geoserver开发资料收集
  • 原文地址:https://www.cnblogs.com/dream397/p/15093309.html
Copyright © 2011-2022 走看看