3

Im having trouble understanding the meaning of const int* const &alias_for_ptr = ptr; with regards to the 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 is it that ptr == alias_for_ptr returns false, (in fact alias_for_ptr retains its old value of &a)? I was under the impression that alias_for_ptr will always have the same value as ptr (though the use of the & symbol) and that const int* const X = Y only ensures that I cannot change both the value of X and the value pointed by X through that identifier X.

Also if I remove the second const then the script will not compile, which confuses me futher. Note that the compile error is: invalid initialization of reference of type ‘const int*&’ from expression of type ‘int*’.

tmoschou
  • 977
  • 1
  • 8
  • 11

1 Answers1

2

Which compiler are you using? I've compiled under MSVC++ 2010, and it works as you expect.

I think what's happening is a temporary is being assigned to a const-reference, since the type of "ptr" is converted from "int*" to a "const int*". What happens if you remove the first const?

EDIT: Read here for more on references: Reference initialization in C++.

Community
  • 1
  • 1
axw
  • 6,908
  • 1
  • 24
  • 14
  • I think your right. Im using g++, if I remove the first const, then it works as expected, also if I add a const to the line above so its `const int* ptr = &a;` then it also works. Is there a way to do without adding/removing those two consts? I've tried using the `const_cast` operator but with no luck. Prehaps its a bug with g++. – tmoschou Dec 19 '10 at 09:38