Correct usage(s) of const_cast<>

后端 未结 8 813
陌清茗
陌清茗 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:57

    There is an example of const_cast usage in c++ primer(5th edition) book. Below function returns reference to const string

    // return a reference to the shorter of two strings
    const string &shorterString(const string &s1, const string
    &s2)
    {
        return s1.size() <= s2.size() ? s1 : s2;
    }
    

    The book then mentions the case when we want a non const reference.

    We can call the function on a pair of nonconst string arguments, but we’ll get a reference to a const string as the result. We might want to have a version of shorterString that, when given nonconst arguments, would yield a plain reference. We can write this version of our function using a const_cast:

    string &shorterString(string &s1, string &s2)
    {
        auto &r = shorterString(const_cast(s1),
                                const_cast(s2));
        return const_cast(r);
    }
    

    This version calls the const version of shorterString by casting its arguments to references to const. That function returns a reference to a const string, which we know is bound to one of our original, nonconst arguments. Therefore, we know it is safe to cast that string back to a plain string& in the return.

    According to the book, it should be used if we know it is safe to cast.

提交回复
热议问题