深入學習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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM