Problem with: 'const int * const & alias_for_ptr = ptr;', why do both identifiers have different values?

It’s hard for me to make sense of the const int* const &alias_for_ptr = ptr; following:

#include <iostream>
using namespace std;

int main() {

    int a = 10;

    int* ptr = &a;
    const int* const &alias_for_ptr = ptr;

    ptr = NULL; //or ptr = 0;

    if (ptr == alias_for_ptr)
        //This should execute but doesn't
        cout << "ptr == alias_for_ptr" << endl;
    else
        //This should NOT execute but DOES
        cout << "ptr != alias_for_ptr" << endl;
    return 0;

}

Why ptr == alias_for_ptrreturns false (actually alias_for_ptrsaves the old value &a)? I got the impression that alias_for_ptrit will always have the same meaning as ptr(although the use of the symbol and symbol), and that const int* const X = Yonly guarantees that I can not change both the value Xand the specified value Xthrough this identifier X.

Also, if I delete the second const, then the script will not compile, which confuses me further. Note that the compiler error: invalid initialization of reference of type β€˜const int*&’ from expression of type β€˜int*’.

+3
1

? MSV++ 2010, , .

, , const-, "ptr" "int *" "const int *". , const?

: : ++.

+2

Source: https://habr.com/ru/post/1781092/


All Articles