简体   繁体   English

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

[英]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? 此外,这个代码可能不会导致段错误,因为它将访问的内存检索在运算符函数调用结束时取消分配的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 ? */

}

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 ). 另外还要注意,返回副本可以easilly编译器通过省略掉NRVO (即代码它相当NRVO友好 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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