C++ RTTI 继承导致类大小增加
在 C++ 中,问题很简单。
我有两个类,一个包含另一个作为其实现的一部分。
struct A
{
void do_something()
{
};
};
struct B
{
A obj_A;
void hello_world()
{
};
};
现在的问题是,当我执行 sizeof(B) 和类型 B 的对象时,如果 A 是 B 的一部分,则结构 B 会大一个字节。A 100% 仅包含非虚拟成员(不需要虚拟表)并且不需要 typeid 检查。 有没有什么方法(比如编译器指令)可以从 B 中完全删除不需要的字节,但仍然通过 B 访问 A 的成员函数?
我只能假设额外的字节是编译器将 char* 添加到 A 的名称“A”,但任何其他想法都可能有所帮助。
In C++ the problem is simple.
I have 2 classes one contains the other as part of its implementation.
struct A
{
void do_something()
{
};
};
struct B
{
A obj_A;
void hello_world()
{
};
};
Now the problem is that structure B is one byte larger if A is part of B when I do a sizeof(B) and object of type B. A is 100% only going to include only non-virtual members (no virtual table required) and there is no need for a typeid check. Is there any way (like a compiler directive) to completely remove the unneeded byte from B but still access A's member function through B?
I can only assume the extra byte is a compiler added char* to A's name "A" but any other ideas can be helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
sizeof(A) 不能为 0,因为对象的每个部分都应该是“可寻址的”(也就是说,当我们使用运算符 & 时应该有不同的地址)
sizeof(A) cannot be 0 because, each part of an object should be "adressable" (that is should have a different adress when we use operator &)
不幸的是,你没有提到编译器。
无论如何,在您发布的代码中,A 类是“空基类优化”的候选者。 这是 C++ 标准的一部分,该标准规定可以优化没有成员变量的基类以不占用任何字节。
B 必须按照 C++ 标准占用空间,因为它至少包含一个成员(即 obj_A)。
您可以通过调用 do_something() 直接从 B 中访问 A 的成员函数。 不需要魔法。
You don't mention compilers, unfortunately.
Anyway, in the code you post, the class A is a candidate for the "Empty Base Class Optimization". Which is a part of the C++ standard that says that a base class with no member variables can be optimized away to take up no bytes.
B must by the C++ standard take up space, as it contains at least one member (namely obj_A).
You can access A's member function directly from within B, by calling do_something(). No magic is needed.