How to properly overload postfix increment operator?

1.4k views Asked by At

Is there a way to modify this code so that I do not receive a warning when compiling ? Also, couldn't this code potentially result in a segfault since the memory it is going to access to retrieve the value of x in main got deallocated at the end of the operator function call?

class A {

  int x; /* value to be post-incremented */

  public:

  A() {  /* default constructor */
  }

  A( A & toCopy ) {   /* copy constructor */
    x = toCopy.x;
  }

  A & operator++(int) {  /* returns a reference to A */

    A copy( *this );         /* allocate a copy on the stack */
    ++x;

    return copy;            /* PROBLEM: returning copy results in a warning */

  }                         /* memory for copy gets deallocated */

}; /* end of class A */

int main() {

  A object;
  object.x = 5;

  cout << (object++).x << endl;   /* Possible segfault ? */

}
2

There are 2 answers

8
Daniel Frey On BEST ANSWER

You need to return a value (not a reference):

A operator++(int) { /*...*/ }

this will resolve the compiler warning and you won't end up with a dangling reference.

0
Manu343726 On

The postfix operator doesn't return by reference, returns by value:

A operator++(int) {  /* returns a copy */

    A copy( *this );         /* allocate a copy on the stack */
    ++x;

    return copy;

  } 

Note that in your code you are returning a reference to a local variable, which has undefined-behavior.

Also note that the return copy could be easilly elided by the compiler through a NRVO (That code its pretty NRVO-friendly).