返回值与返回引用的问题

此处小论一下返回值与返回引用的问题。
先看程序:

#include <iostream>
using namespace std;

class X
{
        int i;
public:
        X(int ii = 0);
        ~X();
        void modify();
};

X::X(int ii)
{
        i = ii;
        cout<<"constructor   "<< this->i <<endl;
}

X::~X()
{
        cout<<"destructor   "<< this->i <<endl;
}

void X::modify()
{
        i++;
}
#if 0
X& f5()                           //此处返回的是X类的引用,当函数结束,调用析构函数,释放内存。
{
        return X(20);        //其实,仍然是在强调,不能返回局部变量的引用。。函数结束,变量消失,引用无意义。
}
#endif
#if 1
X f5()
{
        return X(20);          //直接返回一个无名的X对象,调用了构造函数。但并未在该函数结束时调用析构函数。
                                     //没有创建临时对象,不释放当前的无名对象。
}
#endif
void main()
{
        X  a(10);
        f5() = a;                //因为C++默认提供=运算符重载,故此处不用自己写重载函数即可实现对象之间的浅拷贝。浅拷贝。
        
}

 

易知:运行结果:
constructor   10
constructor   20
destructor   10
destructor   10
Press any key to continue
以上结果,因为调用的是返回值为对象而非引用的f5函数,该函数在结束时并未调用析构函数,故在最后接受了对象a的赋值。

当调用返回值是x类的引用时(将上述代码中预处理 的 1 和 0 调换),可得结果:
constructor   10
constructor   20
destructor   20
destructor   10
Press any key to continue
由以上分析易知,在使用返回引用的时候,一旦函数结束,则对象不复存在,自动调用析构函数。
还是在强调同一个问题:不能返回局部变量的引用。

posted @ 2013-11-13 19:54  KingDr  阅读(804)  评论(0编辑  收藏  举报