3

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. 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;
  }
};
Community
  • 1
  • 1
prongs
  • 9,422
  • 21
  • 67
  • 105

3 Answers3

4

The caller now has to deal with deleting the memory.

7stud
  • 46,922
  • 14
  • 101
  • 127
1

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.

Community
  • 1
  • 1
doctorlove
  • 18,872
  • 2
  • 46
  • 62
1

So instead of creating the tmp object on stack, we create it on heap and return reference to that. So we can avoid the extra copy.

There are no extra copy in most cases according to RVO. Value x inside of operator++ directly move up as return value. 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). However, your implementation do copy in this line:

X tmp(*this);

or in this:

X* tmp = new X(*this);
Boris
  • 597
  • 2
  • 10