Correct usage(s) of const_cast<>

后端 未结 8 821
陌清茗
陌清茗 2020-12-02 14:23

As a common rule, it is very often considered a bad practice to use const_cast<>() in C++ code as it reveals (most of the time) a flaw in the design.

8条回答
  •  佛祖请我去吃肉
    2020-12-02 15:02

    One very legitimate use of this is when you have both a const and non const api (for const and non const objects respectively) as in

    class Bar {
       const SomeType& foo() const; 
       SomeType& foo();
    }
    

    Then since we don't want to duplicate the code in both functions we often use

    class Bar {
       SomeType& foo() {
          //Actual implementation 
       }
       const SomeType& foo() const {
            return const_cast(this)->foo();
       }
    };
    

    This is of course assuming that foo does not do something that violates the const semantics.

提交回复
热议问题