Dear friends, i'm concerned if i'm making a bad use of references in C++ In the following method GCC complains warning "reference to local variable ‘me’ returned"
MatrizEsparsa& MatrizEsparsa::operator+(MatrizEsparsa& outra){
MatrizEsparsa me(outra.linhas(),outra.colunas());
return me;
}
But, with the following changes the warning disappears:
MatrizEsparsa& MatrizEsparsa::operator+(MatrizEsparsa& outra){
MatrizEsparsa me(outra.linhas(),outra.colunas());
MatrizEsparsa &ref = me;
return ref;
}
Is the former method ( returning the 'ref' variable ) correct\acceptable ?
No. ref
still refers to me
which will be destroyed at the end of the call.
You should return a copy of your result (not prefixed by &
).
MatrizEsparsa MatrizEsparsa::operator+(const MatrizEsparsa& outra) const {
return MatrizEsparsa(outra.linhas(),outra.colunas());
}
I also added two const
specifiers (to the parameter and to the method) since I doubt outra
or the calling instance need to be modified in this case. (I could be wrong, but then your operator+
would have a weird semantic)
By doing what you did, you just made the code more complex. The compiler probably was confused and couldn't warn you about your possible mistake.
Usually, when you have to use clever tricks to do simple things, it means something is wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With