How to get a pointer from a link?

There seem to be a lot of questions related to the pointer and the link, but I could not find what I want to know. Basically, an object is passed by reference:

funcA(MyObject &objRef) { ... } 

Inside a function, can I get a pointer to this object instead of a link? If I treat the objRef reference as an alias of MyObject , can &objRef give me a pointer to a MyObject? This does not seem likely. I'm confused.

Edit: upon closer inspection, objRef returns me a pointer to the object I need. Most of you gave me the correct information / answer, thank you very much. I went for the answer that seems most indicative in this case.

+43
c ++
Feb 13 '12 at 16:00
source share
6 answers

Yes, applying the operator address to the link matches the address of the source 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 
+67
Feb 13 2018-12-12T00:
source share

Any operator applied to a link is actually applicable to the object to which it refers ( ยง5 / 5 [expr] ); the link can be considered as a different name for the same object. Thus, accessing the link address will give you the address of the object to which it refers.

It is generally not indicated whether the link requires storage ( ยง8.3.2 / 4 [dcl.ref] ), and therefore it would be pointless to take the address of the link 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.

+27
Feb 13 2018-12-12T00:
source share

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

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

This works whether the operator& T overloads or not.

+22
Feb 13 '12 at 16:12
source share

Use the address operator in the link.

 MyObject *ptr = &objRef; 
+4
Feb 13 2018-12-12T00:
source share

Use the address-of ( & ) operator in the link.

 &objRef 

Like any other operator used for reference, this actually affects the mentioned object.

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

+4
Feb 13 '12 at 16:15
source share

In C ++, a link is a limited type of pointer. It can only be assigned once and can never be NULL. Links are most useful when used to indicate that a function parameter is passed by reference, where the address of the variable is passed. Without reference, the value of "Tale" is used instead.

-3
Feb 13 2018-12-12T00:
source share



All Articles