C++ 使用此指针返回与按值返回

C++ 使用此指针返回与按值返回,c++,c++11,C++,C++11,返回this指针和按值返回之间的区别是什么 我将试着用一个例子来解释我的情况 我有以下代码 #include <iostream> using namespace std; class Count { private: int count; public: //Constructor Count():count(0) { cout << "Constructor called" <&

返回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++;
        return *this;
}
上述函数在返回此指针时调用复制构造函数

有人能帮我理解其中的区别吗。

您的返回*这不会返回此指针。这是一个指针,但*这不是指针,它是计数类型的对象。因此return*返回*this by value的当前值,即返回Count对象的副本

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


两种变体的作用相同。在您的案例中,这两种方法都按值返回。这两个版本至少在概念上都调用复制构造函数,调用可以优化。

在这种情况下,两个版本都执行相同的操作—一个返回有问题对象的副本,而另一个手动构造有问题对象的副本并返回它

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

Count& operator++() 
{
        count++;
        return *this;
}
这具有返回引用的优点,因此您可以使用如下代码

++(++C);
并使其按预期的方式运行。对于您的版本,该代码将递增C,但随后递增C的一个副本


规范运算符重载签名列表可用。

按值返回通常更为优化和快速。相关:
++(++C);