簡體   English   中英

指向 const 雙指針參數的非常量指針參數

[英]non-const pointer argument to a const double pointer parameter

C++中star之前的const修飾符意味着使用這個指針指向的值不能改變,而指針本身可以指向別的東西。 在下面

void justloadme(const int **ptr)
{
    *ptr = new int[5];
}

int main()
{
    int *ptr = NULL;
    justloadme(&ptr);
}

不應允許justloadme函數編輯由傳遞的參數指向的整數值(如果有),而它可以編輯 int* 值(因為 const 不在第一顆星之后),但仍然為什么我會收到編譯器錯誤在 GCC 和 VC++ 中?

GCC:錯誤:從int**const int**無效轉換

VC++:錯誤 C2664:“justloadme”:無法將參數 1 從“int **”轉換為“const int **”。 轉換失去了限定符

為什么說轉換丟失了限定符? 它不是獲得了const限定符嗎? 此外,它是不是類似於strlen(const char*)我們傳遞一個非常量char*

大多數時候,編譯器是對的,而直覺是錯的。 問題是,如果允許該特定分配,您可能會破壞程序中的常量正確性:

const int constant = 10;
int *modifier = 0;
const int ** const_breaker = &modifier; // [*] this is equivalent to your code

*const_breaker = & constant;   // no problem, const_breaker points to
                               // pointer to a constant integer, but...
                               // we are actually doing: modifer = &constant!!!
*modifier = 5;                 // ouch!! we are modifying a constant!!!

標有 [*] 的行是該違規行為的罪魁禍首,因該特定原因而被禁止。 該語言允許將 const 添加到最后一級,但不允許添加到第一級:

int * const * correct = &modifier; // ok, this does not break correctness of the code

暫無
暫無

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

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