此函数是我的c ++类的大型项目的一部分。当我尝试在visual c ++ 2017上运行它时,我收到以下警告:
警告C4172:返回局部变量的地址或临时:temp
Item& Item::operator++(int n) {
//Increments the code to be printed on the next insertion and returns the
//value before incrementation.
Item temp = *this;
code++;
return temp;
}
有没有办法删除此警告并仍然在增量前返回值?感谢。
答案 0 :(得分:2)
警告是正确的。你试图返回一个对本地对象的引用,当离开函数时它将被销毁,并留下悬挂的引用。
在递增之前返回值?
我想你应该把它改成按值返回; post-increment operator的想法是在执行增量之前返回副本。即。
Item Item::operator++(int n) {