Possible Duplicate:
Returning a reference can work?
Why 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 and why it is declared static ? please enlighten properly..
I can’t tell you why code is organized as it is, but having static there makes it survive function exit. If static would not be used, then it would be allocated on stack and rewritten later.