将nonconst的地址分配给const指针

时间:2015-04-07 02:14:51

标签: c++ pointers const

我正在研究指针,constness。我在某些方面感到困惑。我了解到在C ++中禁止将const的地址分配给nonconst指针,但是可以使用const_cast来解决。没关系。

但是,允许将非对象变量的地址分配给const指针。我不明白为什么允许它。请看下面的例子。在这个例子中,ptr是一个指向const int的指针。但是,ptr指向的值会发生变化。这里有一个矛盾,因为ptr指向的const int值会发生变化。你能解释一下这个矛盾,或者如果我错了,你能解释一下原因吗?

#include <iostream>
using namespace std;

int main() {

    int year = 2012;
    const int* ptr = &year;
    year=100;
    year=101;
    cout << *ptr;
    // 101 is printed, the value ptr points to change whenever year changes

    return 0;
}

2 个答案:

答案 0 :(得分:3)

如果您熟悉文件访问权限,那么使用指向const的指针有点像打开文件以进行只读。您将获得一个只能用于阅读的文件句柄,但这并不意味着该文件无法以其他方式更改。

类似地,当你有一个指向const的指针时,你有办法读取一个对象,但不能写。但是,这并不意味着该对象不能以其他方式写入。

答案 1 :(得分:1)

看看这个例子:

int year=5; // is allowed
//const int year=5;  // is also allowed

const int* ptr = &year;         // ptr points to const data, but has nonconst address
*ptr = 141;                     // its not allowed
++ptr;                          // allowed

int* const constPointer = &year; // ptr points to nonconst data, but has const adress
*constPointer = 8;              // allowed
++constPointer;                 // not allowed

// pointed value and pointer are const
const int* const constDataAndPointer = &year; // ptr points to const data, also has const adress
*constDataAndPointer = 124;     // not allowed
++constDataAndPointer;          // not allowed