Sunday, May 1, 2011

C++ post and pre-increment operator overloading does not behave like intrinsic type operators

//C++ post and pre-increment operator overloading does not behave like intrinsic types
//Version: 1.00

#include <iostream>
using std::cout;
using std::endl;
using std::ostream;

class IntWrapper
{
  friend ostream & operator<<( ostream&, const IntWrapper& );

  public:
  IntWrapper( int val = 0 ) : i(val) {;}

  IntWrapper operator+( const IntWrapper& rhs) const
  {
    //use RVO
    return IntWrapper( this->i + rhs.i );
  }

  IntWrapper& operator++()
  {
    ++this->i;
    return *this;
  }

  IntWrapper operator++(int)
  {
    IntWrapper tmp(*this);
    this->operator++();
    return tmp;
  }

  private:
  int i;

};

ostream &operator<<( ostream &, const IntWrapper & );

int main()
{
  //interesting results of the post and pre increment operators

  IntWrapper test;
  int i = 0;

  IntWrapper test1 = test + test++;
  int test2 = i + i++;

  //test1 should be the same as test2 but they are not

  cout << test1 << " for intrinsic types test1 should be the same as test2 but is not since they are not intrinsic types " <<
  test2 << endl;

  cout << i << i++ << test << test++ << endl;

  system("pause");
}

ostream &operator<<( ostream &output, const IntWrapper &r )
{
  output << r.i;
  return output;
}

The conclusion to this experiment is that due to the unspecified behavior according to clause [5/4]
of the standard the assumption that overloading post and pre increment operators will behave in the same manner as the intrinsic type operators is incorrect and not waranted by the standard.

No comments:

Post a Comment