In his The C++ Programming Language Stroustrup gives the following example for inc/dec overloading:
class Ptr_to_T { T* p; T* array ; int size; public: Ptr_to_T(T* p, T* v, int s); // bind to array v of size s, initial value p Ptr_to_T(T* p); // bind to single object, initial value p Ptr_to_T& operator++(); // prefix Ptr_to_T operator++(int); // postfix Ptr_to_T& operator--(); // prefix Ptr_to_T operator--(int); // postfix T&operator*() ; // prefix }
Why prefix operators return by reference while postfix operators return by value?
Thanks.
To understand better, you have to imagine (or look at) how are these operators implemented. Typically, the prefix operator++ will be written more or less like this:
Since
thishas been modified ‘in-place’, we can return a reference to the instance in order to avoid a useless copy.Now, here’s the code for the postfix operator++:
As the postfix operator returns a temporary, it has to return it by value (otherwise, you’ll get a dangling reference).
The C++ Faq Lite also has a paragraph on the subject.