const转换为全局var和程序崩溃(C ++) [英] const cast to a global var and program crashed (C++)
问题描述
int main()
{
const int maxint=100;//The program will crash if this line is put outside the main
int &msg=const_cast<int&>(maxint);
msg=200;
cout<<"max:"<<msg<<endl;
return 0;
}
如果'const int maxint = 100;'定义函数将运行ok被放置在主函数内部,但是崩溃并弹出一个错误消息,如果放在外面,说访问违反。
The function will run ok if the 'const int maxint=100;' definition is put inside the main function but crash and popup a error message said "Access Violation" if put outside.
有人说这是一种未定义的行为想知道确切的答案,以及我如何可以安全地使用const转换?
Someone says it's some kind of 'undefined behavior', and i want to know the exact answer and how i can use the const cast safely?
推荐答案
它们是正确的,你不允许修改 const
变量的值,这是抛弃 const
的危险:这不是真的 const
。
They are correct, it is undefined behaviour. You're not allowed to modify the value of a const
variable, which is the danger of casting away the const
ness of something: you better know it's not really const
.
编译器, maxint
是 const
并且应该永远不会被修改,甚至不必给它的地址。它可以替换 maxint
的所有用法,如果它看上去合适的话。也可能只是把常量放在一部分只读的内存中,正如Matteo Italia指出的,这可能是你发生了什么。这是为什么修改它会产生未定义的行为。
The compiler, seeing that maxint
is const
and should never be modified, doesn't even have to give it an address. It can just replace all the uses of maxint
with 100 if it sees fit. Also it might just put the constant in to a portion of memory that is read-only, as Matteo Italia points out, which is probably what's happening for you. That's why modifying it produces undefined behaviour.
你可以安全地抛弃变量的 const
是如果变量实际上不是 const
,但 const
限定符添加到非 - const
变量,如下所示:
The only way you can safely cast away the const
ness of a variable is if the variable is not actually const
, but the const
qualifier was added to a non-const
variable, like this:
int f(const int& x) {
int& nonconst = const_cast<int&>(x);
++nonconst;
}
int blah = 523;
f(blah); // this is safe
const int constblah = 123;
f(constblah); // this is undefined behaviour
想想这个例子,它完美编译:
Think about this example, which compiles perfectly:
int f(const int& x) {
int& nonconst = const_cast<int&>(x);
++nonconst;
}
int main() {
f(4); // incrementing a number literal???
}
你可以看到如何使用 const_cast
是非常危险的,因为没有办法实际告诉变量是否原来 const
或不。你应该避免在可能的情况下使用 const_cast
(通过不接受 const
参数的函数)。
You can see how using const_cast
is pretty dangerous because there's no way to actually tell whether a variable is originally const
or not. You should avoid using const_cast
when possible (with functions, by just not accepting const
parameters).
这篇关于const转换为全局var和程序崩溃(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!