Getting the same value of the const variable even after changing it through const_cast

前端 未结 5 1208
我在风中等你
我在风中等你 2021-01-21 23:47

Consider the below code snippet:

int main()
{
    const int i=3;
    int *ptr;

    ptr=const_cast(&i);
    *ptr=5;

    cout<<\"i= \"<&         


        
相关标签:
5条回答
  • 2021-01-22 00:27

    It's not an optimization. An optimization is the transformation of a program into another program that has the same behaviour, but uses less resources. Your program does not have any defined behaviour, so you can't possibly apply any transformation to it that yields the same behaviour.

    0 讨论(0)
  • 2021-01-22 00:38

    I hade same problem, I added volatile, now it's modifying:

    #include<iostream>
    using namespace std;
    
    int main()
    {
      volatile const int a=5;
      int *p = const_cast<int*>(&a);
      *p=6;
      cout<<"a="<<a;
      return 0;
    }
    

    Output:

    a=6
    

    volatile tells compiler that the identifier can be modified (if not by this code then by some one else, so do not perform any optimization)

    0 讨论(0)
  • 2021-01-22 00:40

    Is it any compiler optimization mechanism that compiler replaces the variable in the program with the value?

    Yes; that will be why you don't see the value changing. The behaviour of trying to modify a const object is left undefined in order to allow optimisations like that (as well as allowing the objects to be placed in unwritable memory).

    0 讨论(0)
  • 2021-01-22 00:42

    Most likely since it is a const int, the compiler is optimizing and directly replacing it with the value of i.

    0 讨论(0)
  • 2021-01-22 00:43

    i could be stored in a protected area of memory for ptr to point to. Of course anything can be the case, which is why it's undefined - which basically means don't depend on any particular behaviour occurring if you do try to trigger undefined behaviour.

    For all you know it could cause your computer to go into cardiac arrest or start shooting out laser beams, but you never know because it's ... (w a i t _ f o r _ i t) ... undefined ;).

    0 讨论(0)
提交回复
热议问题