3

コンパイル時に警告を受け取らないようにこのコードを変更する方法はありますか? また、メインの 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 ? */

}
4

2 に答える 2