只有一个成员的匿名联盟

Anonymous union with only one member

本文关键字:联盟 有一个 成员      更新时间:2023-10-16

我遇到了这段代码,只有一个成员在一个匿名联合中(在查看UE4源代码时不引用它(,我想知道这个匿名联合。 它只是一些从未清理过的旧代码,还是与对齐或其他任何东西有关?

struct Matrix4 {
union { 
__declspec(align(16)) float M[4][4];
};
// Methods
};

语法__declspec(align(16))表明这段代码是为Visual Studio编写的。

我猜这些代码的作者想利用Visual Studio编译器的特殊性,出于性能原因,不默认初始化union内的字段。

请考虑以下示例:

struct Matrix4 {
alignas(16) float M[4][4];
};
// ok everywhere
static_assert( Matrix4().M[0][0] == 0 );
struct Matrix4U {
union { 
alignas(16) float M[4][4];
};
};
// fails in Visual Studio
static_assert( Matrix4U().M[0][0] == 0 );

这里Matrix4内部没有匿名联合,它的默认构造函数Matrix4()用零初始化M,正如static_assert所证明的那样。

Matrix4U以匿名联合包装M(如问题中所示(跳过Matrix4U()中的零初始化,static_asserts打印错误(仅在 MSVC 中(:

<source>(15): error C2131: expression did not evaluate to a constant
<source>(15): note: failure was caused by a read of an uninitialized symbol
<source>(15): note: see usage of 'Matrix4U::M'

在线演示:https://gcc.godbolt.org/z/hYcrEcnMc

相关文章: