簡體   English   中英

將const int分配給指向int的const指針是非法的嗎?

[英]Assigning const int to a const pointer to int is illegal?

為什么以下違法?

extern const int size = 1024;

int * const ptr = &size;

當然,應該允許指向非const數據的指針指向const int(反之亦然)嗎?

這是來自C ++ Gotchas項目#18

如果您真的是其中之一

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

那是合法的。 你的是非法的。 因為那不是你能做的

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

和bah,您的常量剛剛被更改。

讓我們看看另一種方式:

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!

幸運的是,以上內容是不允許的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM