如何正确重载postfix增量运算符?

时间:2013-09-11 18:36:03

标签: c++ operator-overloading compiler-warnings postfix-operator

有没有办法修改此代码,以便在编译时不会收到警告?此外,这段代码无法导致段错误,因为它将访问的内存检索在运算符函数调用结束时释放的main中的x的值?

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 个答案:

答案 0 :(得分:6)

您需要返回一个值(不是引用):

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

这将解决编译器警告,你不会得到悬空引用。

答案 1 :(得分:2)

后缀运算符不按引用返回,按值返回:

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

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

    return copy;

  } 

请注意,在您的代码中,您将返回对局部变量的引用,该变量具有未定义的行为

另请注意,编译器可以通过NRVO(该代码非常 NRVO友好)简单地省略返回副本。