Question

I tried executing the following program.

#include<iostream>
using namespace std;
int main()
{
const int a = 0;
cout << &a <<endl;
int* ptr = const_cast<int*>(&a);
*ptr = 2;
cout << ptr <<endl;
cout << *ptr <<endl;
cout << a <<endl;
return 0;
}

The output was:

   0xbf92ebd8
   0xbf92ebd8
   2
   0

From what I know, const_cast makes a mutable, so that, it can be changed. The change is reflected when I display *ptr, but the change is not reflected in a. Can anyone explain ?

EDIT: Thanks for all the answers. I get it that I am observing an undefined behavior. And, I was initially confusing between mutable and *const_cast*. But then, could you tell me for what all scenarios, do we use const_cast?

Was it helpful?

Solution

From C++03 5.2.1 const_cast /7:

[Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier may produce undefined behavior (7.1.5.1). ]

In 7.1.5.1 The cv-qualifiers /4:

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

And, in the terms and definitions section:

[Note: permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

Minor changes have been made in the latest standard but the general idea still holds. Bottom line, don't do that.

OTHER TIPS

C++11 Standard says:

7.1.6.1
(...)
4 Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

That means, that you cannot expect anything, when attempting to do this. It may work, it may not, exception may be thrown, program may be terminated, depending on how designers of your compiler designed it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top