#include <iostream> #include <stdio.h> using namespace std; class A{ public: void fun(int& temp){cout<<"am inside fun()"<<endl; temp = 2000; printf("in fun() temp[%p] temp val[%d]\n",&temp, temp); } };const int temp=100;int main() { A a; printf("in main() temp[%p] temp val[%d]\n",&temp, temp); a.fun(const_cast<int&>(temp)); cout<<"temp:"<<temp<<endl; }This will generate an error. The reason is that the constant variable temp does not have physical storage:http://stackoverflow.com/questions/8290132/is-memory-allocated-for-a-static-const-variable-whose-address-is-never-usedHowever, if you put temp inside main int main(){const int temp=100;...} Its behaviour will be large undefined. Since using const_cast to cast away const ness and reassign the value may or may not change the value itself.
Sunday, February 3, 2013
const and const_cast
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment