2013-05-04 158 views
0

論 「裏面的C++對象模型」 由S.利普曼,你會發現下面的摘錄26頁:爲什麼編譯器會對下面的`datum :: rotate()`使用虛擬調用?

void rotate(
X datum, 
const X *pointer, 
const X &reference) 
{ 
    // cannot determine until run-time 
    // actual instance of rotate() invoked 
    (*pointer).rotate(); 
    reference.rotate(); 
    // always invokes X::rotate() 
    datum.rotate(); 
} 
main() { 
    Z z; // a subtype of X 
    rotate(z, &z, z); 
    return 0; 
} 

這一段:

The two invocations through pointer and reference are resolved dynamically. In this example, they both invoke Z::rotate(). The invocation through datum may or may not be invoked through the virtual mechanism; however, it will always invoke X::rotate().

據我所知,datum.rotate()會始終使用靜態調用進行調用。爲什麼編譯器會在這裏使用虛擬調用?

+0

理論上可能很有意思,但在實際代碼中按值傳遞多態類型的人應該「重新受教育」。 – Jon 2013-05-04 18:50:51

回答

0

編譯器可以選擇使用虛擬呼叫,即使這樣做沒有必要。該標準沒有說編譯器「必須」將其轉換爲靜態調用。只要調用「正確」函數,編譯器就完成了它的工作。

編輯:這樣看來,標準(至少n3337)不說,編譯器究竟是如何設想被稱作 - 它基本上只是說,

注:通話的解釋虛擬函數取決於被調用的對象的類型(動態類型),而對非虛擬成員函數的調用的解釋僅取決於指向該對象的指針或引用的類型(參見 )靜態類型)(5.2.2)。 - 結束註釋

相關問題