Given below is my understanding:
Don't modify the value of the variable for which constness is removed. If you do, then it is results in undefined behaviour.
The only use of const_cast is in the below mentioned scenario:
Code:
void f1(int& pValue1)
{
//pValue1 is however not modified inside f1
//pValue1 is only used as rvalue (never should it use pValue1 as lvalue)
}
void f2(const int& pValue2)
{
f1( const_cast<int&>((pValue2)) );
}
===========================
For reference, code output of the original program (after modification to print the address):
Code:
z = 10 &z = 0x7fff5fbfc44c
*x =15 x = 0x7fff5fbfc44c
ref = 15 &ref = 0x7fff5fbfc44c
As others have already said, this is undefined behavior. However, one optimization technique is to replace all const variables by their actual value. So, if you were to look at the assembly, you'd probably see that the compiler compiled the following line:
Bookmarks