How to get a pointer from a reference?

后端 未结 6 870
野趣味
野趣味 2020-12-07 20:22

There seems to be many relavent questions talking about pointer vs. reference, but I couldn\'t find what I want to know. Basically, an object is passed in by a reference:

相关标签:
6条回答
  • 2020-12-07 20:23

    The general solution is to use std::addressof, as in:

    #include <type_traits>
    
    void foo(T & x)
    {
        T * p = std::addressof(x);
    }
    

    This works no matter whether T overloads operator& or not.

    0 讨论(0)
  • 2020-12-07 20:26

    Any operator applied to a reference will actually apply to the object it refers to (§5/5 [expr]); the reference can be thought of as another name for the same object. Taking the address of a reference will therefore give you the address of the object that it refers to.

    It as actually unspecified whether or not a reference requires storage (§8.3.2/4 [dcl.ref]) and so it wouldn't make sense to take the address of the reference itself.

    As an example:

    int x = 5;
    int& y = x;
    int* xp = &x;
    int* yp = &y;
    

    In the above example, xp and yp are equal - that is, the expression xp == yp evaluates to true because they both point to the same object.

    0 讨论(0)
  • 2020-12-07 20:26

    In C++, a reference is a restricted type of pointer. It can only be assigned once and can never have a NULL value. References are most useful when used to indicate that a parameter to a function is being Passed by Reference where the address of the variable is passed in. Without a Reference, Pass By Value is used instead.

    0 讨论(0)
  • 2020-12-07 20:29

    Use the address-of (&) operator on the reference.

    &objRef
    

    Like any other operator used on a reference, this actually affects the referred-to object.

    As @Kerrek points out, since the operator affects the referred-to object, if that object has an overloaded operator& function, this will call it instead and std::address_of is needed to get the true address.

    0 讨论(0)
  • Yes, applying the address-of operator to the reference is the same as taking the address of the original object.

    #include <iostream>
    
    struct foo {};
    
    void bar( const foo& obj )
    {
      std::cout << &obj << std::endl;
    }
    
    int main()
    {
      foo obj;
      std::cout << &obj << std::endl;
      bar( obj );
    
      return 0;
    }
    

    Result:

    0x22ff1f
    0x22ff1f
    
    0 讨论(0)
  • 2020-12-07 20:43

    Use the address operator on the reference.

    MyObject *ptr = &objRef;
    
    0 讨论(0)
提交回复
热议问题