如何正确重载后缀增量运算符

How to properly overload postfix increment operator?

本文关键字:运算符 后缀 何正确 重载      更新时间:2023-10-16

有没有办法修改此代码,以便在编译时不会收到警告?此外,这段代码是否可能导致段错误,因为它将要访问以检索 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 ? */
}

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

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

这将解决编译器警告,并且您最终不会得到悬而未决的引用。

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

A operator++(int) {  /* returns a copy */
    A copy( *this );         /* allocate a copy on the stack */
    ++x;
    return copy;
  } 

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

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