深入学习c++--左值引用和右值引用

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    int t = 10;                         //t: 左值 
    int t2 = t + 1;                     //t: 右值 
    
    int a = 1;                          
    const int &b = a + 1;               // 左值引用 
//    int &b = a + 1;                     // 错误 
    cout << b  << " " << a << endl;
    
    int c = 1;
    int &&c2 = c + 1;                   // 右值引用 
    cout << c2 << " " << c << endl;
    
    int d = 1;
    int &&dd = std::move(d);            // 直接把 左值或者右值 转换成 右值引用
    cout << dd << " " << endl;          // 注意,在调用完std::move之后,不能再使用d, 只能用dd
    
    string s = "hello";
    vector<string> v ;
    v.push_back(std::move(s));          // 调用移动构造函数,掏空 s, 掏空后,最好不要使用s了 !!
    cout << v.front() << endl;
    cout << "s: " << s << endl; 
    
    
    return 0;
}

参考:https://www.cnblogs.com/cly-blog/p/5980546.html

猜你喜欢

转载自www.cnblogs.com/douzujun/p/10793538.html