常量是一个谎言? (因为常量可以被抛弃) [英] Is const a lie? (since const can be cast away)
问题描述
可能重复:结果
我推销const正确性
块引用>什么是关键字的用处
在
或ç常量
C ++
,因为它是允许这样的事情?无效const_is_a_lie(const int的* N)
{
*(为(int *)N)= 0;
}诠释的main()
{
INT N = 1;
const_is_a_lie(安培; N);
的printf(%d个,N);
返回0;
}
输出:0
块引用>很显然,
常量
不能保函参数的非可修改性。解决方案
常量
是您对编译器的承诺,不是它保证你。例如,
无效const_is_a_lie(const int的* N)
{
*(为(int *)N)= 0;
}#包括LT&;&stdio.h中GT;
诠释的main()
{
const int的N = 1;
const_is_a_lie(安培; N);
的printf(%d个,N);
返回0;
}在 http://ideone.com/Ejogb 显示输出为
1
块引用>由于该
常量
中,编译器允许假设的价值不会改变,因此它可以跳过重读它,如果这将使程序更快在此情况下,由于
const_is_a_lie()
违反合同,奇怪的事情发生了。不违反合同。和高兴的是,编译器给你帮助保持合同。石膏是邪恶的。Possible Duplicate:
Sell me on const correctnessWhat is the usefulness of keyword
const
inC
orC++
since it's allowed such a thing?void const_is_a_lie(const int* n) { *((int*) n) = 0; } int main() { int n = 1; const_is_a_lie(&n); printf("%d", n); return 0; }
Output: 0
It is clear that
const
cannot guarante the non-modifiability of the argument.解决方案
const
is a promise you make to the compiler, not something it guarantees you.For example,
void const_is_a_lie(const int* n) { *((int*) n) = 0; } #include <stdio.h> int main() { const int n = 1; const_is_a_lie(&n); printf("%d", n); return 0; }
Output shown at http://ideone.com/Ejogb is
1
Because of the
const
, the compiler is allowed to assume that the value won't change, and therefore it can skip rereading it, if that would make the program faster.In this case, since
const_is_a_lie()
violates its contract, weird things happen. Don't violate the contract. And be glad that the compiler gives you help keeping the contract. Casts are evil.这篇关于常量是一个谎言? (因为常量可以被抛弃)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!