问题描述
看下面的代码:
struct A {
short s;
int i;
};
struct B {
short s;
int i;
};
union U {
A a;
B b;
};
int fn() {
U u;
u.a.i = 1;
return u.b.i;
}
是否保证fn()
返回1
?
注意:这是对此的后续问题
Note: this is a follow-up question to this.
推荐答案
是的,这是定义的行为.首先让我们看看标准关于A
和B
的内容. [class.prop]/3 有
Yes, this is defined behavior. First lets see what the standard has to say about A
and B
. [class.prop]/3 has
- 没有非标准布局类(或此类数组)或引用的非静态数据成员,
- 没有虚拟函数,也没有虚拟基类,
- 对所有非静态数据成员具有相同的访问控制,
- 没有非标准布局的基类,
- 最多具有一个任何给定类型的基类子对象,
- 具有该类及其基类中所有的非静态数据成员和位字段,并且首先在同一类中声明它们,并且
- [...](在这种情况下,这里什么也没说)
- has no non-static data members of type non-standard-layout class (or array of such types) or reference,
- has no virtual functions and no virtual base classes,
- has the same access control for all non-static data members,
- has no non-standard-layout base classes,
- has at most one base class subobject of any given type,
- has all non-static data members and bit-fields in the class and its base classes first declared in the same class, and
- [...] (nothing said here has any bearing in this case)
所以A
和B
都是标准布局类型.如果我们查看 [class.mem]/23
So A
and B
are both standard layout types. If we look at [class.mem]/23
struct T1 { int a, b; };
struct T2 { int c; double d; };
union U { T1 t1; T2 t2; };
int f() {
U u = { { 1, 2 } }; // active member is t1
return u.t2.c; // OK, as if u.t1.a were nominated
}
-示例示例"] [注:通过非易失性类型的glvalue读取易失性对象具有未定义的行为([dcl.type.cv]). —尾注]
— end example ] [ Note: Reading a volatile object through a glvalue of non-volatile type has undefined behavior ([dcl.type.cv]). — end note ]
那么我们就有了这样的类,它们具有相同的公共初始序列,布局相同,并且访问非活动类型的相同成员就像访问活动类型的成员一样.
Then we have that the classes have the same common initial sequence, are laid out the same, and accessing the same member of the non-active type is treated as if accessing that member of the active type.
这篇关于布局兼容类型的并集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!