【问题标题】:C++ forbidden pointer to pointer conversionC++禁止指针到指针转换
【发布时间】:2013-04-14 09:33:18
【问题描述】:

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

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

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

【问题讨论】:

  • 为什么应该被允许?一般情况下,您不能将U* 转换为W*,因为这没有任何意义...
  • 我想在两个转换禁令之间画平行线,这不是你提到的线程的重点。 WIM,我在问其他的转换禁令有什么相似之处。
  • 重复的 Q 在 C 中,而不是 C++。但是 C++ 只是收紧了类型系统规则,所以禁令仍然是出于同样的原因。

标签: c++ pointers type-conversion


【解决方案1】:

Type *const Type* 是允许的:

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

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

如果允许Type **const Type** 的转换,我们可能会

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

对于derived **Base ** 的转换,当Derived1Derived2 类型派生自相同的Base 时会出现问题。那么,

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

Derived2 d2;
Derived2* ptrtod2 = &d2;

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

Derived1 * 指向Derived2

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

【讨论】:

  • 不幸的是,变量名真的不可读。简单地将ptrto 替换为p 应该会有所帮助。
  • *ptrtoptrtobase = ptrtod2 ; 不会导致切片吗? (我不知道用指向父类的指针分配是否会产生切片)
猜你喜欢
  • 1970-01-01
  • 2016-08-24
  • 2022-01-18
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多