const to Non-const Conversion in C++

后端 未结 5 1455
鱼传尺愫
鱼传尺愫 2020-12-04 15:11

I\'m really annoyed by const keyword these days, as I\'m not quite familiar with it. I had a vector that stores all const pointers like vector

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 15:51

    You can assign a const object to a non-const object just fine. Because you're copying and thus creating a new object, constness is not violated.

    Like so:

    int main() {
       const int a = 3;
       int b = a;
    }
    

    It's different if you want to obtain a pointer or reference to the original, const object:

    int main() {
       const int a = 3;
       int& b = a;       // or int* b = &a;
    }
    
    //  error: invalid initialization of reference of type 'int&' from
    //         expression of type 'const int'
    

    You can use const_cast to hack around the type safety if you really must, but recall that you're doing exactly that: getting rid of the type safety. It's still undefined to modify a through b in the below example:

    int main() {
       const int a = 3;
       int& b = const_cast(a);
    
       b = 3;
    }
    

    Although it compiles without errors, anything can happen including opening a black hole or transferring all your hard-earned savings into my bank account.

    If you have arrived at what you think is a requirement to do this, I'd urgently revisit your design because something is very wrong with it.

提交回复
热议问题