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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With