我以前很轻松地使用过工会;今天当我读到这篇文章并知道这个代码时,我很震惊

union ARGB
{
    uint32_t colour;

    struct componentsTag
    {
        uint8_t b;
        uint8_t g;
        uint8_t r;
        uint8_t a;
    } components;

} pixel;

pixel.colour = 0xff040201;  // ARGB::colour is the active member from now on

// somewhere down the line, without any edit to pixel

if(pixel.components.a)      // accessing the non-active member ARGB::components

实际上是未定义的行为,即从工会成员中读取除最近写的人以外的内容会导致未定义的行为。如果这不是联合的预期用途,那么什么才是?谁能详细解释一下吗?

更新:

我想事后澄清一些事情。

The answer to the question isn't the same for C and C++; my ignorant younger self tagged it as both C and C++. After scouring through C++11's standard I couldn't conclusively say that it calls out accessing/inspecting a non-active union member is undefined/unspecified/implementation-defined. All I could find was §9.5/1: If a standard-layout union contains several standard-layout structs that share a common initial sequence, and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members. §9.2/19: Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members. While in C, (C99 TC3 - DR 283 onwards) it's legal to do so (thanks to Pascal Cuoq for bringing this up). However, attempting to do it can still lead to undefined behavior, if the value read happens to be invalid (so called "trap representation") for the type it is read through. Otherwise, the value read is implementation defined. C89/90 called this out under unspecified behavior (Annex J) and K&R's book says it's implementation defined. Quote from K&R: This is the purpose of a union - a single variable that can legitimately hold any of one of several types. [...] so long as the usage is consistent: the type retrieved must be the type most recently stored. It is the programmer's responsibility to keep track of which type is currently stored in a union; the results are implementation-dependent if something is stored as one type and extracted as another. Extract from Stroustrup's TC++PL (emphasis mine) Use of unions can be essential for compatness of data [...] sometimes misused for "type conversion".

最重要的是,这个问题(它的标题从我的提问开始就没有改变)是为了理解联合的目的而提出的,而不是关于标准允许什么。例如,使用继承来实现代码重用当然是c++标准允许的,但这并不是将继承引入c++语言特性的目的或初衷。这就是为什么安德烈的回答仍然被人们所接受的原因。


当前回答

在1974年记录的C语言中,所有结构成员共享一个公共名称空间,“ptr->成员”的含义被定义为添加 成员的位移到“ptr”,并使用 成员的类型。这种设计使得成员可以使用相同的ptr 名称取自不同的结构定义,但偏移量相同; 程序员将这种能力用于各种目的。

When structure members were assigned their own namespaces, it became impossible to declare two structure members with the same displacement. Adding unions to the language made it possible to achieve the same semantics that had been available in earlier versions of the language (though the inability to have names exported to an enclosing context may have still necessitated using a find/replace to replace foo->member into foo->type1.member). What was important was not so much that the people who added unions have any particular target usage in mind, but rather that they provide a means by which programmers who had relied upon the earlier semantics, for whatever purpose, should still be able to achieve the same semantics even if they had to use a different syntax to do it.

其他回答

@bobobobo代码是正确的,正如@Joshua指出的那样(遗憾的是,我不允许添加注释,所以在这里做,IMO不允许它放在第一位的坏决定):

https://en.cppreference.com/w/cpp/language/data_members#Standard_layout告诉我们这样做是可以的,至少从c++ 14开始

在具有非并集类类型T1的活动成员的标准布局联合中,允许读取另一个非并集类类型T2的联合成员的非静态数据成员m,前提是m是T1和T2的公共初始序列的一部分(除非通过非易失性glvalue读取易失性成员是未定义的)。

因为在当前的情况下T1和T2无论如何都提供了相同的类型。

尽管这是严格未定义的行为,但实际上它适用于几乎任何编译器。它是一种被广泛使用的范例,任何有自尊的编译器都需要在这种情况下做“正确的事情”。它当然比类型双关语更受欢迎,在某些编译器中,类型双关语很可能会生成坏代码。

我经常遇到的联合最常见的用法是别名。

考虑以下几点:

union Vector3f
{
  struct{ float x,y,z ; } ;
  float elts[3];
}

这有什么用?它允许通过任意名称干净利落地访问Vector3f的vec;成员:

vec.x=vec.y=vec.z=1.f ;

或者通过整数访问数组

for( int i = 0 ; i < 3 ; i++ )
  vec.elts[i]=1.f;

在某些情况下,通过名称访问是最清晰的方法。在其他情况下,特别是当以编程方式选择轴时,更简单的方法是通过数值索引访问轴- x为0,y为1,z为2。

你可以使用a并集,主要有两个原因:

一种以不同方式访问相同数据的方便方法,就像在您的示例中一样 当存在不同的数据成员,其中只有一个可以“活动”时,一种节省空间的方法

1实际上更像是一个c风格的黑客,在你知道目标系统的内存架构是如何工作的基础上,以捷径编写代码。就像之前所说的,如果你没有瞄准许多不同的平台,你便能够避开这一问题。我相信一些编译器可能也会让你使用打包指令(我知道他们在结构上这样做)?

2的一个很好的例子。可以在COM中广泛使用的VARIANT类型中找到。

行为可能没有定义,但这只是意味着没有一个“标准”。所有优秀的编译器都提供#pragmas来控制打包和对齐,但可能有不同的默认值。默认值也会根据所使用的优化设置而改变。

此外,工会不仅仅是为了节省空间。它们可以帮助现代编译器使用类型双关语。如果你reinterpret_cast<>所有的东西,编译器就不能假设你正在做什么。它可能不得不放弃它所知道的类型并重新开始(强制写回内存,与CPU时钟速度相比,这是非常低效的)。