常量是一个谎言? (因为常量可以被抛弃) [英] Is const a lie? (since const can be cast away)

查看:142
本文介绍了常量是一个谎言? (因为常量可以被抛弃)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  我推销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 correctness

What is the usefulness of keyword const in C or C++ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆