简体   繁体   English

C ++ postfix ++运算符重载

[英]C++ postfix ++ operator overloading

According to this: Operator overloading , 根据这个: 运算符重载

class X {
  X& operator++()
  {
    // do actual increment
    return *this;
  }
  X operator++(int)
  {
    X tmp(*this);
    operator++();
    return tmp;
  }
};

is the way to implement ++ operators. 是实现++运算符的方法。 The second one(the postfix operator) returns by value and not by reference. 第二个(后缀运算符)按值返回,而不是按引用返回。 That's clear because we can't return a reference to a local object. 这很清楚,因为我们无法返回对本地对象的引用。 So instead of creating the tmp object on stack, we create it on heap and return reference to that. 因此,我们不是在堆栈上创建tmp对象,而是在堆上创建它并返回对它的引用。 So we can avoid the extra copy. 所以我们可以避免额外的副本。 So my question is, is there any problem with the following: 所以我的问题是,以下是否有任何问题:

class X {
  X& operator++()
  {
    // do actual increment
    return *this;
  }
  X& operator++(int)
  {
    X* tmp = new X(*this);
    operator++();
    return *tmp;
  }
};

调用者现在必须处理删除内存。

If your aim to to avoid an extra copy, bear in mind there will probably be not an extra copy. 如果您的目的是避免额外的副本,请记住可能没有额外的副本。 RVO will avoid it - the return value will be put straight into the caller's variable X, optimising away the copy. RVO将避免它 - 返回值将直接放入调用者的变量X中,从而优化副本。

So instead of creating the tmp object on stack, we create it on heap and return reference to that. 因此,我们不是在堆栈上创建tmp对象,而是在堆上创建它并返回对它的引用。 So we can avoid the extra copy. 所以我们可以避免额外的副本。

There are no extra copy in most cases according to RVO. 根据RVO,在大多数情况下没有额外的副本。 Value x inside of operator++ directly move up as return value. operator++内部的值x直接向上移动为返回值。 Check this: 检查一下:

#include <iostream>

class X 
{
    public:

        X() {}
        X( const X & x ) {
            std::cout << "copy" << std::endl;
        }

        X& operator++()
        {
            // do actual increment
            return *this;
        }
        X& operator++(int)
        {
            X x;
            operator++();
            return x;
        }
};

int main()
{
    X x;
    x++;

    return 0;
}

No copy (just tested by vc7). 没有副本(仅通过vc7测试)。 However, your implementation do copy in this line: 但是,您的实现会在此行中复制:

X tmp(*this);

or in this: 或者在这个:

X* tmp = new X(*this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM