您好,登錄后才能下訂單哦!
右值引用是C++11標(biāo)準(zhǔn)引入的一個(gè)技術(shù)。
與左值引用類似,右值引用的是右值,包括常量、臨時(shí)值等不可作為左值的值,使用&&表示右值引用,如:type &&t = value1+value2;,在標(biāo)準(zhǔn)庫(kù)的頭文件<uility>有std::move()函數(shù)返回對(duì)應(yīng)的右值類型。如果是const 左值引用類型,則同樣可以接收右值。
右值的應(yīng)用不少,下面以一個(gè)簡(jiǎn)單的字符串存儲(chǔ)類介紹其中的移動(dòng)構(gòu)造函數(shù)、移動(dòng)賦值函數(shù):
// a.h #ifndef A_H #define A_H #include <iostream> #include <cstring> using std::cout; using std::endl; class A { public: A(); // 默認(rèn)構(gòu)造函數(shù) A(const char* str); // 構(gòu)造函數(shù) A(A &&a); // 移動(dòng)構(gòu)造函數(shù) A &&operator =(A &&a); // 移動(dòng)賦值函數(shù) ~A(); // 析構(gòu)函數(shù) void print(); // 輸出mStr private: int mLength; char *mStr; }; #endif
// a.cpp #include "a.h" A::A() { mLength = 0; mStr = nullptr; } A::A(const char *str) { if (str != nullptr) { // 分配資源 mLength = strlen(str); mStr = new char[mLength+1]; strcpy(mStr,str); } else { A(); } } A::A(A &&a) { // 獲取a的資源 cout << "A(&&)" << endl; mLength = a.mLength; mStr = a.mStr; // 將a的mStr設(shè)為nullptr,防止a銷毀時(shí)釋放內(nèi)存a.mStr a.mStr = nullptr; a.mLength = 0; } A &&A::operator =(A &&a) { cout << "operator =(A&&)" << endl; if (mStr != nullptr) { delete []mStr; mStr = nullptr; } // 獲取右值a的資源 mStr = a.mStr; mLength = 0; // 防止右值a銷毀時(shí)釋放mStr的資源 a.mStr = nullptr; a.mLength = 0; // 使用std::move()返回右值引用類型 return std::move(*this); } A::~A() { if (mStr != nullptr) { delete []mStr; } } void A::print() { cout << mStr << endl; }
// main.cpp #include <iostream> #include "A.h" using std::cout; using std::ends; int main() { A str1("asd");// 拷貝構(gòu)造函數(shù) str1.print(); str1 = "123"; // 移動(dòng)賦值函數(shù) str1.print(); A str2(A("zmh")); //移動(dòng)構(gòu)造函數(shù) str2.print(); return 0; }
輸出:
asd
operator =(A&&)
123
zmh
使用右值引用時(shí),要防止右值銷毀而使獲取的資源無效。
以上是對(duì)右值引用的簡(jiǎn)單介紹,歡迎大家一起交流討論。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。