Search code examples
c++castingconst-cast

C++ non const to const casting compilation error


the below code doesn't compile

void aaa(const int **a) {
}

int *a[] = {new int[2]};
aaa(a);

I got "cannot convert parameter 1 from 'int [1]' to 'const int *" in VS2010 and similar error in gcc

when I change my declaration to:

int const *a[] = {new int[2]};

or

const int *a[] = {new int[2]};

it compiles, but I don't understand why it doesn't accept a non const variable declaration


Solution

  • The type of a is int*[]; the type you want is int const**. int*[] converts to int**, but this will not convert implicitly to int const**. Consider the following code to understand why:

    static int const ci = 42;
    
    void aaa( int const** out )
    {
        *out = &ci;
    }
    
    int
    main()
    {
        int* pa;
        aaa( &pa );     //  NOT LEGAL, because...
        *pa = 0;        //  would now change ci
        std::cout << ci << std::endl;
        return 0;
    }
    

    As you can see, allowing this conversion would break const without requiring a cast.

    Depending on what you are doing, you might want to use:

    void aaa( int const* const* out );
    

    The implicit conversion of int** to int const *const * is legal. (Otherwise, you'll need a const_cast somewhere, to tell the compiler that you know what you're doing, and that it isn't really a problem.)