返回参考资料在这里是如何工作的

how returning reference work here

本文关键字:工作 何工作 参考资料 在这里 返回      更新时间:2023-10-16

可能重复:
返回推荐信是否可行?

为什么这个代码有效(matrix是一个类):

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;
}

buf在这里做什么?它如何避免我们有垃圾值?为什么它被声明为static请适当开导。。

我不能告诉你为什么代码是按原样组织的,但在那里有静态可以使它在函数退出时幸存下来。若不使用static,那个么它将在堆栈上进行分配,然后重写。