const/非const对象指针的并集 [英] Union of const/non-const Object Pointers

查看:60
本文介绍了const/非const对象指针的并集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例代码:

  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;} 

在构造时, 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和非const成员的并集时,这些平等是否总是正确?

是的,两个指针都将引用同一地址中的同一对象.内存中的位将相同.

但是可以保证b.mA始终等于b.mConstA吗?

是的,它们的值将相同,但这并不意味着您可以真正使用它.这等效于使用 const_cast ,您将获得指向该对象的非const指针,但是如果该对象确实是 const ,则使用该指针修改该对象是未定义的行为.

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?

解决方案

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.

这篇关于const/非const对象指针的并集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆