简体   繁体   中英

How to properly overload postfix increment operator?

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 ? */

}

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.

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM