将const int赋值给指向int的const指针是非法的

Assigning const int to a const pointer to int is illegal?

本文关键字:int const 指针 非法 赋值      更新时间:2023-10-16

为什么以下内容是非法的?

extern const int size = 1024;
int * const ptr = &size;

当然,应该允许指向非常量数据的指针指向常量int(而不是相反)?

这来自C++Gotchas项目#18

如果你真的是指

const int * const ptr = &size; 
const int * ptr = &size;

这是合法的。你的是违法的。因为它不是你可以做

int * ptr const = &size;
*ptr = 42;

啊,你的惊愕刚刚改变了。

让我们看看另一种方式:

int i = 1234; // mutable 
const int * ptr = &i; // allowed: forming more const-qualified pointer
*i = 42; // will not compile

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

如果允许指向非一致数据的指针指向const int,则可以使用指针更改const int的值,这将是不好的。例如:

int const x = 0;
int * const p = &x;
*p = 42;
printf("%d", x);  // would print 42!

幸运的是,以上情况是不允许的。