默认活动字段用于C++中的匿名联合。

huangapple go评论85阅读模式
英文:

default active field used for an anonymous union in c++

问题

在匿名联合体中,哪个字段将处于活动状态?

英文:

Say I have something like this:

 struct a_struct
 {
      int number = 0;
 
      union
      {
           long l;
           short* sp;
      };
 };

And then, somewhere else in code, I declare an instance of the struct like

 a_struct temp;
 temp.number = -1;

Which would be the active field in the anonymous union?

答案1

得分: 2

没有成员在匿名联合中默认初始化,因此没有子对象的生命周期开始,也没有成员被设置为活动状态。您将不得不通过分配(在允许的情况下)、通过new表达式、在a_struct的构造函数成员初始化列表中显式设置其中一个,或者通过向匿名联合的一个成员添加默认成员初始化程序来明确设置一个活动成员。

即使自动设置了一个活动成员,它仍然需要在读取之前分配一个值。匿名联合的成员需要具有平凡的默认构造函数,以便您的示例能够良好形成,因此它们在默认初始化后所有标量子对象中都将具有不确定的值,读取不确定的值会导致未定义的行为(有一些非常小的例外情况)。

英文:

No member is initialized in an anonymous union by-default and so no subobject has its lifetime started and no member is set active. You'll have to set one active explicitly by assignment (where allowed), by new-expression, in a_struct's constructor's member initializer list, or by adding a default member initializer to exactly one of the anonymous union members.

Even if one were automatically active, it would still need to be assigned a value before reading from it. The members of the anonymous union need to have trivial default constructors in order for your example to be well-formed at all, so they will have indeterminate values in all their scalar subobjects after default-initialization and reading an indeterminate value causes undefined behavior (with some very minor exceptions).

huangapple
  • 本文由 发表于 2023年7月28日 01:17:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782093.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定