I used to think returning a reference is bad as our returned reference will refer to some garbage value. But this code works (matrix is a class):
const int max_matrix_temp = 7;
matrix&get_matrix_temp()
{
static int nbuf = 0;
static matrix buf[max_matrix_temp];
if(nbuf == max_matrix_temp)
nbuf = 0;
return buf[nbuf++];
}
matrix& operator+(const matrix&arg1, const matrix&arg2)
{
matrix& res = get_matrix_temp();
//...
return res;
}
What is buf doing here and how does it save us from having garbage values?
I see no
bufdeclared anywhere, which means it doesn’t go out of scope with function return, so it’s okay. (it actually looks like it’s meant to bematrixbufwhich is also fine, because it’sstatic).EDIT: Thanks to R. Martinho Fernandes for the guess. Of course it is
matrix buf, so it makesbufstatic array in which temporary is allocated to make sure it doesn’t get freed when the function returns and therefore the return value is still valid.