对象内存布局 (11)

来源:互联网 发布:奴婢知奴婢知错跪罚 编辑:程序博客网 时间:2024/05/16 14:47

在C++中,一个类实例化得到的结果就是一个对象。一个类包含成员变量和成员函数,其中成员变量又分为nonstatic成员变量和static成员变量;成员函数又可以分为nonstatic成员函数、static成员函数以及virtual成员函数。一个对象包含可能存在的vfptr以及它声明的或基类继承而来的nonstatic成员变量,static成员变量、static成员函数、nonstatic成员函数以及virtual函数均存在于对象之外。

 

VC2005中有一个非常重要的编译选项:

对于查看类的对象的内存布局,微软内部在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编译器也不会在支持了。