why const_cast??

As with help of const_const if some one is going to modify my declared constant object then what is use of const qualifier?

I mean how someone ensure that what he has declared as a const is not going to modified anyways??

just want to know :)
It is for use in incorrectly defined systems that declare things as const that should not be mutable that should be const. If you declare a const object and use const_cast to try to modify it anyway, behavior is undefined. It may actually modify the object, it may not because the object is in read-only memory, it may crash inexplicably 1 minute later, etc.
Last edited on
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.
@Disch: Yeah, you're right, I mistyped what I was thinking.
Topic archived. No new replies allowed.