当有人会用一个工会吗?它是从唯一的C-天残? [英] When would anyone use a union? Is it a remnant from the C-only days?

查看:113
本文介绍了当有人会用一个工会吗?它是从唯一的C-天残?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经学会了,但没有真正得到工会。每个C或C ++的文字我通过介绍他们(有时在传球),但它们往往会给为什么或者使用它们很少有实际的例子。当工会在现代(甚至遗留)的情况下有用吗?当你有非常有限的空间内工作我只有两个猜测是编程的微处理器,或者当你正在开发一个API(或类似的东西),并要强制最终用户只有一个几个对象/类型的实例,在一次。在这两种猜测甚至接近吧?

I have learned but don't really get unions. Every C or C++ text I go through introduces them (sometimes in passing), but they tend to give very few practical examples of why or where to use them. When would unions be useful in a modern (or even legacy) case? My only two guess would be programming microprocessors when you have very limited space to work with, or when you're developing an API (or something similar) and you want to force the end user to have only one instance of several objects/types at one time. Are these two guesses even close to right?

推荐答案

工会通常用于与该公司鉴别的:一个变量,表示该联盟的领域是有效的。例如,假设您想要创建自己的类型:

Unions are usually used with the company of a discriminator: a variable indicating which of the fields of the union is valid. For example, let's say you want to create your own Variant type:

struct my_variant_t {
    int type;
    union {
        char char_value;
        short short_value;
        int int_value;
        long long_value;
        float float_value;
        double double_value;
        void* ptr_value;
    };
};

然后你会使用它,例如:

Then you would use it such as:

/* construct a new float variant instance */
void init_float(struct my_variant_t* v, float initial_value) {
    v->type = VAR_FLOAT;
    v->float_value = initial_value;
}

/* Increments the value of the variant by the given int */
void inc_variant_by_int(struct my_variant_t* v, int n) {
    switch (v->type) {
    case VAR_FLOAT:
        v->float_value += n;
        break;

    case VAR_INT:
        v->int_value += n;
        break;
    ...
    }
}

这实际上是pretty常见的成语,特别是Visual Basic的内部。

This is actually a pretty common idiom, specially on Visual Basic internals.

有关一个真实的例子见SDL的 SDL_Event工会。 (实际源$ C ​​$ C这里)。有一个在联盟的顶部有一个键入字段,以及同一领域重复每SDL_ *事件结构。然后,处理正确的情况下,您需要检查的值键入字段。

For a real example see SDL's SDL_Event union. (actual source code here). There is a type field at the top of the union, and the same field is repeated on every SDL_*Event struct. Then, to handle the correct event you need to check the value of the type field.

好处很简单:有一个单一的数据类型来处理所有类型的事件,而无需使用不必要的内存

The benefits are simple: there is one single data type to handle all event types without using unnecessary memory.

这篇关于当有人会用一个工会吗?它是从唯一的C-天残?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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