這個實驗需要以下的代碼:
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進行了賦值;
以上三種獲取函數返回值的方式都可以正確執行。以上分析可以看出,這三種方式存在執行效率的差別。而在C++中,STL容器模板的 front() 成員函數均會返回引用。因此,這裡可以根據是否需要對容器中的值進行修改而決定需要哪個方法。甚至這三種情況的選用不當也會有內存洩露的危險。