Correct usage(s) of const_cast<>

后端 未结 8 822
陌清茗
陌清茗 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 14:49

    Like others have said, its primary purpose is to remove const from objects in order to pass to non-const correct functions you know won't modify the argument.

    There is a trick (by Meyers?) to avoid code duplication, and it goes like this:

    struct foo
    {
        const return_type& get(void) const
        {
            // fancy pants code that you definitely
            // don't want to repeat
    
            return theValue; // and got it
        }
    
        return_type& get(void)
        {
            // well-defined: Add const to *this,
            // call the const version, then
            // const-cast to remove const (because
            // *this is non-const, this is ok)
            return const_cast(static_cast(*this).get());
        }
    };
    

提交回复
热议问题