本文介绍了在C和C工会的目的++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用工会早前舒适;今天,当我读到,我感到震惊,才知道,这$ C $ç

 工会ARGB
{
    uint32_t的颜色;    结构componentsTag
    {
        uint8_t有B:
        uint8_t有克;
        uint8_t有ř;
        uint8_t有一个;
    } 组件;}像素;pixel.colour = 0xff040201; // ARGB ::颜色是活跃的成员从现在开始//某个地方的路线,没有任何编辑像素如果(pixel.components.a)//访问非活跃成员ARGB ::组件

实际上是不确定的行为,即从最近比写入导致不确定的行为之外的其他的工会成员阅读。如果这不是工会的使用目的是什么?可有人请精心解释一下吗?

更新:

我想澄清在事后的几件事情。


  • 的回答这个问题是不是C和C ++一样的;无知的年轻的自己标记它作为C和C ++。

  • 通过C ++ 11的标准精练我不能得出结论说,它叫一声访问/检查非活动的联合成员之后是未定义/未指定/实现定义。所有我能找到的第9.5节/ 1:

  • Extract from Stroustrup's TC++PL (emphasis mine)

Above all, this question (whose title remains unchanged since my ask) was posed with an intention of understanding the purpose of unions AND not on what the standard allows E.g. Using inheritance for code reuse is, of course, allowed by the C++ standard, but it wasn't the purpose or the original intention of introducing inheritance as a C++ language feature. This is the reason Andrey's answer continues to remain as the accepted one.

解决方案

The purpose of unions is rather obvious, but for some reason people miss it quite often.

The purpose of union is to save memory by using the same memory region for storing different objects at different times. That's it.

It is like a room in a hotel. Different people live in it for non-overlapping periods of time. These people never meet, and generally don't know anything about each other. By properly managing the time-sharing of the rooms (i.e. by making sure different people don't get assigned to one room at the same time), a relatively small hotel can provide accomodations to a relatively large number of people, which is what hotels are for.

That's exactly what union does. If you know that several objects in your program hold values with non-overlapping value-lifetimes, then you can "merge" these objects into a union and thus save memory. Just like a hotel room has at most one "active" tenant at each moment of time, a union has at most one "active" member at each moment of program time. Only the "active" member can be read. By writing into other member you switch the "active" status to that other member.

For some reason, this original purpose of the union got "overriden" with something completely different: writing one member of a union and then inspecting it through another member. This kind of memory reinterpretation is not a valid use of unions. It generally leads to undefined behavior.

EDIT: Using unions for the purposes of memory reinterpretation (i.e. writing one member and then reading another) was eventually made legal in one of the Technical Corrigendums to C99 standard. Now it is officially OK to do that in C. However, keep in mind that formally this does not protect you from running into undefined behavior by attempting to read a trap representation.

这篇关于在C和C工会的目的++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:40
查看更多