Why does const_cast remove constness for a pointer but not for a pointer to a const?

后端 未结 3 921
小鲜肉
小鲜肉 2021-02-05 12:31

I understand that const_cast works with pointers and references.

I\'m assuming that the input to const_cast should be a pointe

3条回答
  •  礼貌的吻别
    2021-02-05 13:21

    Modifying the constant via the const_cast is undefined behaviour.

    The compiler sees that you are trying to print a constant variable, knows it can never change so compiles:

    cout << "i: " << i << endl;
    

    to:

    cout << "i: " << 123 << endl;
    

    see: https://godbolt.org/z/bYb0mx. With optimisations enabled it optimises your code to just printing 123: https://godbolt.org/z/4Ttlmj.

    Ultimately compilers make assumptions in order to create faster/smaller code, if you enter the realms of undefined behaviour some of those assumptions may be incorrect and produce surprising results.

提交回复
热议问题