-
January 29th, 2010, 07:42 AM
#1
const_cast does not modify variables value
const int z = 10;
const int *x = &z;
*const_cast <int *> (x) = 1;
const int &ref = z;
const_cast<int &> (ref) = 15;
cout<< "z= " << z;
cout <<"*x ="<<*x;
cout << "ref = "<<ref;
Output seen
z = 10
*x = 15;
ref = 15
how can z be 10 if its reference and value at its address is 15. is a separate copy of z kept ?
-
January 29th, 2010, 08:07 AM
#2
Re: const_cast does not modify variables value
If I remember correctly, you are looking at the result of undefined behaviour: that of trying to modify something that is really const.
-
January 29th, 2010, 08:26 AM
#3
Re: const_cast does not modify variables value
Laserlight is correct, undefined behaviour
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
-
January 29th, 2010, 01:10 PM
#4
Re: const_cast does not modify variables value
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:
As if it were written as:
Code:
cout<< "z= " << 10;
Viggy
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|