Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are Legitimate uses of const_cast

Tags:

c++

constants

Since with help of const_cast anyone can modify my declared constant object - what use is the const qualifier?

I mean how can someone ensure that what he declared const is not going to be modified anyway?

like image 697
mac mohan Avatar asked Sep 17 '13 05:09

mac mohan


Video Answer


1 Answers

You are right, uses of const_cast often indicates a design flaw, or an API that is out of your control.

However, there is an exception, it's useful in the context of overloaded functions. I'm quoting an example from the book C++ Primer:

// 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;
}

This function takes and returns references to const string. We can call the function on a pair of non-const 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 non-const 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<const string&>(s1),
                            const_cast<const string&>(s2));
    return const_cast<string&>(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, non-const arguments. Therefore, we know it is safe to cast that string back to a plain string& in the return.

like image 62
Yu Hao Avatar answered Sep 30 '22 20:09

Yu Hao