结构中的联合与继承

Union vs inheritance in structures

假设我有一些结构,基本上有一个 'general' 字段和一些独特的数据,例如:

struct A
{
    char type;
    int data;
};

struct B
{
    char type;
    int data[2];
};

等等(我有很多)。所以我可以只创建一个具有相同字段的基础结构,并继承其他字段。我虽然可以使用 union 做同样的事情,例如:

union AnyClass
{
    struct A _a;
    struct B _b;
    ...
};

我正在接收一些数据(完全适合 union 中最大的成员),因此我更愿意使用以下语法:

// to read it from buffer (I am receiving data from another PC, which stores data the same way (in the same union) as I do
char buf[sizeof(AnyClass)];
char type = buf[0]; // detect type
AnyClass inst;
memcpy(&inst, buf, sizeof(inst));
switch(type)
{
    ... // handle data according to its type
}

// if I want to create a new object, and send it, I can use
AnyClass myObj;
new (&myObj._b) B();
... // do whatever I want

注意:我知道我必须以某种方式对齐数据,所以两台机器(received/sender)都应该正确解释 buf。

  1. 它能运行 比使用 BaseStructure 和继承其他问题的解决方案更快吗(所以,我必须立即转换它们),或者它会被编译成几乎相同的代码?
  2. 用起来还好吗,还是设计不好?
  3. 如果还有其他解决方案,您能尽快解释一下吗?

上述方法之间的性能差异很小。很有可能你根本不会注意到它。

我会像这样塑造你的 类:

class AnyClass
{
    char type;
    union
    {
        struct
        {
             int data1;
        };
        struct
        {
             int data2[2];
        };
    };

; 

注意使用匿名结构和联合。

为什么你需要字符缓冲区?始终分配类型化结构并更好地定义它而无需 ctor 和 dectors。我不喜欢这一行:

char type = buf[0]; // detect type

这里直接假设物理偏移量。对结构布局的假设越少,结果就越好。