2012-01-19 51 views
-6

可能重複:
Returning a reference can work?如何返回這裏參考工作

爲什麼此代碼(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請正確指導..

+1

正如在你問的原始問題的答案(http://stackoverflow.com/questions/8924966/returning-reference/8924994#8924994)中指出的那樣,它被聲明爲靜態的,否則一旦函數完成後它將不再存在,意味着對數組中元素的任何引用都是無效的。 –

回答

0

我不能告訴你爲什麼代碼是按原樣組織的,但是有靜態的地方會讓它在函數退出時生存下來。如果不使用靜態,那麼它將被分配到堆棧並在稍後被重寫。