将const int分配给指向int的const指针是非法的吗?

use*_*112 1 c++ pointers const

以下为什么违法?

extern const int size = 1024;

int * const ptr = &size;
Run Code Online (Sandbox Code Playgroud)

当然应该允许指向非const数据的指针指向一个const int(只是不是相反)?

这是来自C++ Gotchas项目#18

Bal*_*Pal 6

如果你真的是指其中一个

const int * const ptr = &size; 
const int * ptr = &size;
Run Code Online (Sandbox Code Playgroud)

这是合法的.你的是非法的.因为它不是你能做到的

int * ptr const = &size;
*ptr = 42;
Run Code Online (Sandbox Code Playgroud)

而且,你的const刚刚改变了.

让我们看看另一种方式:

int i = 1234; // mutable 
const int * ptr = &i; // allowed: forming more const-qualified pointer
*i = 42; // will not compile
Run Code Online (Sandbox Code Playgroud)

我们不能在这条道路上造成伤害.