For a school project, I am writing a class to store arbitrary length integers. I have an operator- for it like this:
BigInt BigInt::operator-() const {
BigInt newNum { *this };
newNum.m_positive = !newNum.m_positive;
return newNum;
}
The problem with this code is that the current object gets copied twice (at line 2 and line 4). Is there any way I can avoid this?
Things that don't work:
- Simply returning a reference to newNum: UB
- Allocating memory with new and returning a reference to it: memory leak
- Allocating memory and returning a (smart) pointer: Not the desired behavior for the - operator
- Changing this and have it copied by the return statement: Can't undo the changes to this