const/非const对象指针的并集 [英] Union of const/non-const Object Pointers
问题描述
请考虑以下示例代码:
A类{上市:A():n(0){}int n;};B级{上市:B(A * a):mA(a){}B(const A * a):mConstA(a){}工会{A * mA;const A * mConstA;};};int main(){A a;B b1(& a);B b2(const_cast< const A *>(& a));返回0;}
在构造时, 当您具有 类似地,下面的代码可以正常编译/运行: 但是可以保证 当您拥有const和非const成员的并集时,这些平等是否总是正确? 是的,两个指针都将引用同一地址中的同一对象.内存中的位将相同. 但是可以保证b.mA始终等于b.mConstA吗? 是的,它们的值将相同,但这并不意味着您可以真正使用它.这等效于使用 Consider the sample code below: At construction, Are these equalities always true when you have a union of Similarly, the code below compiles/runs fine: But is it guaranteed for 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/非const对象指针的并集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! b1
将具有指向 a
的可变指针,而 b2
将具有指向 a 的不变指针.代码>.在这种情况下,
b1.mA
等于 b2.mConstA
,而 b1.mConstA
等于 b2.mA
./p> const
和非 const
对象指针的并集时,这些相等性是否始终为真?
int main(){const A a;B b(& a);b.mA-> n = 3;//亵渎!!!返回0;}
b.mA
始终等于 b.mConstA
吗? const_cast
,您将获得指向该对象的非const指针,但是如果该对象确实是 const
,则使用该指针修改该对象是未定义的行为.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;
}
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
.const
and non-const
object pointers?int main()
{
const A a;
B b(&a);
b.mA->n = 3; // Blasphemy!!!
return 0;
}
b.mA
to always be equal to b.mConstA
?
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.