最好使用 union 而不是 struct 的场景

发布于 2024-12-26 16:38:42 字数 61 浏览 1 评论 0原文

有人可以给我一些场景,在某些问题中使用 union 而不是 struct 是明智的吗?

谢谢

Can some give me some scenario where it is wise to use union instead of struct in some problem?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

晌融 2025-01-02 16:38:42

每当遇到数据瓶颈,并且有两条互斥但在同一数据结构中可用的数据时,明智的做法是使用联合。

假设我有两条具有相同数据的消息,除了两条数据之间互斥且大小接近(一个 32 位 int 和一个 4 字节数组)。我可以将两者结合起来,并且消息可以共享数据结构,而不会增加它们不会使用的大小。

注意问题:

未来数据可能不会相互排斥。
互斥数据的初始化。
为两条消息重用相同的数据实例(您需要确保切换出互斥的数据,或者接收者处理垃圾数据)。

使用联合来引用具有不同类型定义的相同数据是未定义的行为。所以:

  • 不要使用联合来欺骗类型系统。
  • 不要使用联合来存储指针和访问引用。
  • 不要使用联合来创建更便宜的类型转换。

另外,不要将联合数据与可以从代码中的另一点删除的指针数据一起使用。您的联合中可能有一个已删除的指针,并且意外地使用其他定义引用了数据。

最重要的是,如果您不理解这个答案。 不要使用联合。

It is wise to use a union whenever you have a data bottleneck, and you have two pieces of data that are mutually exclusive, but available in the same data structure.

Let's say I have two messages that have identical data, except for two pieces of data are mutually exclusive between them, and are close in size (an 32 bit int, and a 4 byte array). I can make a union of the two, and the messages can share data structure without having an increase in size that they won't use.

Be aware of problems:

The data may not be mutually exclusive in the future.
Initialization of the mutually exclusive data.
Reusing the same instance of the data for both messages (you'll need to be sure you switch out the mutually exclusive data, or the receiver deals with junk data).

Having a union to refer to the same data with different type definitions is undefined behavior. So:

  • Do not use a union to cheat the type system.
  • Do not use a union to store a pointer and access an reference.
  • Do not use a union to create cheaper type casting.

Also, Do not use a union with data that is a pointer which can be deleted from another point in the code. You likely have a deleted pointer in your union and accidentally refer to the data using the other definition.

And most importantly, if you do not understand this answer. Do not use a union.

此刻的回忆 2025-01-02 16:38:42

联合可以是获取数据结构的实际二进制表示的一种方法。

#include <iostream>
#include <iomanip>

union MyUnion {
    int integer;
    unsigned char bytes[sizeof(int)];
};

int main() {
    MyUnion foo;
    foo.integer = 42;
    std::cout << "My computer represents " << foo.integer << " as:";
    for (int i = 0; i < sizeof(foo.bytes); ++i) {
      std::cout << ' ' << std::hex << std::setw(2) << std::setfill('0')
                << static_cast<unsigned int>(foo.bytes[i]);
    }
    std::cout << std::endl;
    return 0;
}

在 C++ 中还有其他方法可以实现此目的,但使用联合使意图变得相当透明。

请注意,结果可能会因平台(小端字节序与大端字节序)而异,也可能因编译器(它如何打包和填充数组和数据类型)而异。大多数时候,您不需要做这样的事情。

有时您必须处理具有多种不同解释的旧二进制格式。 (“如果第一个字节是 3,则下一个值是最多 16 个字节的以零结尾的 ASCII 字符串,否则,下一个 DWORD 对齐的 int 是资源块中的偏移量...”)。如果您了解所涉及的所有字节序和打包问题,则联合可以相对容易地分离这样的结构。

Unions can be a way to get at the actual binary representation of a data structure.

#include <iostream>
#include <iomanip>

union MyUnion {
    int integer;
    unsigned char bytes[sizeof(int)];
};

int main() {
    MyUnion foo;
    foo.integer = 42;
    std::cout << "My computer represents " << foo.integer << " as:";
    for (int i = 0; i < sizeof(foo.bytes); ++i) {
      std::cout << ' ' << std::hex << std::setw(2) << std::setfill('0')
                << static_cast<unsigned int>(foo.bytes[i]);
    }
    std::cout << std::endl;
    return 0;
}

There are other ways to accomplish this in C++, but using a union makes the intent rather transparent.

Note that the results may vary by platform (little-endian vs. big-endian) and possibly by compiler (how it packs and pads arrays and data types). Most of the time, you shouldn't need to do stuff like this.

Sometimes you have to deal with a legacy binary format with several different interpretations. ("If the first byte is a 3, then the next value is a zero-terminated ASCII string of at most 16 bytes, otherwise, the next DWORD-aligned int is an offset in the resource block ..."). If you understand all the endianness and packing issues involved, a union makes it relatively easy to tease apart such a struct.

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