const_cast VS mutable ? any difference?

前端 未结 4 792
时光说笑
时光说笑 2021-02-06 03:50

From my understanding , mutable cancels the constness of a variable

Class A {
  void foo() const {
  m_a = 5;
}
mutable int m_a;
};
         


        
4条回答
  •  悲&欢浪女
    2021-02-06 04:24

    const_cast cannot cancel constness of an object. const_cast can only remove constness from an access path to an object. Access path is a pointer or a reference to an object. Removing the constness from the access path has absolutely no effect on the object itself. Even if you use const_cast to remove the constness of the access path, that still does not necessarily give you the permission to modify the object. Whether you can do it or not still depends on the object itself. If it is const, you are not allowed to modify it and any attempts to do so will result in undefined behavior.

    For example, this illustrates the intended use of const_cast

      int i = 5; // non-constant object
      const int *p = &i; // `p` is a const access path to `i`
    
      // Since we know that `i` is not a const, we can remove constness...
      int *q = const_cast(p);
      // ... and legally modify `i`
      *q = 10;
      // Now `i` is 10
    

    The only reason the above is legal and valid is the fact that i is actually a non-constant object, and we know about it.

    If the original object was really constant, then the above code would produce undefined behavior:

      const int j = 5; // constant object
      const int *p = &j; // `p` is a const access path to `j`
    
      int *q = const_cast(p); // `q` is a non-const access path to `j`
      *q = 10; // UNDEFINED BEHAVIOR !!!
    

    C++ language does not allow you to modify constant objects and const_cast is completely powerless here, regardless of how you use it.

    mutable is a completely different thing. mutable creates a data filed that can be legally modified even if the containing object is declared const. In that sense mutable does allow you to modify [some designated parts of] constant objects. const_cast, on the other hand, can't do anything like that.

提交回复
热议问题