C++ 成員函數返回引用,三種獲取返回值的效果

這個實驗需要以下的代碼:

class Test
{
public:
    Test(){cout << "Test" << endl;}
    ~Test(){cout << "~Test" << endl;}
    Test(const Test &right)
    {
        cout << "Test(const)" << endl;
        this->a = right.a;
    }
    Test & operator =(const Test & right)
    {
        cout << "operator=" << endl;
        if(&right == this){
            return *this;
        }
        this->a = right.a;
        return *this;
    }

    Test & geta(){return *this;}
    int getdata(){return a;}
private:
    int a;
};

int main()
{
    Test a;
    cout << "#1#" << endl;
    Test s = a.geta();
    cout << "#2#" << endl;
    Test &p = a.geta();
    cout << "#3#" << endl;
    Test q;
    q = a.geta();
    return 0;
}

上述代碼的運行結果爲:

Test
#1#
Test(const)
#2#
#3#
Test
operator=
~Test
~Test
~Test

分析:

#1# Test s = a.geta() :此條語句生成了一個新的s對象。調用複製構造函數對其進行了初始化;

#2# Test &p = a.geta() :此條語句是以引用名p來指向geta()函數返回的對象,這裏沒有多餘的操作;

#3# Test q; q = a.geta() :這兩條語句,首先調用參數爲空的構造函數,生成對象q。接下來通過調用operator=函數對q進行了賦值;

       1、以上三種獲取函數返回值的方式都可以正確執行。可以看出,這三種方式存在執行效率的差別。而在C++中,STL容器模板的 front() 成員函數均會返回引用。

       2、根據是否需要對容器中的值進行修改而決定需要哪個方法。

       3、這三種情況的選用不當可能有內存泄露的危險。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章