C++禁止指针到指针转换

2022-01-13 00:00:00 pointers type-conversion c++

在 C++ 中,Type **Type const ** 的转换是被禁止的.此外,不允许将 derived ** 转换为 Base **.

In C++, Type ** to Type const ** conversion is forbidden. Also, conversion from derived ** to Base ** is not allowed.

为什么这些转换是 wtong ?还有其他不能发生指针转换的例子吗?

Why are these conversions wtong ? Are there other examples where pointer to pointer conversion cannot happen ?

有没有办法解决:如何将指向 Type 类型的非常量对象的指针转换为指向 Type 类型的 const 对象的指针code>,因为 Type ** --> Type const ** 不成功?

Is there a way to work around: how to convert a pointer to pointer to a non-const object of type Type to a pointer to pointer to const object of type Type, since Type ** --> Type const ** does not make it ?

推荐答案

Type * to const Type* 是允许的:

Type t;
Type *p = &t;
const Type*q = p;

*p可以通过p修改,但不能通过q修改.

*p can be modified through p but not through q.

如果 Type **const Type** 转换被允许,我们可能有

If Type ** to const Type** conversion were allowed, we may have

const Type t_const;

Type* p;
Type** ptrtop = &p;

const Type** constp = ptrtop ; // this is not allowed
*constp = t_const; // then p points to t_const, right ?

p->mutate(); // with mutate a mutator, 
// that can be called on pointer to non-const p

最后一行可能会改变 const t_const

The last line may alter const t_const !

derived **Base ** 的转换,Derived1Derived2 类型派生时会出现问题来自相同的 Base.那么,

For the derived ** to Base ** conversion, problem occurs when Derived1 and Derived2 types derive from same Base. Then,

Derived1 d1;
Derived1* ptrtod1 = &d1;
Derived1** ptrtoptrtod1 = &ptrtod1 ;

Derived2 d2;
Derived2* ptrtod2 = &d2;

Base** ptrtoptrtobase = ptrtoptrtod1 ;
*ptrtoptrtobase  = ptrtod2 ;

并且一个 Derived1 * 指向一个 Derived2.

and a Derived1 * points to a Derived2.

Type ** 设为指向 const 的指针的正确方法是将其设为 Type const* const*.

Right way to make a Type ** a pointer to pointer to a const is to make it a Type const* const*.

相关文章