zoukankan      html  css  js  c++  java
  • c++11 左值引用、右值引用

    c++11 左值引用、右值引用

    #define _CRT_SECURE_NO_WARNINGS
    
    #include <iostream>
    #include <string>
    #include <vector>
    #include <map>
    
    // C++中还有一个被广泛认同的说法,那就是可以取地址的、有名字的就是左值,反之,不能取地址的、没有名字的就是右值。
    // 相对于左值,右值表示字面常量、表达式、函数的非引用返回值等。
    
    /*
    左值引用是对一个左值进行引用的类型,右值引用则是对一个右值进行引用的类型。
    
    左值引用和右值引用都是属于引用类型。无论是声明一个左值引用还是右值引用,都必须立即进行初始化。
    而其原因可以理解为是引用类型本身自己并不拥有所绑定对象的内存,只是该对象的一个别名。
    
    左值引用是具名变量值的别名,而右值引用则是不具名(匿名)变量的别名。
    
    */
    int &a = 2;       // 左值引用绑定到右值,编译失败, err
    int b = 2;        // 非常量左值
    // “const 类型 &”为 “万能”的引用类型,它可以接受非常量左值、常量左值、右值对其进行初始化;
    const int &c = b; // 常量左值引用绑定到非常量左值,编译通过, ok
    const int d = 2;  // 常量左值
    const int &e = c; // 常量左值引用绑定到常量左值,编译通过, ok
    const int &b = 2; // 常量左值引用绑定到右值,编程通过, ok
    
    // 右值引用,使用&&表示
    int && r1 = 22;
    int x = 5;
    int y = 8;
    int && r2 = x + y;
    
    template <typename T>
    T && a = ReturnRvalue();
    
    // 通常情况下,右值引用是不能够绑定到任何的左值的
    int c;
    int && d = c; //err
    
    
    void process_value(int & i) //参数为左值引用
    {
        cout << "LValue processed: " << i << endl;
    }
    
    void process_value(int && i) //参数为右值引用
    {
        cout << "RValue processed: " << i << endl;
    }
    
    
    void mytest()
    {
        int a = 0;
        process_value(a); //LValue processed: 0
        process_value(1); //RValue processed: 1
    
        return;
    }
    
    
    int main()
    {
        mytest();
    
        system("pause");
        return 0;
    }
  • 相关阅读:
    小波变换的引入,通俗易懂
    Leetcode 437. Path Sum III
    Leetcode 113. Path Sum II
    Leetcode 112 Path Sum
    Leetcode 520 Detect Capital
    Leetcode 443 String Compression
    Leetcode 38 Count and Say
    python中的生成器(generator)总结
    python的random模块及加权随机算法的python实现
    leetcode 24. Swap Nodes in Pairs(链表)
  • 原文地址:https://www.cnblogs.com/lsgxeva/p/7787544.html
Copyright © 2011-2022 走看看