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