Recently I found a piece of C++ code that effectively does the following:
char* pointer = ...;
const char* constPointer = const_cast<const char*>( pointer );
Obviously the author thought that const_cast means "add const", but in fact const can be just as well added implicitly:
const char* constPointer = pointer;
Is there any case when I would really have to const_cast to a pointer-to-const (const_cast<const Type*> as in above example)?
const_cast, despite its name, is not specific to const; it works with cv-qualifiers which effectively comprises both const and volatile.
While adding such a qualifier is allowed transparently, removing any requires a const_cast.
Therefore, in the example you give:
char* p = /**/;
char const* q = const_cast<char const*>(p);
the presence of the const_cast is spurious (I personally think it obscures the syntax).
But you can wish to remove volatile, in which case you'll need it:
char const volatile* p = /**/;
char const* q = const_cast<char const*>(p);
This could appear, for example, in driver code.
You can use static_cast to add const as well. So I don't see any situation where you have to use const_cast to add const. But explicit casting (be it one or another) can sometimes be needed when you want to change the type of the object for example for overload resolution.
E.g.
void f(char*);
void f(const char*);
int main()
{
char* p = 0;
f(p); //calls f(char*)
f(static_cast<const char*>(p)); //calls f(const char*);
f(const_cast<const char*>(p)); //calls f(const char*);
}
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