这个实验需要以下的代码:
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() 成员函数均会返回引用。因此,这里可以根据是否需要对容器中的值进行修改而决定需要哪个方法。甚至这三种情况的选用不当也会有内存泄露的危险。
原文地址:http://blog.csdn.net/gulansheng/article/details/46597807