使用VS隐藏命令,编译时输出类内存分布:项目-->工程名称(XXX)属性-->配置属性-->C/C++ -->命令行,在命令行中添加:/d1reportAllClassLayout或/d1reportSingleClassLayoutXXX(Class名称)。
/d1reportAllClassLayout:打印所有类内存分布。
/d1reportSingleClassLayoutXXX(Class名称):打印指定类内存分布。
测试代码如下:
class Base
{
public:
Base() : nBase(10) {}
public:
virtual void funBase()
{ printf("-=-=-=- funBase() -=-=-=-=\n"); }
private:
int nBase;
};
class Derive : public Base
{
public:
Derive() : nB(100) {}
public:
virtual void funBase()
{ printf("-=-=-=- funDerive1() -=-=-=-=\n"); }
virtual void funOwn()
{ printf("-=-=-=- funOwn() -=-=-=-=\n"); }
void DeriveCommonFun() {}
private:
int nB;
};
编译输出类Derive如下:
1>class Derive size(12):
1> +---
1> | +--- (base class Base)
1> 0 | | {vfptr}
1> 4 | | nBase
1> | +---
1> 8 | nB
1> +---
1>Derive::$vftable@:
1> | &Derive_meta
1> | 0
1> 0 | &Derive::funBase
1> 1 | &Derive::funOwn
1>Derive::funBase this adjustor: 0
1>Derive::funOwn this adjustor: 0
从上面可以看出,继承类Derive大致内存分布:
虚函数表、基类变量、继承类变量。
另外,根据对类内存分布了解,可以遍历调用相关函数和变量验证,具体可参照:
http://blog.csdn.net/haoel/article/details/3081328/
http://blog.csdn.net/haoel/article/details/3081385