Legitimate uses of const_cast are extremely rare. Far more rare than legitimate uses of goto. If you find yourself using it, you're probably using it incorrectly.
Zhuge wrote: |
---|
It is for use in incorrectly defined systems that declare things as const that should not be |
It's say actually for the opposite of that. For incorrectly defined systems that declare things as
nonconst that should be const.
For example, there might be a very old C library which takes a
char*
as a parameter, but does not modify the passed in string data:
|
void doSomething(char* foo);
|
The problem here is that this does not work with std::string objects because to get a char pointer you have to use c_str() which gives you a
const char pointer.
Now, if doSomething does not actually attempt to modify the data, then casting away the const is fine:
1 2 3
|
string str = "whatever";
doSomething( const_cast<char*>( str.c_str() ) );
|
That's really what const_cast is primarily for: being able to call legacy/non-const-correct code from const-correct C++.
But again I must iterate this only works if 'doSomething'
does not attempt to modify the passed data. It is
never safe to take modify a const object or reference by simply casting away the constness of it.