当使用工会以及何时使用结构 [英] When to use a union and when to use a structure

查看:162
本文介绍了当使用工会以及何时使用结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道工会和结构之间的差异。
但是,从设计和编码的角度看,也有不同的用途使用,而不是一个structure.One工会的情况下是一个空间optimization.Are使用其中的任何更多的优势。

I know the differences between union and structure. But from a design and coding perspective what are the various uses cases of using a union instead of a structure.One is a space optimization.Are there any more advantages of using them.

推荐答案

有真的只有两个主要用途。首先是建立一个可识别联合。这可能是你被思维的空间优化,但有一点更给它。你需要数据的额外位知道哪个成员工会是活着(它具有有效数据),因为编译器不会为你做这个。你通常会看到code一样,有一个结构内部的工会,是这样的:

There's really only two major uses. The first is to create a discriminated union. That's probably what you were thinking of by "space optimization," but there's a bit more to it. You need an extra bit of data to know which member of the union is "alive" (has valid data in it) since the compiler does not do this for you. You'd usually see code like that having a union inside of a struct, something like:

struct mixed {
  enum { TYPE_INT, TYPE_FLOAT } type;
  union {
    int    int_value;
    float  float_value;
  } data;
};

当分配给任何data.int_value或data.float_value,你会预期到类型成员设置为合适的枚举值也是如此。然后使用混合值的code可以找出是否阅读int_value或float_value。

When assigning to either data.int_value or data.float_value, you'd be expected to set the type member to the appropriate enumeration value as well. Then your code using the mixed value can figure out whether to read the int_value or float_value.

第二显著使用工会是提供一个API,允许用户访问相同的数据多种方式。这是pretty有限的,因为它需要在工会的所有类型在内存中以相同方式敷设。例如,一个int和一个浮动是完全不同的,并访问一个浮点数作为一个整数不会给你任何特别有意义的数据。

The second significant use of unions is to offer an API that allows the user to access the same data multiple ways. This is pretty limited, as it requires all types in the union to be laid in memory in identical ways. For example, an int and a float are entirely different, and accessing a float as an integer does not give you any particularly meaningful data.

有关这个用例的有用示例,请参见网络API将有多少定义一个工会IPv4地址,是这样的:

For a useful example of this use case, see how many networking APIs will define a union for IPv4 addresses, something like:

union ipv4addr {
  unsigned  address;
  char      octets[4];
};

大多数code只是想通过各地的32位整数值,但有些code要读取单个八位字节。这是所有指针类型转换是可行的,但它是一个更容易一些,更自我记录,因此就更安全以这样的方式使用工会。

Most code just wants to pass around the 32-bit integer value, but some code wants to read the individual octets (bytes). This is all doable with pointer casts, but it's a bit easier, more self-documenting, and hence slightly safer to use a union in such a fashion.

虽然一般情况下,如果你不知道你是否需要一个联盟,你几乎肯定不需要的。

In general though, if you're not sure if you need a union, you almost certainly do not need one.

这篇关于当使用工会以及何时使用结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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