开发者

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

开发者 https://www.devze.com 2023-01-31 02:41 出处:网络
Im having trouble understanding the meaning of const int* const &alias_for_ptr = ptr; with regards to the following:

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 compi开发者_运维知识库le error is: invalid initialization of reference of type ‘const int*&’ from expression of type ‘int*’.


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++.

0

精彩评论

暂无评论...
验证码 换一张
取 消