Kac*_*acy 3 c++ operator-overloading compiler-warnings postfix-operator
有没有办法修改此代码,以便在编译时不会收到警告?此外,这个代码可能不会导致段错误,因为它将访问的内存检索在运算符函数调用结束时取消分配的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 ? */
}
Run Code Online (Sandbox Code Playgroud)
您需要返回一个值(不是引用):
A operator++(int) { /*...*/ }
Run Code Online (Sandbox Code Playgroud)
这将解决编译器警告,你不会得到一个悬空引用.