码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 成员函数返回引用,三种获取返回值的效果

时间:2015-06-23 10:17:24      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:c++   标准   stl   

这个实验需要以下的代码:

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() 成员函数均会返回引用。因此,这里可以根据是否需要对容器中的值进行修改而决定需要哪个方法。甚至这三种情况的选用不当也会有内存泄露的危险。

C++ 成员函数返回引用,三种获取返回值的效果

标签:c++   标准   stl   

原文地址:http://blog.csdn.net/gulansheng/article/details/46597807

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!