Reputation: 29
This function is part of a larger project for my c++ class. When I try to run it on visual c++ 2017 I get the following warning:
warning C4172: returning address of local variable or temporary: 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;
}
Is there a way to remove this warning and still return the value before the incrementation? Thanks.
Upvotes: 1
Views: 470
Reputation: 172924
The warning is correct. You're trying to return a reference to local object, which will be destroyed when get out of the function, with the dangled reference left.
return the value before the incrementation?
I suppose you should change it to return-by-value; the idea of post-increment operator is to return a copy before performing increment. i.e.
Item Item::operator++(int n) {
Upvotes: 2