C/C++ changing the value of a const

后端 未结 18 1835
醉梦人生
醉梦人生 2020-11-28 07:28

I had an article, but I lost it. It showed and described a couple of C/C++ tricks that people should be careful. One of them interested me but now that I am trying to repli

18条回答
  •  囚心锁ツ
    2020-11-28 07:41

    Note any attempt to cast away constness is undefined by the standard. From 7.1.5.1 of the standard:

    Except that any class member declared mutable can be modified, any attempt to modify a const object during its lifetime results in undefined behavior.

    And right after this example is used:

    const int* ciq = new const int (3);     //  initialized as required
    int* iq = const_cast(ciq);        //  cast required
    *iq = 4;                                //  undefined: modifies a  const  object
    

    So in short what you want to do isn't possible using standard C++.

    Further when the compiler encounters a declaration like

    const int a = 3; // I promisse i won't change a
    

    it is free to replace any occurance of 'a' with 3 (effectively doing the same thing as #define a 3)

提交回复
热议问题