|
-
April 10th, 2013, 06:55 PM
#2
Re: How does const_cast<> work?
 Originally Posted by vincegata
const_cast<> supposed to "cast away const" but it does not. The output is: 1002 1001, I expect it to be 1002 1002. Could someone explain what's going on? Thx.
Code:
#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
const int ci = 1001;
int* i1 = const_cast<int*>(&ci);
*i1 = 1002;
cout << *i1 << " " << ci << endl;
return 0;
}
Your program is ill-formed. According to the standard, you are not allowed to assign to the result of a const_cast when the original is defined as const. "Casting away const" just means that you are circumventing the type system. You are not changing any actual characteristics of the data in your program. The only real use for it is when you need to use a C interface that does not support const. But you should only use it when you are sure that the result of the const_cast will not be written to.
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
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
|