C++ forbidden pointer to pointer 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 ** 的转换,Derived1 和 Derived2 类型派生时会出现问题来自相同的 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*.
这篇关于C++禁止指针到指针转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++禁止指针到指针转换
- 近似搜索的工作原理 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
