We all know that the const object is used to declare a variable as a constant. It cannot be modified unless the conversion is displayed in the program.
This article reminds you of an implicit error and a solution to this problem.
Consider the following code:
# Include <iostream> int main () {const int A = 0; int * P = const_cast <int *> (& A); // & A returns int *, const_cast <int *> display to int *. * p = 1; int B = * P; int c = A; STD: cout <"B:" <B <STD: Endl <"C: "<C <STD: Endl; STD: cout <& A <" "<p <STD: Endl; return 0 ;}
The output result is:
B: 1
C: 2
0x7fffe27cd63c 0x7fffe27cd63c
The problem is here! We obviously changed the value of A, and the address pointed to by the pointer is the same as the address of the variable.
This is so horrible. We changed the value of a through * P, but the result of the next use of a remains unchanged. This reminds us again that we should not use forced type conversion easily, which will often lead to some errors that we cannot perceive.
It is easy to solve this problem. Use the volatile modifier to force variable A to read the latest data in the memory each time it is accessed.
# Include <iostream> int main () {const volatile int A = 0; int * P = const_cast <int *> (& A); // & A returns int *, const_cast <int *> display to int *. * p = 1; int B = * P; int c = A; STD: cout <"B:" <B <STD: Endl <"C: "<C <STD: Endl; return 0 ;}
The output result is:
B: 1
C: 1
Some readers have come up with the reason: the compiler has replaced the symbol of the const object. The following uses the const object, instead of extracting the latest value from the memory.