C++ RTTI 继承导致类大小增加

发布于 2024-07-19 19:48:23 字数 423 浏览 3 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

明媚殇 2024-07-26 19:48:23

sizeof(A) 不能为 0,因为对象的每个部分都应该是“可寻址的”(也就是说,当我们使用运算符 & 时应该有不同的地址)

struct A
{
};

struct B
{
    A m_a1;
    A m_a2;
};

void test()
{
    B b;
    A* pa1 = &b.m_a1;
    A* pa2 = &b.m_a2;

    // "pa1" need to be different from "pa2" 
}

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 &)

struct A
{
};

struct B
{
    A m_a1;
    A m_a2;
};

void test()
{
    B b;
    A* pa1 = &b.m_a1;
    A* pa2 = &b.m_a2;

    // "pa1" need to be different from "pa2" 
}
尬尬 2024-07-26 19:48:23

不幸的是,你没有提到编译器。

无论如何,在您发布的代码中,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文