C++對象記憶體布局–虛基類表的使用

來源:互聯網
上載者:User

C++對象記憶體布局--虛基類表的使用

一、測試VS編譯器,虛基類表在函數調用時是怎麼使用的

1、測試代碼:

//虛基類表指標的使用.cpp//2010.8.19//使用VC++6.0/VS2005/VS2008編譯器編譯,OllyDbg反組譯碼工具調試查看虛基類表的使用。#include <iostream>using namespace std;////////////////////////////////////////////////////////////////class Base{    public:        Base(int a = 10):a(a)        {        }        virtual void show()        {            cout << "Base::show()" << endl;        }        virtual void testA()        {            cout << "Base::testA()" << endl;        }    private:        int a;};////////////////////////////////////////////////////////////////class BaseA : virtual public Base{    public:        BaseA(int b = 20):b(b)        {        }        virtual void showA()        {            cout << "BaseA::showA()" << endl;        }        void testA()        {            cout << "BaseA::testA()" << endl;        }    private:        int b;};////////////////////////////////////////////////////////////////class BaseB : virtual public Base{    public:        BaseB(int c = 30):c(c)        {        }        virtual void showB()        {            cout << "BaseB::showB()" << endl;        }    private:        int c;};////////////////////////////////////////////////////////////////class Derived : public BaseA, public BaseB{    public:        Derived(int d = 40):d(d)        {        }        virtual void show()        {            cout << "Derived::show()" << endl;        }        virtual void test()        {            cout << "Derived::test()" << endl;        }    private:        int d;};////////////////////////////////////////////////////////////////int main(){    Derived obj;cout << "start" << endl;//為方便反組譯碼調試設定的標記Base *pb = &obj;pb->show();cout << "start" << endl;//為方便反組譯碼調試設定的標記、system("pause");    return 0;}

2、使用OllyDbg反組譯碼調試的相關結果:

 

圖 1 VC++6.0編譯器,OD調試結果

 

圖 2 VS2005/2008編譯器,OD調試結果

3、結果表明,在調用虛基類函數的時候,有使用到虛基類表指標。

二、測試GCC編譯器,虛基類表在函數調用時是怎麼使用的

1、測試代碼跟上邊的一樣。

2、使用OllyDbg反組譯碼調試的相關結果:

 

圖 3 GCC編譯器,OD調試結果

3、結果表明,在調用虛基類函數的時候,沒用到虛基類表指標,直接:ADD EAX, 14,擷取虛基類執行個體地址。可能是測試的代碼比較簡單,編譯器做了最佳化。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.