A
aschepler
Consider this compilation unit:
struct Base {};
struct A : public Base { int x; };
struct B : public Base { int y; };
int Base::*const px = static_cast<int Base::*>(&A::x);
int Base::*const py = static_cast<int Base::*>(&B::y);
bool f() {
return px == py;
}
First, is the program ill-formed? Or is the behavior undefined?
5.10p2 says px == py "if and only if they would refer to the same
member of the same most derived object (1.8) or the same subobject if
they were dereferenced with a hypothetical object of the associated
class type." I assume the "associated class type" here is Base. But
5.2.9p9 and 5.5p4 make it clear that dereferencing an object with
dynamic type Base using px or py gives undefined behavior.
If the above is ill-formed or undefined, does it follow that the
expression (px == px) has the same problem?
Not too surprisingly, my compiler has the above f() return true. If
this happens, it seems reasonable to assume that the following also
always returns true, although the a.*py is technically at best
undefined:
bool g( A& a ) {
return &(a.*py) == &a.x;
}
Realistically, it seems like I can count on the "logic" that f()
implies g(), even though the Standard doesn't technically guarantee
this. But if any of this is ill-formed, I want to avoid it.
struct Base {};
struct A : public Base { int x; };
struct B : public Base { int y; };
int Base::*const px = static_cast<int Base::*>(&A::x);
int Base::*const py = static_cast<int Base::*>(&B::y);
bool f() {
return px == py;
}
First, is the program ill-formed? Or is the behavior undefined?
5.10p2 says px == py "if and only if they would refer to the same
member of the same most derived object (1.8) or the same subobject if
they were dereferenced with a hypothetical object of the associated
class type." I assume the "associated class type" here is Base. But
5.2.9p9 and 5.5p4 make it clear that dereferencing an object with
dynamic type Base using px or py gives undefined behavior.
If the above is ill-formed or undefined, does it follow that the
expression (px == px) has the same problem?
Not too surprisingly, my compiler has the above f() return true. If
this happens, it seems reasonable to assume that the following also
always returns true, although the a.*py is technically at best
undefined:
bool g( A& a ) {
return &(a.*py) == &a.x;
}
Realistically, it seems like I can count on the "logic" that f()
implies g(), even though the Standard doesn't technically guarantee
this. But if any of this is ill-formed, I want to avoid it.