首页 > 编程语言 > 详细

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

时间:2019-04-29 23:49:07      阅读:125      评论:0      收藏:0      [点我收藏+]
#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

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

原文:https://www.cnblogs.com/douzujun/p/10793538.html

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