FAQ 23.08 What should the prefix and postfix versions of operator return?

FAQ 23.08 What should the prefix and postfix versions of operator++ return?

++i should return a reference to i; i++ should return either void or a copy of the original state of i.

The prefix version, operator++(), should return *this, normally by reference. For example, if the class of the object is Fred, Fred::operator++() should normally return *this as a Fred&. It is also valid, but not as desirable, if it returns void.

The postfix version, Fred::operator++(int), should return either nothing (void) or a copy of the original state of the object, *this. In any event, it should not return a Fred& because that would confuse users. For example, if i++ returned *this by reference, the value returned from i++ would be the same as the value returned from ++i. That would be counterintuitive.

It is often easiest if Fred::operator++(int) is implemented in terms of Fred::operator++():

 #include <iostream> using namespace std; class Fred { public:   Fred& operator++ ()   throw();   Fred operator++ (int) throw(); }; Fred& Fred::operator++ () throw() {   cout << "do the increment here\n";   return *this;                                      <-- 1 } Fred Fred::operator++ (int) throw() {   Fred old = *this;   ++(*this);                                         <-- 2   return old;                                        <-- 3 } int main() {   Fred i;   ++i;                                               <-- 4   i++;                                               <-- 5 } 

(1) The prefix version returns the new value of *this

(2) The postfix version calls the prefix version

(3) The postfix version returns the old value of *this

(4) Call the prefix version

(5) Call the postfix version

Note that users should avoid i++ in their code unless the old state of i is needed. In particular, simple statements such as i++; (where the result of i++ is ignored) should generally be replaced by ++i;. This is because i++ may cause more overhead than ++i for user-defined (classes) types. For example, calling i++ may create an unnecessary copy of i. Of course, if the old value of i is needed, such as in j = i++, the postfix version is beneficial.

The two versions of operator-- are similar: the prefix version should return *this by reference, and the postfix version should return either the old state of *this or void.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net