Is const_cast safe?

后端 未结 6 2159
名媛妹妹
名媛妹妹 2020-11-22 12:17

I can\'t find much information on const_cast. The only info I could find (on Stack Overflow) is:

The const_cast<>() i

6条回答
  •  自闭症患者
    2020-11-22 12:55

    I can think of two situations where const_cast is safe and useful (there may be other valid cases).

    One is when you have a const instance, reference, or pointer, and you want to pass a pointer or reference to an API that is not const-correct, but that you're CERTAIN won't modify the object. You can const_cast the pointer and pass it to the API, trusting that it won't really change anything. For example:

    void log(char* text);   // Won't change text -- just const-incorrect
    
    void my_func(const std::string& message)
    {
        log(const_cast(&message.c_str()));
    }
    

    The other is if you're using an older compiler that doesn't implement 'mutable', and you want to create a class that is logically const but not bitwise const. You can const_cast 'this' within a const method and modify members of your class.

    class MyClass
    {
        char cached_data[10000]; // should be mutable
        bool cache_dirty;        // should also be mutable
    
      public:
    
        char getData(int index) const
        {
            if (cache_dirty)
            {
              MyClass* thisptr = const_cast(this);
              update_cache(thisptr->cached_data);
            }
            return cached_data[index];
        }
    };
    

提交回复
热议问题