2011-09-14 80 views

回答

3

我認爲這是在談論這樣的事情:

class A; 

class B { 
public: 
    A * m_a; 
    B(A * a) : m_a(a) {} 
}; 

Class A { 
public: 
    int m_num; 
    A(int num=0) : m_num(num) {} 
    void DoSomethingConst(B * someB) const; 
}; 

void SomeOtherFunction() 
{ 
    A myA; 
    B myB(&myA); 

    //do something with myA.m_num (1) 
    myA.DoSomethingConst(&myB); 
    //do something else with myA.m_num (2) 
} 

裏面的SomeOtherFunction,編譯器不能在寄存器中保存的myA.m_num值(1)和期間(2)再次使用它。即使DoSomethingConstconst,因此不應更改值myA.m_num,但值仍然可以更改,因爲在myB內有一個非const指針指向myA,所以myA.m_nummyA.DoSomethingConst期間仍然可以更改。在這種情況下,證明存在對myA的非常量引用是微不足道的,通常情況下不是。

1

這裏「寄存器緩存」意味着讓編譯器將值存儲在寄存器中。

調用const成員函數不應更改任何成員變量的值,因此如果某些成員變量的值存儲在寄存器中,那麼函數返回時這些值仍然有效。

不是一個非常重要的優化,我猜。