Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is const_cast<const Type*> ever useful?

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)?

like image 322
sharptooth Avatar asked Mar 16 '11 10:03

sharptooth


2 Answers

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.

like image 92
Matthieu M. Avatar answered Oct 07 '22 09:10

Matthieu M.


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*);
}
like image 20
Armen Tsirunyan Avatar answered Oct 07 '22 11:10

Armen Tsirunyan