返回 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;
}
上面的函数在返回 this 指针时调用复制构造函数。
有人可以帮我理解其中的区别吗?
最佳答案
您的return *this
并不“返回此指针”。 this
是一个指针,但 *this
不是指针,它是一个 Count
类型的对象。因此,return *this
按值返回 *this
的当前值,即它返回 Count
对象的拷贝。
return temp
版本执行相同的操作,但由于某些无法解释的原因,它首先将 *this
的当前状态存储在局部变量 temp
然后返回 temp
。我不知道这样做有什么意义。
两种变体都做同样的事情。在您的情况下,两者都按值返回。两个版本都调用复制构造函数(至少在概念上,可以优化该调用)。
关于c++ - 使用此指针返回与按值返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30600706/