[C++11]右值和右值引用
生活随笔
收集整理的這篇文章主要介紹了
[C++11]右值和右值引用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
代碼如下:
#include <iostream> using namespace std;int main() {//左值int num = 9;//左值引用int &a = num;//右值const int N = 5;//右值引用int && b = 8;//常量左值引用const int &c = num;//常量右值引用const int &&d = 6;//const int &&d = b; error//int && f = b; error//右值引用給常量的左值引用初始化const int &a = b;//常量右值引用給常量的右值引用初始化const int &aa = d;}右值引用的作用以及使用:
代碼如下:
#include <iostream> using namespace std;class Test { public:Test() :m_num(new int(100)){cout << "construct" << endl;cout << "address = " << m_num << endl;}Test(const Test & a) :m_num(new int(*a.m_num)){cout << "copy construct" << endl;}~Test(){cout << "destruct" << endl;delete m_num;}public:int *m_num; };Test getobj() {Test t;return t; }int main() {Test t = getobj();return 0; }測試結(jié)果:
代碼如下:
#include <iostream> using namespace std;class Test { public:Test() :m_num(new int(100)){cout << "construct" << endl;cout << "address = " << m_num << endl;}Test(const Test & a) :m_num(new int(*a.m_num)){cout << "copy construct" << endl;}//有右值引用的構(gòu)造函數(shù)稱為移動構(gòu)造函數(shù)//移動構(gòu)造函數(shù) -> 復(fù)用其他對象中的資源(堆內(nèi)存)//m_num 淺拷貝Test(Test && a) :m_num(a.m_num){a.m_num = nullptr;cout << "move construct" << endl;}~Test(){cout << "destruct" << endl;delete m_num;}public:int *m_num; };Test getobj() {Test t;return t; }int main() {Test t = getobj();//直接賦值return 0; }測試結(jié)果:
因?yàn)間etobj()返回的是臨時變量,所以程序優(yōu)先調(diào)用移動構(gòu)造函數(shù),如果返回的不是臨時對象,就會調(diào)用拷貝構(gòu)造函數(shù)。
通過右值引用賦值:
代碼如下:
int main() {Test && t1 = getobj();cout <<"address = "<< t1.m_num << endl;return 0; }測試結(jié)果:
不管是直接進(jìn)行賦值,還是右值引用賦值,都要求右側(cè)的對象是一個臨時對象,才會調(diào)用移動構(gòu)造函數(shù)。
如果沒有移動構(gòu)造函數(shù),它會調(diào)用拷貝構(gòu)造函數(shù)。
如果沒有移動構(gòu)造函數(shù),使用右值引用初始化要求更高一點(diǎn)。
要求右側(cè)是一個臨時的不能取地址的對象。
代碼如下:
Test getobj() {return Test(); }int main() {Test && t2 = getobj();cout <<"address = "<< t2.m_num << endl;return 0; }測試結(jié)果:
代碼如下:
Test&& getobj()//將亡值 {return Test(); }int main() {Test && t2 = getobj();cout <<"address = "<< t2.m_num << endl;return 0; }測試結(jié)果:
&&的特性:
右值引用被推導(dǎo)或被傳遞之后對應(yīng)的就是一個左值或者右值。
以上圖片來自下面鏈接:
https://subingwen.cn/cpp/rvalue-reference/
總結(jié)
以上是生活随笔為你收集整理的[C++11]右值和右值引用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [C++11]lambda表达式语法
- 下一篇: 官员称苹果 2023 财年印度 iPho