Conversion from int** to const int**

前端 未结 3 1081
逝去的感伤
逝去的感伤 2020-12-10 05:22

Why do I get in this code:

void foo ( const int ** );

int main() {
    int ** v = new int * [10];
    foo(v);

    return 0;
}

this error:

3条回答
  •  攒了一身酷
    2020-12-10 06:22

    You're being misled here by C++'s confusing parsing rules for pointers. It might be clearer to look at this way:

    typedef const int * ptr_to_const_int;
    void foo( ptr_to_const_int *);
    int main() {
        int ** v = new int * [10];
        foo(v);
    
        return 0;
    }
    

    What foo()'s parameter list promises is that you'll be passing it a pointer to a (pointer-to-constant-thing). But new int*[10] means "pointer to (pointer-to-not-constant-thing)".

    So if foo were defined like this:

    foo( const int **p )
    {
      (*p); //<-- this is actually of type const int *
    }
    

    whereas I think you're expecting that

    foo( const int **p )
    {
      (*p); //<-- you're expecting this to be of type int *
      p = 0; //<-- and this to throw a compiler error because p is const
    }
    

    but it's not p that you're declaring to be constant, it's the thing it points to.

    Anyway just use a typedef in this case and everything will be clear and readable.

提交回复
热议问题