C++右值引用

    右值引用是C++11標(biāo)準(zhǔn)引入的一個(gè)技術(shù)。

為彝良等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及彝良網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為成都網(wǎng)站建設(shè)、成都網(wǎng)站制作、彝良網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專(zhuān)業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!

    與左值引用類(lèi)似,右值引用的是右值,包括常量、臨時(shí)值等不可作為左值的值,使用&&表示右值引用,如:type &&t = value1+value2;,在標(biāo)準(zhǔn)庫(kù)的頭文件<uility>有std::move()函數(shù)返回對(duì)應(yīng)的右值類(lèi)型。如果是const 左值引用類(lèi)型,則同樣可以接收右值。

    右值的應(yīng)用不少,下面以一個(gè)簡(jiǎn)單的字符串存儲(chǔ)類(lèi)介紹其中的移動(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銷(xiāo)毀時(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銷(xiāo)毀時(shí)釋放mStr的資源
    a.mStr = nullptr;
    a.mLength = 0;
    // 使用std::move()返回右值引用類(lèi)型
    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í),要防止右值銷(xiāo)毀而使獲取的資源無(wú)效。

    以上是對(duì)右值引用的簡(jiǎn)單介紹,歡迎大家一起交流討論。

當(dāng)前標(biāo)題:C++右值引用
瀏覽路徑:http://muchs.cn/article48/picshp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機(jī)網(wǎng)站建設(shè)、微信公眾號(hào)虛擬主機(jī)、標(biāo)簽優(yōu)化、Google、網(wǎng)站維護(hù)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司