+ 1
Garbage problem in C++
Hello, I have a need to use operators for user-defined objects. I so far wanted to make this kind of expression to work: Number n = Number(...) + Number(...); But I end up getting garbage results. (A Number object has an array attribute.) (I don't want to use pointers in the expression.) Is it even valid to run similar expressions, to strictly return user-defined objects? Otherwise the garbage might be caused by something else. Problem appears here: https://code.sololearn.com/c3Pnnnr8yp9g/#cpp
3 Antworten
+ 7
After some debugging, I realized that whatever object is passed to your overloaded + operator would get destroyed after the addition took place. Turns out the fix is pretty simple too, just pass RHS by reference, so that it does not get destroyed right after addition is completed.
Number operator+(Number& n2) {
// ....
}
I suggest doing the same to your overloaded comparison operator definition, so that it does not cause issues down the road.
+ 7
I really thought you had a hidden sink somewhere which called delete or invoked the destructor. I was so confused lol.
+ 1
Hatsy Rei Also confused, thought the garbage was caused by the n3 variable in operator+. But now it makes sense that it was caused by the n2 parameter instead.
Thanks a lot!