簡體   English   中英

為什么我不能在賦值的右側放置指向const的指針?

[英]Why can't I put a pointer to const on right hand side of assignment?

為什么我不能在賦值的右側放置const int *cp1 請看這個樣本

int x1 = 1;
int x2 = 2;

int *p1 = &x1;
int *p2 = &x2;

const int *cp1 = p1;

p2 = p1;    // Compiles fine

p2 = cp1;   //===> Complilation Error

為什么我在指定位置出錯? 畢竟我不想改變一個常量值,我只是試圖使用一個常量值。

我在這里錯過了一些東西。

畢竟我不想改變一個恆定的值

不允許從“指針指向const”到“指向非const指針”的隱式轉換,因為它可以更改常量值。 考慮以下代碼:

const int x = 1;
const int* cp = &x; // fine
int* p = cp;        // should not be allowed. nor int* p = &x;
*p = 2;             // trying to modify constant (i.e. x) is undefined behaviour

BTW:對於你的示例代碼,使用const_cast會很好,因為cp1實際上指的是非const變量(即x1 )。

p2 = const_cast<int*>(cp1);

暫無
暫無

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

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