Is it allowed to cast away const on a const-defined object as long as it is not actually modified?

前端 未结 2 961
借酒劲吻你
借酒劲吻你 2020-12-17 10:51

Is the following allowed:

const int const_array[] = { 42 };

int maybe_inc(bool write, int* array) {
  if (write) array[0]++;
  return array[0];
}

int main(         


        
2条回答
  •  死守一世寂寞
    2020-12-17 11:10

    If it compiles, then it is allowed. But it does not mean, it is legal.

    #include 
    
    int main(int argc, char *argv[]) 
    {
        const int arr[] = {1, 2, 3};
        int* parr = const_cast(arr);
        parr[0] = 0;
        for(auto& n : arr)
            std::cout << n << std::endl;
    }
    

    The above code compiles in Ubuntu 20.04 g++ compiler. It also runs without problem. But the above code actually is undefined behaviour.

提交回复
热议问题