Prefix/Postfix increment operators

Cam picture Cam · Jul 5, 2010 · Viewed 23.3k times · Source

I'm wanting to make sure I understand pass-by-value vs pass-by-reference properly. In particular, I'm looking at the prefix/postfix versions of the increment ++ operator for an object.

Let's suppose we have the following class X:

class X{
private:
    int i;
public:
 X(){i=0;}
 X& operator ++ (){ ++i; return *this; } //prefix increment

 X operator ++ (int unused){ //postfix increment
  X ret(*this);
  i++;
  return ret;
 }

 operator int(){ return i; } //int cast
};

First of all, have I implemented the prefix/postfix increment operators properly?

Second, how memory-efficient is the postfix operator, compared to the prefix operator? Specifically how many X object copies are created when each version of the operator is used?

An explanation of exactly what happens with return-by-reference vs return-by-value might help me understand.


Edit: For example, with the following code...

X a;
X b=a++;

...are a and b now aliases?

Answer

fredoverflow picture fredoverflow · Jul 5, 2010

It is more idiomatic to call the prefix increment of the object itself in the postfix increment:

X operator++(int)
{
    X copy(*this);
    ++*this;         // call the prefix increment
    return copy;
}

The logic of incrementing an X object is thus solely contained inside the prefix version.