C++:如何知道基类子对象的大小? [英] C++ : How can I know the size of Base class SubObject?

查看:33
本文介绍了C++:如何知道基类子对象的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.

这里我在讨论空基优化,并且 MSalters 发表了这个有趣的评论:

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

没有一个班级可以有sizeof(Class)==0,是否为空.但是我们正在专门讨论空基类子对象的大小.它不需要自己的 vtable,也不需要一个虚表指针.假设常见的vtable 指针在偏移处的布局0;这将导致零大小基类子对象共享其带有派生类的 vtable 指针.没问题:那些应该是相同的无论如何,这就是重点虚函数.

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.

我的具体问题是:当我们使用 Empty Class 作为基类时,编译器可能会优化,也可能不会.我们将如何确定它的实际作用?

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?

.

推荐答案

好的答案.

顺便说一句,MS VC++ 和 G++ 编译器可以转储类布局供您学习.

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

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

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

这使用了我在 1990 年编写的类和 vtable 布局转储代码来测试正确的布局对象、vtables、vbtables 等.

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

为了更好地理解 C++ 编译器如何在内存中布置对象,您可能会喜欢 http:///www.openrce.org/articles/files/jangrayhood.pdf 和 Stan Lippman 的书 Inside the C++ Object Model.

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.

快乐黑客!

这篇关于C++:如何知道基类子对象的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆