問題描述
我知道使用 const_cast
通常是個壞主意,但我在玩它時遇到了一個奇怪的行為,其中:
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.
有人對此有解釋嗎?
代碼
#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;
}
輸出
MPtr = 0x7fff9b4b6ce0 (*MPtr) = 11
&M = 0x7fff9b4b6ce0 M = 10
推薦答案
所以,除了它是未定義的行為"(它是)之外,編譯器完全可以使用 M
是一個常數,因此在 cout ... << 的評估中不會改變.M<<...
,因此可以使用立即數為 10 的指令,而不是 M
內存中存儲的實際值.(當然,標準不會說這是如何工作的,更多的是未定義",并且編譯器能夠在不同的情況下選擇不同的解決方案等等,所以如果你修改,你完全有可能得到不同的結果代碼,使用不同的編譯器,不同版本的編譯器或風向不同的方向吹).
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.
是的,這也是您不應該使用 const_cast
的原因之一.至少不是那些最初是 const
的東西——如果你有這樣的東西就可以了:
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);
在這種情況下,x
實際上并不是 const,當我們將它傳遞給 func
時,它只是變成了 const.當然,編譯器可能仍然假設 x
在 func
中沒有改變,因此你可能會遇到問題......
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....
這篇關于const_cast 的奇怪行為的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!