Address of a reference

前端 未结 5 1086
北恋
北恋 2021-01-16 02:40

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 addr

相关标签:
5条回答
  • 2021-01-16 02:49

    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.

    0 讨论(0)
  • 2021-01-16 03:05

    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.

    0 讨论(0)
  • 2021-01-16 03:06

    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.

    0 讨论(0)
  • 2021-01-16 03:12

    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.

    0 讨论(0)
  • 2021-01-16 03:14

    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
    
    0 讨论(0)
提交回复
热议问题