如何正确重载后缀增量运算符
How to properly overload postfix increment 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 ? */
}
你需要返回一个值(而不是引用):
A operator++(int) { /*...*/ }
这将解决编译器警告,并且您最终不会得到悬而未决的引用。
后缀运算符不按引用返回,而是按值返回:
A operator++(int) { /* returns a copy */
A copy( *this ); /* allocate a copy on the stack */
++x;
return copy;
}
请注意,在代码中,您将返回对具有未定义行为的局部变量的引用。
另请注意,编译器可以通过 NRVO 轻松省略返回副本(该代码对 NRVO 非常友好)。
相关文章:
- 增量运算符与后缀混淆
- 后缀 "&" (地址) 运算符 在 C++ 中
- 使用 C++ 将中缀转换为后缀(包括赋值运算符)
- C++编译器如何扩展前缀和后缀运算符++()?
- 指向重载前缀和后缀运算符中的类对象的指针
- 输入迭代器 - 星号和后缀运算符
- C++如何知道在重载运算符时增量++是前缀或后缀
- 后缀运算符链表泛型节点迭代器
- 如何使用虚拟后缀运算符解决切片问题
- 前缀和后缀运算符 C++
- C++14 中 std::string 的运算符后缀
- 后缀运算符不应该被视为二元运算符吗
- 编译器如何翻译后缀/前缀运算符
- 虚拟参数在后缀运算符重载中的用途?C++
- 涡轮增压C++(非可视)(后缀和前缀运算符)
- while 循环中的后缀运算符
- 如何计算前缀和后缀运算符的组合
- C++ “运算符=”(后缀到中缀)不匹配
- C++ 重载'--'后缀运算符
- 未声明运算符++后缀