代码之家  ›  专栏  ›  技术社区  ›  kiriloff

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

  •  3
  • kiriloff  · 技术社区  · 13 年前

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

    为什么这些转换是wtong?是否还有其他无法进行指针到指针转换的示例?

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

    1 回复  |  直到 13 年前
        1
  •  5
  •   kiriloff    13 年前

    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 ** 转换,当 Derived1 Derived2 类型派生自相同 Base 然后

    Derived1 d1;
    Derived1* ptrtod1 = &d1;
    Derived1** ptrtoptrtod1 = &ptrtod1 ;
    
    Derived2 d2;
    Derived2* ptrtod2 = &d2;
    
    Base** ptrtoptrtobase = ptrtoptrtod1 ;
    *ptrtoptrtobase  = ptrtod2 ;
    

    和一个 Derived1 * 指向a 衍生2 .

    正确的方式 类型** 指向const的指针的指针使其成为 Type const* const* .