首页 > 技术文章 > 关于const的一个有趣的现象

lijianlin1995 2014-02-18 23:07 原文

先上代码

#include <iostream>

using namespace std;

int main()
{
    // vector<int>::iterator it=const_cast<  vector<int>::iterator >(v.begin());
    // vector<const int>::iterator it=(v.begin());

    const int a=0;
    int &b=const_cast<int&>(a);
    //int &b=(int &)a;这个也可以
    b=10;
    cout<<a<<','<<b<<endl;
    cout<<&a<<','<<&b<<endl;

    const int c=0;
    int* d=const_cast<int*>(&c);
    // int *d=(int *)&c;
    *d=10;
    cout<<c<<','<<*d<<endl;
    cout<<&c<<','<<d<<endl;

    return 0;
}

输出0 10 并且两个&c跟d是同一个值

怀疑是编译优化把输出改成字面常量了,但是用gcc编译时开o0和-E发现跟猜想并不一样,确实是输出变量。

1 既然编译器允许去掉const修饰符,那通过指针或者引用修改const变量会发生什么?

2 如果是采取了修改const变量新开辟一块儿内存,那为什么地址一样?如果是在原来的地址修改了变量的值,为什么输出c和*d不是同一个值?

这种现象就是 常量折叠。。。

所以大概const修饰符就是在语义层面的,运行时某块内存,某个数据没有const的修饰,只是在编译阶段,会对变量进行检查。

推荐阅读