Address of a reference

限于喜欢 提交于 2019-12-19 11:21:39

问题


So I am having a discussion with a friend about reference and pointers.

What we got talking about is "you can take an address of a pointer but you cant take an address of a reference"

And I disagree on that point. lets take an example:

int x = 0;
int &xRef = x;
cout << &xRef << &x <<endl;

this example shows the same address, but never the less ain't I taking the address of xRef by doing &xRef. Couldn't you argue that we have 2 variables with the same address, so even though I am taking the address of the reference, it is still the address of the reference (even though that is the address of x)?


回答1:


The unary operator & returns the address of the designated object. Reference is not an object. It is reference to object. So this statement

cout << &xRef << &x <<endl;

outputs in the both cases the address of the designated object that is of x. Even though the compiler can allocate memory for a reference the reference itself has no address That is you can not apply operator & that to get its address. It is the object (or a function) that is referenced to by a reference that has an address.




回答2:


C++ Standard n3337 § 8.3.2/4

It is unspecified whether or not a reference requires storage (3.7).

So this is unspecified whether reference has storage. Most probably not. It is just alias. When you use it in the code it follows that special operations are taken by compiler, it might do some things similar to pointer operations.




回答3:


You can think of references as aliases for objects. So, in your example, &xRef declares xRef which is another name for x. Hence you're printing twice the adress of the same object.




回答4:


By the time you apply the address-of operator in your example, there is no distinction between the reference and the real object anymore. The reference is the object.

The rule instead applies at the moment you try to declare a pointer to a reference. Try it:

int x = 0;
int &*ptr = &x;

Result with MSVC 2013:

error C2528: 'ptr' : pointer to reference is illegal



回答5:


Just for completenesses sake: There is a way to produce a pointer to a reference.

auto foo(int &x){
    return [&]{std::cout << x;};
}

What the compiler is allowed to do here is not to capture a reference tox but to capture the stack pointer instead. Based on the stack pointer the compiler knows the offsets to the various parameters of foo and may save some memory for the lambda. However, after the lambda has been returned the parameters of foo are gone and the lambda references objects that do not exist. Therefore it is forbidden / UB to do this.



来源:https://stackoverflow.com/questions/23959119/address-of-a-reference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!