Weird Behaviour with const_cast
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?
Code
#include <iostream>
int main()
{
const int M = 10;
int* MPtr = const_cast<int*>(&M);
(*MPtr)++;
std::cout << "MPtr = " << MPtr << " (*MPtr) = " << (*MPtr) << std::endl;
std::cout << " &M = " << &M << " M = " << M << std::endl;
}
Output
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;
}
...
func(&x);
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....
5 плюса
The program has undefined bahaviour because you may not change a const object.
From the C++ Standard
Автор: Vlad from Moscow Размещён: 13.03.2014 09:364 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 ]
Вопросы из категории :
- c++ What are the barriers to understanding pointers and what can be done to overcome them?
- c++ Какой самый простой способ для анализа файла INI в C ++?
- c++ Когда вы должны использовать «друг» в C ++?
- c++ Как вы очищаете переменную stringstream?
- c++ В C ++ конструктор и деструктор могут быть встроенными функциями?
- c++ Что такое виртуальный базовый класс в C ++?
- pointers Как вы передаете функцию в качестве параметра в C?
- pointers Regular cast vs. static_cast vs. dynamic_cast
- pointers Каковы различия между переменной-указателем и ссылочной переменной в C ++?
- pointers Почему я не могу конвертировать 'char **' в 'const char * const *' в C?
- pointers Что такое умный указатель и когда я должен его использовать?
- casting Приведите int к перечислению в C #
- casting Синтаксические стили C ++
- casting Приведение списка <int> в список <string> в .NET 2.0
- casting Зачем использовать static_cast <int> (x) вместо (int) x?
- casting Прямое приведение против оператора "как"?