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