Date: Sat, 1 Feb 2020 09:54:24 +0300
According to the standard the following code contains UB
union U {
struct A {
int x, y;
} a;
struct B {
int s, t;
} b;
};
int f() {
U u;
u.a = { 1, 2 };
u.b.s = 3; // ends lifetime of u.a
(http://eel.is/c++draft/class.union#6.note-1)
return u.b.t; // u.a.y is already dead, u.b.t is not initialized yet
}
U::A and U::B are layout-compatible and so subobjects of U could be read
interchangeably, but mix of read and write operations is still prohibited.
I don't see fundamental reasons for this restriction, for instance how it
prevents TBAA or something similar. Is the current behavior a deficiency of
the standard which should be fixed somehow in the future or am I missing
something important?
union U {
struct A {
int x, y;
} a;
struct B {
int s, t;
} b;
};
int f() {
U u;
u.a = { 1, 2 };
u.b.s = 3; // ends lifetime of u.a
(http://eel.is/c++draft/class.union#6.note-1)
return u.b.t; // u.a.y is already dead, u.b.t is not initialized yet
}
U::A and U::B are layout-compatible and so subobjects of U could be read
interchangeably, but mix of read and write operations is still prohibited.
I don't see fundamental reasons for this restriction, for instance how it
prevents TBAA or something similar. Is the current behavior a deficiency of
the standard which should be fixed somehow in the future or am I missing
something important?
-- Andrey Davydov
Received on 2020-02-01 00:57:12