使用此指针返回vs按值返回

时间:2015-06-02 15:46:43

标签: c++ c++11

返回this指针和按值返回有什么区别。

我将尝试用一个例子解释我的案例..

我有以下代码

#include <iostream>
using namespace std;

class Count
{
    private:

        int count;      

    public:

        //Constructor
        Count():count(0) { cout << "Constructor called" << endl; }

        Count(Count& C):count(C.count)
        {  
            cout << "Copy constructor called" << endl; 
        }

        //Destructor
        ~Count() { cout << "Destructor called" << endl; }

        Count  operator ++ () {
            count++;
            Count temp;
            temp.count = count;
            return temp;
            //return *this;

        }

        //Display the value.
         void display() { 
            cout << "The value of count is " << count << endl; 
        }

};

int main()
{
Count C;
Count D;
C.display();
D.display();
D=++C;
C.display();
D.display();
return 0;
}

我在类

中有以下功能
Count  operator ++ () {
        count++;
        Count temp;
        temp.count = count;
        return temp;
}

当我使用上面的函数时,我看到返回值时会调用普通的构造函数。

但我改变了以下功能

Count  operator ++ () {
        count++;
        return *this;
}

上面的函数在返回此指针时调用复制构造函数。

有人可以帮我理解差异。

2 个答案:

答案 0 :(得分:3)

您的return *this没有“返回此指针”。 this是一个指针,但*this不是指针,它是Count类型的对象。因此,return *this按值返回*this的当前值,即返回Count对象的副本。

return temp版本执行相同的操作,但由于某些无法解释的原因,它首先将当前状态*this存储在局部变量temp中,然后返回temp。我不知道这样做有什么意义。

两种变体都做同样的事情。在您的情况下,两者都按值返回。两个版本都调用复制构造函数(至少在概念上,调用可以优化)。

答案 1 :(得分:1)

在这种情况下,两者都做同样的事情 - 一个返回相关对象的副本,而另一个手动构造相关对象的副本并返回它。

我应该指出,更为惯用的方法是

Count& operator++() 
{
        count++;
        return *this;
}

这具有返回引用的优点,因此您可以使用

之类的代码
++(++C);

让它按预期行事。使用您的版本,该代码将增加C,但随后增加C的副本。

可以使用规范运算符重载签名列表on this Wikipedia page

相关问题