【整理】查看C++對象記憶體布局

來源:互聯網
上載者:User

     在C++中,一個類執行個體化得到的結果就是一個對象。一個類包含成員變數和成員函數,成員變數分為non-static和static,成員函數分為non-static成員函數、static成員函數以及virtual成員函數。一個對象包含可能存在的vfptr以及它聲明的或基類繼承而來的non-static成員變數,static成員變數、static成員函數、non-static成員函數以及virtual函數均存在於對象之外。

    VC2005中有一個非常重要的編譯選項:對於查看類的對象的記憶體布局,MS在VC2005中(要先進入Microsoft Visual Studio -> Visual Studio Tools -> Visual Studio 2005命令提示)提供了一個非常重要的編譯選項:/d1reportSingleClassLayout

    如果想向查看檔案Polymorphism06.cpp中的類Child的對象在記憶體中的分布情況,先進入cmd命令視窗,改變目錄到Polymorphism06.cpp所在的目錄,然後鍵入如下命令:

        cl Polymorphism06.cpp /d1reportSingleClassLayoutChild

    斷行符號得到如下結果: (注意:除關於記憶體布局的資訊外還有很多其他資訊)   

    有時我們會發現輸出中會出現vtordisp,它到底是是什麼意思呢,請看下面MSDN的解釋:

    The
vtordisp pragma is applicable only to code that uses virtual bases. If a
derived class overrides a virtual function that it inherits from a
virtual base class, and if a constructor or destructor for the derived
class calls that function using a pointer to the virtual base class, the
compiler may introduce additional hidden "vtordisp" fields into classes
with virtual bases.

    The
vtordisp pragma affects the layout of classes that follow it. The /vd0
and /vd1 options specify the same behavior for complete modules.
Specifying off suppresses the hidden vtordisp members. Specifying on,
the default, enables them where they are necessary. Turn off vtordisp
only if there is no possibility that the class's constructors and
destructors call virtual functions on the object pointed to by the this
pointer.

    vtordisp is now deprecated and will be removed in a future release of Visual C++.

    /vd編譯器選項會影響全域編譯模式。使用vtordisp編譯指示可以在基於類方式上開啟或禁止vtordisp域:

        #pragma vtordisp(off)

        class GetReal:virtual public{...}

        #pragma vtordisp(on)

    這是一個過時的東西,以後的VC編譯器也不會在支援了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.