Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning references from a C++ methods

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 ?

like image 409
Lucas Avatar asked Nov 30 '22 18:11

Lucas


1 Answers

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.

like image 79
ereOn Avatar answered Dec 10 '22 02:12

ereOn