C++ forbidden pointer to pointer conversion

前端 未结 1 1222
长情又很酷
长情又很酷 2020-12-19 18:24

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

相关标签:
1条回答
  • 2020-12-19 19:04

    Type * to const Type* is allowed:

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

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

    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
    

    The last line may alter const t_const !

    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 ;
    

    and a Derived1 * points to a Derived2.

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

    0 讨论(0)
提交回复
热议问题