问题
Consider the sample code below:
class A
{
public:
A() : n(0) {}
int n;
};
class B
{
public:
B(A* a) : mA(a) { }
B(const A* a) : mConstA(a) { }
union {
A* mA;
const A* mConstA;
};
};
int main()
{
A a;
B b1(&a);
B b2(const_cast<const A*>(&a));
return 0;
}
At construction, b1
would have a mutable pointer to a
, while b2
would have an immutable pointer to a
. In this scenario, b1.mA
equals b2.mConstA
, and b1.mConstA
equals b2.mA
.
Are these equalities always true when you have a union of const
and non-const
object pointers?
Similarly, the code below compiles/runs fine:
int main()
{
const A a;
B b(&a);
b.mA->n = 3; // Blasphemy!!!
return 0;
}
But is it guaranteed for b.mA
to always be equal to b.mConstA
?
回答1:
Are these equalities always true when you have a union of const and non-const members?
Yes, both pointers will refer to the same object in the same address. The bits in memory will be the same.
But is it guaranteed for b.mA to always be equal to b.mConstA?
Yes, their values will be the same, but that does not mean that you can really use it. This is equivalent to using const_cast
, you will get a non-const pointer to the object, but if the object is really const
, using that pointer to modify the object is undefined behavior.
来源:https://stackoverflow.com/questions/18063233/union-of-const-non-const-object-pointers