将非常量的地址分配给常量指针

Assigning the address of nonconst to a const pointer

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

但是,允许将非常量变量的地址分配给常量指针。我不明白为什么允许这样做。请看下面的例子。在此示例中,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;
}

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

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

看这个例子:

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