且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++:我如何知道Base类SubObject的大小?

更新时间:2023-11-13 12:56:34

只有空基本类才能优化编译器?





顺便说一句,MS VC ++和G ++编译器可以转储类布局供您研究。



使用VC ++只需运行 cl.exe / c / d1reportAllClassLayout< source> .cpp



vtable布局转储代码我在1990年写的测试正确的布局对象,vtables,vbtables等。



为了更好地理解C ++编译器如何在内存中布置对象, http://www.openrce.org/articles/files/jangrayhood.pdf 和Stan Lippman的书C ++对象模型里面。



快乐黑客!


.

Here I was discussing Empty Base Optimization, and MSalters made this interesting comment:

No class can ever have sizeof(Class)==0, empty or not. But we're talking specifically over the size of an empty base class subobject. It doesn't need its own vtable, nor a vtable pointer. Assume the common layout of a vtable pointer at offset 0; that would cause the zero-sized base class subobject to share its vtable pointer with the derived class. No problem: those should be identical anyway, that's pretty much the point of virtual functions.

My question specifically is this: compiler may optimize when we use Empty Class as base class, or it may not. How would we determine as to what it actually does?

And in general, how can we know the size of base class subobject? Is the size of Base subobject same irrespective of whether we use it as base or not? Do compilers optimize only with Empty Base Classes?

.

Good answers.

By the way, MS VC++ and G++ compilers can dump class layouts for you to study.

With VC++ just run cl.exe /c /d1reportAllClassLayout <source>.cpp

This uses class and vtable layout dump code I wrote in 1990 to test proper layout objects, vtables, vbtables, etc.

To better understand how C++ compilers lay out objects in memory, you might enjoy http://www.openrce.org/articles/files/jangrayhood.pdf and Stan Lippman's book Inside the C++ Object Model.

Happy hacking!