Unhandled exception while over-writing value after removing constness

94 views Asked by At

Below is the code :-

const int temp=100;

class A
{
public:
    void fun(int& temp)
    {
        cout<<"am inside fun()"<<endl;
        temp = 2000;            <<<<<<<<<<<<<<Here getting exception....
        printf("in fun() temp[%p] temp val[%d]\n",&temp, temp);
    }
};

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;
    system("pause");
    return 0;
}

In this case it's not allowing me to overwrite temp in fun even when I explicitly removed the constness. When I declare temp inside main everything is fine i.e it allows me to overwrite that value in fun.

Compiled in VS2008.

Can anyone help me figure out the behavioral difference between these two scenarios.

3

There are 3 answers

2
Tony Delroy On BEST ANSWER

The difference is that the global variable's likely to be located in a read-only memory segment, so attempts to modify it will may be trapped by the CPU, while a local non-static const variable's likely to be put in a CPU register or on the stack where it's possible to modify it. That said, you should avoid changing variables defined as const, and only use const_cast to regain write access to variable that was initially defined as non-const.

0
Cheers and hth. - Alf On

Casting away an original const and attempting a modification is Undefined Behavior.

You are not guaranteed to get an exception, but your are lucky to get one.

1
M.M On

Attempting to modify a const object causes undefined behaviour.

You cannot "remove the constness" of a const object.

In this case, your compiler is being nice to you by generating an exception, instead of just behaving weirdly and continuing.