How to convert “pointer to pointer type” to const?

后端 未结 2 2052
南方客
南方客 2020-12-01 16:10

With the following code

void TestF(const double ** testv){;}
void callTest(){
    double** test;
    TestF(test);
}

I get this:



        
2条回答
  •  爱一瞬间的悲伤
    2020-12-01 17:10

    It is correct that a double ** cannot be implicitly converted to a const double **. It can be converted to a const double * const *, though.

    Imagine this scenario:

    const double cd = 7.0;
    double d = 4.0;
    double *pd = &d;
    double **ppd = &pd;
    const double **ppCd = ppd;  //this is illegal, but if it were possible:
    *ppCd = &cd;  //now *ppCd, which is also *ppd, which is pd, points to cd
    *pd = 3.14; // pd now points to cd and thus modifies a const value!
    

    So, if your function does not intend to modify any of the pointers involved, change it to take a const double * const *. If it intends to do modifications, you must decide whether all the modifications it does are safe and thus const_cast can be used, or whether you really need to pass in a const double **.

提交回复
热议问题