non-const pointer argument to a const double pointer parameter

后端 未结 1 1161
小蘑菇
小蘑菇 2020-12-11 05:00

The const modifier in C++ before star means that using this pointer the value pointed at cannot be changed, while the pointer itself can be made to point someth

相关标签:
1条回答
  • 2020-12-11 05:45

    As most times, the compiler is right and intuition wrong. The problem is that if that particular assignment was allowed you could break const-correctness in your program:

    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!!!
    

    The line marked with [*] is the culprit for that violation, and is disallowed for that particular reason. The language allows adding const to the last level but not the first:

    int * const * correct = &modifier; // ok, this does not break correctness of the code
    
    0 讨论(0)
提交回复
热议问题