Correct usage(s) of const_cast<>

后端 未结 8 812
陌清茗
陌清茗 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<Bar*>(this)->foo();
       }
    };
    

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

    0 讨论(0)
  • 2020-12-02 15:09

    it is pretty much designed to be only used with legacy APIs that are not const correct i.e. with a function you can't change that has non const interface but doesn't actually mutate anything on the interface

    0 讨论(0)
提交回复
热议问题