有没有办法修改这段代码,这样我在编译时就不会收到警告?此外,这段代码是否会导致段错误,因为它要访问以检索 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) { /*...*/ }
这将解决编译器警告,您不会以悬空引用结束。
关于c++ - 如何正确重载后缀增量运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18748757/