Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C++ 多型如何在編譯期與執行期分別實現

多型是什麼?簡單說,呼叫端呼叫同一個介面,而這個介面有多種實作,依上下文不同會落到不同的實作上。本文只討論繼承關係下的多型,並拆解 C++ 編譯器在編譯期與執行期各做了什麼。

實驗程式

#include <iostream>
using namespace std;

class Father
{
public:
    int m_fMember;

    void testFunc(){ cout << "Father testFunc " << m_fMember << endl; }
    virtual void testVFunc(){ cout << "Father testVFunc " << m_fMember << endl; }

    Father(){ m_fMember = 1; }
};

class Child : public Father
{
public:
    int m_cMember;
    Child(){ m_cMember = 2; }

    virtual void testVFunc(){ cout << "Child testVFunc " << m_cMember << ":" << m_fMember << endl; }
    void testFunc(){ cout << "Child testFunc " << m_cMember << ":" << m_fMember << endl; }
    void testNFunc(){ cout << "Child testNFunc " << m_cMember << ":" << m_fMember << endl; }
};

int main()
{
    Father* pRealFather  = new Father();
    Child*  pFalseChild  = (Child*)pRealFather;      // 危險的向下轉型
    Father* pFalseFather = new Child();

    pFalseFather->testFunc();
    pFalseFather->testVFunc();

    pFalseChild->testFunc();
    pFalseChild->testVFunc();
    pFalseChild->testNFunc();

    return 0;
}

輸出為:

Father testFunc 1
Child testVFunc 2:1
Child testFunc 0:1
Father testVFunc 1
Child testNFunc 0:1

同樣呼叫 testFunc 與 testVFunc,結果截然不同,這就是多型。順帶說明:第三、五行之所以印出 0,是因為 pFalseChild 其實指向一個 Father 物件,強制轉型後讀取 m_cMember 屬於未定義行為,這個例子只為示範,實務上絕對不要這樣寫。

編譯期:呼叫哪個函式早就定下來了

用 gcc -S 產生組語,看 main 中的呼叫:

call  _ZN6FatherC1Ev            // Father 建構子
call  _ZN5ChildC1Ev             // Child 建構子

call  _ZN6Father8testFuncEv     // 對應 pFalseFather->testFunc()
movq  (%rax), %rax
call  *%rax                     // 對應 pFalseFather->testVFunc()

call  _ZN5Child8testFuncEv      // 對應 pFalseChild->testFunc()
movq  (%rax), %rax
call  *%rax                     // 對應 pFalseChild->testVFunc()

call  _ZN5Child9testNFuncEv     // 對應 pFalseChild->testNFunc()

非虛函式的呼叫,目標符號在編譯完成時就寫死在機器碼裡:_ZN6Father8testFuncEv 與 _ZN5Child8testFuncEv 是兩個不同的程式碼段,編譯器依「指標的靜態型別」決定用哪一個。這就是編譯期多型——靜態決定的部分。

執行期:透過虛表間接跳轉

虛函式的組語多了一段前置動作:先取出物件開頭的虛表指標,再從虛表中取出該函式所在位置的位址,最後 call *%rax 間接跳轉。物件建構時,建構子會把對應類別的虛表位址寫進物件,因此同一句 p->testVFunc() 在不同物件上會跳到不同實作。這就是執行期多型——動態分派的部分。

兩者的實務意義

  • 非虛函式不具多型,即使子類定義了同名函式,透過父類指標呼叫仍走父類版本(常被誤稱為「函式 hides」)。
  • 需要多型就必須 virtual,而虛函式会带来一層間接跳轉與每個物件一個虛表指標的空間成本。
  • 基類有虛函式時,析構函式也應該是虛的,否則透過基類指標刪除子類物件會導致未定義行為。
  • 對效能極敏感的路徑可用 final 或 CRTP 讓編譯器去虛化,換回直接呼叫。
Copyright © Linux教程網 All Rights Reserved