c – 工会会员活跃的原因是什么?

前端之家收集整理的这篇文章主要介绍了c – 工会会员活跃的原因是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
什么使工会会员活跃?

我已经阅读了C 14标准的第9.5章(关于工会的第9.5章),但我还没有找到一个明确的答案,说明工会成员的活动是什么.

有一个说明:

In general,one must use explicit destructor calls and placement new
operators to change the active member of a union.

@H_502_10@

例如,

union U {
  int i;
  short s;
} u;

new(&u.i) int(42);

好的,放置新的更改活动成员,很明显.但是在使用具有普通构造函数的类型时,我们通常不使用placement new.

operator =是否在没有UB的情况下更改活动成员?

u.i = 42;

这里,operator =调用未构造的对象.它定义明确吗?

那这个呢?

struct A {
  int i0;
  int i1;
};
union U {
  A a;
  short s;
} u;

是什么让你成为你的活跃成员?设置i0和&我足够吗?

u.a.i0 = 42;
u.a.i1 = 99;

如果我写的怎么办:

u.a.i0 = 42;     // supposedly this doesn't change the active member to a,as i1 isn't set
int x = u.a.i0;  // is it fine to read from a.i0? a is not an active member supposedly

在u.a.i0 = 42;之后,活动成员不会改为a(我认为),所以UB要做int x = u.a.i0 ;?

C 17是否改进了活跃成员的描述?

解决方法

在C 17中,添加了一个段落,明确讨论了像u.i = 42这样的案例:

[class.union]/5 When the left operand of an assignment operator involves a member access expression (8.2.5) that nominates a union member,it may begin the lifetime of that union member,as described below. For an expression E,
define the set S(E) of subexpressions of E as follows:

(5.1) — If E is of the form A.B,S(E) contains the elements of S(A),and also contains A.B if B names a union member of a non-class,non-array type,or of a class type with a trivial default constructor that is not deleted,or an array of such types.

(5.2) — If E is of the form A[B] and is interpreted as a built-in array subscripting operator,S(E) is S(A) if A is of array type,S(B) if B is of array type,and empty otherwise.

(5.3) — Otherwise,S(E) is empty.

In an assignment expression of the form E1 = E2 that uses either the built-in assignment operator (8.18) or a trivial assignment operator (15.8),for each element X of S(E1),if modification of X would have undefined behavior under 6.8,an object of the type of X is implicitly created in the nominated storage; no initialization is performed and the beginning of its lifetime is sequenced after the value computation of the left and right operands and before the assignment. [ Note: This ends the lifetime of the prevIoUsly-active member of the union,if any (6.8). —end note ]

@H_502_10@

(接着是一个很长的例子,我懒得格式化,但你可以看到here.)

猜你在找的C&C++相关文章