c++ - 使用此指针返回与按值返回

标签 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;
}

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

有人可以帮我理解其中的区别吗?

最佳答案

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

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

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

关于c++ - 使用此指针返回与按值返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30600706/

相关文章:

c++ - 提高融合和常量正确性

c++ - 迭代 vector 对并使用 std::copy 打印结果

c++ - 使用 auto 访问类的私有(private)结构

c++ - 在类似于 Scott Meyer 的单例惯用语的实现中使用新线程安全来实例化单例吗?

c++ - OpenCV绘制带有轴标签和坐标的直方图

c++ - 在 C++ 中计算 sha-256 的一个很好的库

c++ - 小于最小可表示 int 的最小 int 值?

c++ - 如何让代码存在于两个或多个非嵌套命名空间的范围内?

c++ - 重载给我错误 : no match for ‘operator<’

c++ - boost使用c++11有多好?