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?
i
in the postfix operator. In fact, I'd do as FredOverflow suggests and call the prefix version. IMO that's indeed more idiomatic than re-implementing increment (even though the implementation is trivial here). And get rid of that implicit conversion operator. It is going to hurt you otherwise. (The third and last time I wrote an implicit conversion operator was in 2001 and one or two years later I discovered that it caused subtle bugs and removed it - like all the ones before. BTDTGTLS.) – Otes