Weird Behaviour with const_cast

c++ pointers casting

441 просмотра

2 ответа

I know that using const_cast is generally bad idea, but I was playing around with it and I came across a weird behaviour, where:

Two pointers have the same address value, yet when de-referenced, give different data values.

Does anyone have an explanation for this?


#include <iostream>

int main()
    const int M = 10;

    int* MPtr = const_cast<int*>(&M);


    std::cout << "MPtr = " << MPtr << "   (*MPtr) = " << (*MPtr) << std::endl;
    std::cout << "  &M = " << &M << "         M = " << M << std::endl;


MPtr = 0x7fff9b4b6ce0   (*MPtr) = 11
  &M = 0x7fff9b4b6ce0         M = 10
Автор: MGA Источник Размещён: 13.11.2019 11:33

Ответы (2)

2 плюса


So, aside from the "it's undefined behaviour" (which it is), the compiler is perfectly fine to use the fact that M is a constant, thus won't change, in the evaluation of cout ... << M << ..., so can use an instruction that has the immediate value 10, instead of the actual value stored in the memory of M. (Of course, the standard will not say how this works, more than "it's undefined", and compilers are able to choose different solutions in different circumstances, etc, etc, so it's entirely possible that you'll get different results if you modify the code, use a different compiler, different version of compiler or the wind is blowing in a different direction).

Part of the tricky bit with "undefined behaviour" is that it includes things that are "perfectly what you may expect" as well as "nearly what you'd expect". The compiler could also decide to start tetris if it discovers this is what you are doing.

And yes, this is very much one of the reasons why you SHOULD NOT use const_cast. At the very least NOT on things that were originally const - it's OK if you have something along these lines:

int x;

void func(const int* p)
  int *q = const_cast<int *>(p);

  *q = 7;



In this case, x is not actually const, it just becomes const when we pass it to func. Of course, the compiler may still assume that x is not changed in func, and thus you could have problems....

Автор: Mats Petersson Размещён: 13.03.2014 09:42

5 плюса

The program has undefined bahaviour because you may not change a const object.

From the C++ Standard

4 Certain other operations are described in this International Standard as undefined (for example, the effect of attempting to modify a const object). [ Note: This International Standard imposes no requirements on the behavior of programs that contain undefined behavior. —end note ]

Автор: Vlad from Moscow Размещён: 13.03.2014 09:36