c++gccgcc-warninggcc8

c++ const_cast gcc 8.2.1 -Wignored-qualifiers bug?


The following program produces this with gcc 8.2.1:

warning: type qualifiers ignored on cast result type [-Wignored-qualifiers] int * const ptrCast = const_cast(ptr);

int main() {                                         
  int i = 0;                                         
  const int * const ptr = &i;                        
  int * const ptrCast = const_cast<int * const>(ptr);

  return *ptrCast;                                   
}

Compiled as: gcc -Wignored-qualifiers test.cc

From my understanding of const_cast this should not give a warning. Can anyone verify this?


Solution

  • I think you misunderstood the warning.

    It's not about the lack of const here:

    const_cast<      int * const>(ptr)
    //         const  
    

    Rather, it's about the presence of const here:

    const_cast<int * const>(ptr)
    //               ^~~~~
    

    Here const has absolutely zero effect and can be removed, that's what the warning is saying.