Usage: const_cast <type_id> (expression)
This operator is used to remove the const and volatile attributes of the type.
If you see const_cast, you should know that it is used to convert the const nature of the expression. Yes. The const attribute can be converted only when our const_cast is used!
OK. Let's look at a piece of code:
[Cpp]
Const char m = 'T ';
Const char * cm = & m;
Char * n = const_cast <char *> (cm );
* N = 'a ';
Cout <* n <endl;
Well, after the code is compiled, you can see that the result should not be 'T', right, and the final output is 'A ', we changed the value of the variable pointed to by the n pointer ~ Good. This is the credit of our const_cast!
But if so:
[Cpp]
Const char m = 'T ';
Const char * cm = & m;
Char * n = cm;
* N = 'a ';
Cout <* n <endl;
It is a tragedy and cannot be compiled!
You should have understood the above two pieces of code a little bit, but let's look at the following:
[Cpp]
Const char m = 'T ';
Const char * cm = & m;
Char * n = (char *) cm;
* N = 'a ';
Cout <* n <endl;
Oh .. Compilation is successful, and the final result is ~~, Why?
In fact, in C ++, conversions between pointers are not checked. They are converted at will and can be converted to any pointer!
That's it!
By the way, const_cast cannot be used to execute any type conversion, which will cause compilation errors!
[Cpp]
Const char m = 'T ';
Const char * cm = & m;
Int * n = const_cast <int *> (cm );
* N = 'a ';
Cout <* n <endl;
Unfortunately, this code reports an error. Check the error prompt:
Oh ~ This is indeed the case!
Speaking of this, I want to talk about it. do not modify the value of the const variable. But what is the purpose of const_cast?
Here, there is an example in C ++ Primer version 4. Suppose there is a function s, which has a unique parameter of the char * type. We read it only and do not write it! When accessing this function, we 'd better choose to modify it to accept parameters of the const char * type! If not, we need to use const_cast to call the s function with a const value!
[Cpp]
Void s (char *)
{
Cout <'A' <endl;
}
Char a ='s ';
Const char * ss = &;
S (const_cast <char *> (ss ));
OK, we have compiled it!