Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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;
  }
};
like image 829
prongs Avatar asked Dec 05 '25 07:12

prongs


1 Answers

The caller now has to deal with deleting the memory.

like image 100
7stud Avatar answered Dec 07 '25 19:12

7stud